22/02/2012

OWASP top 10 Common Vulnerabilities....What? (Part 2)

This article is the second part of OWASP top 10 Common vulnerabilities...

HTTP Header Injection



Vulnerability Description: 

This post is the second part of the series OWASP what? and focuses explaining how OWASP categorizes vulnerabilities. So HTTP header injection is a general class of web application security vulnerability which occurs when Hypertext Transfer Protocol (HTTP) headers are dynamically generated based on user input. Header injection in HTTP responses can allow for HTTP response splitting, Session fixation via the Set-Cookie header, cross-site scripting (XSS), and malicious redirects attacks via the location header. HTTP header injection is a relatively new area for web-based attacks, and has primarily been pioneered by Amit Klein in his work on request/response smuggling/splitting. During the web application penetration test, we managed to successfully inject HTTP headers on to the server’s responses.

Impact:

Various kinds of attack can be delivered via HTTP header injection vulnerabilities. Any attack that can be delivered via cross-site scripting can usually be delivered via header injection, because the attacker can construct a request which causes arbitrary JavaScript to appear within the response body. Further, it is sometimes possible to leverage header injection vulnerabilities to poison the cache of any proxy server via which users access the application. Here, an attacker sends a crafted request which results in a "split" response containing arbitrary content. If the proxy server can be manipulated to associate the injected response with another URL used within the application, then the attacker can perform a "stored" attack against this URL which will compromise other users who request that URL in future.

Recommendations:

Investigate all uses of HTTP headers, such as

1. Setting cookies
2. Using location (or redirect() functions)
3. Setting mime-types, content-type, file size, etc.
4. Setting custom headers

If these contain Unvalidated user input, the application is vulnerable when used with application frameworks that cannot detect this issue. If the application has to use user-supplied input in HTTP headers, it should check for double “\n” or “\r\n” values in the input data and eliminate it (along with all it mutation, e.g. encoded return characters).

Many application servers and frameworks have basic protection against HTTP response splitting, but it is not adequate to task, and you should not allow Unvalidated user input in HTTP headers.
If possible, applications should avoid copying user-controllable data into HTTP response headers. If this is unavoidable, then the data should be strictly validated to prevent header injection attacks. In most situations, it will be appropriate to allow only short alphanumeric strings to be copied into headers, and any other input should be rejected. At a minimum, input containing any characters with ASCII codes less than 0x20 should be rejected.


References:

  1. https://www.owasp.org/index.php/Interpreter_Injection 
  2. http://en.wikipedia.org/wiki/HTTP_header_injection
  3. http://blogs.msdn.com/b/esiu/archive/2007/09/22/http-header-injection-vulnerabilities.aspx
Invalidated Redirects and Forwards

Vulnerability Description:

A web application takes a parameter and redirects a user to the parameter value, such a Web site, without validation. Attackers exploit this vulnerability with phishing e-mails that cause users to visit malicious sites inadvertently.

Impact: 

Invalidated redirects and forwards vulnerabilities arise when an application incorporates user-controllable data into the target of a redirection in an unsafe way. This behaviour can be leveraged to facilitate phishing attacks against users of the application. The ability to use an authentic application URL, targeting the correct domain with a valid SSL certificate (if SSL is used) lends credibility to the phishing attack because many users, even if they verify these features, will not notice the subsequent redirection to a different domain.

Recommendations:

Investigate all uses of HTTP headers, such as
1. Setting cookies
2. Using location (or redirect() functions)
3. Setting mime-types, content-type, file size, etc.
4. Setting custom headers
If these contain Unvalidated user input, the application is vulnerable when used with application frameworks that cannot detect this issue.
If the application has to use user-supplied input in HTTP headers, it should check for double “\n” or “\r\n” values in the input data and eliminate it (along with all it mutation, e.g. encoded return characters).
Many application servers and frameworks have basic protection against HTTP response splitting, but it is not adequate to task, and you should not allow Unvalidated user input in HTTP headers.
If possible, applications should avoid copying user-controllable data into HTTP response headers. If this is unavoidable, then the data should be strictly validated to prevent header injection attacks. In most situations, it will be appropriate to allow only short alphanumeric strings to be copied into headers, and any other input should be rejected. At a minimum, input containing any characters with ASCII codes less than 0x20 should be rejected.

References:
  1. https://www.owasp.org/index.php/Interpreter_Injection 
  2. http://en.wikipedia.org/wiki/HTTP_header_injection 
  3. http://blogs.msdn.com/b/esiu/archive/2007/09/22/http-header-injection-vulnerabilities.aspx

20/02/2012

OWASP top 10 Common Vulnerabilities....What? (Part 1)

For a long time now...

For a long time now there is a confusion about the common web application vulnerabilities and their countermeasures. This is post is going to clear out the meaning of some of the OWASP top 10 web app vulnerability categorization and provide you with countermeasures (it is going to be a long post).

The OWASP top 10 describes the most common web application vulnerabilities based on the risk, In order to clarify what Risk is and how is perceived from OWASP I am going to give you the definition of risk, so risk is:

"Risk is the potential that a chosen action or activity (including the choice of inaction) will lead to a loss (an undesirable outcome). The notion implies that a choice having an influence on the outcome exists (or existed). Potential losses themselves may also be called "risks". Almost any human endeavor carries some risk, but some are much more risky than others." [1]


The maths of risk is:

Risk = (probability of accident occurring) x (expected loss in case of accident)

Where accident is for example the SQL or LDAP injection and expected loss is more or less the impact. Now OWASP top 10 categorizes is injections as number one vulnerability because the impact of the injection is by far greater than the XSS impact.

e.g.  

SQL Injection Risk (low probability of accident occurring) x (expected high loss in case of accident)

XSS Risk (high probability of accident occurring) x (expected low loss in case of accident)


An example would be that of an SQL injection that results to loss of confidentiality and an XSS that results to user identity theft. The XSS vulnerability is occurring more often than SQL injection but the impact of the SQL injection is bigger.

Back to OWASP top 10


So the follwoing list represent the OWASP top 10:
  1. Injection (e.g. SQL, XML, LDAP injection)
  2. Cross Site Scripting (XSS) 
  3. Broken Authentication (e.g. bad session life-cycle )
  4. Insecure Direct Object Reference (e.g. access functionality with higher privilages)
  5. Cross-Site Request Forgery (CSRF)
  6. Security Misconfiguration (e.g. default admin panel password)
  7. Insecure cryptographic storage (e.g. usage of deprecated cryptographic algorithms)
  8. Failure to restrict URL access (e.g. broken access control)
  9. Un-Sufficient Transportation Layer Protection
  10. Unvalidated direct forwards and redirects (e.g. URL injection) 
So here is the analysis if each vulnerability:

Injection  (SQL Injection)

Impact:

Various attacks can be delivered via SQL injection, including reading or modifying critical application data, interfering with application logic, escalating privileges within the database and executing operating system commands.
An adversary can compromise the integrity, confidentiality and avaliability of the Web server. Also as a side effect costumer reputation can also be achived. An SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. The SQL injection exploit prodiced can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as execute stored procedures in the MSSql Server), recover the content of a given file present on the DBMS 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 effect the execution of predefined SQL commands.

Counter measures (for .NET): 

Make use of parameterized queries. Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.
Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of tom' or '1'='1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string tom' or '1'='1.


Primary Defenses:
  1. Use of Prepared Statements (Parameterized Queries)
  2. Use of Stored Procedures
  3. Escape all User Supplied Input
Additional Defenses:
  1. Also Enforce: Least Privilege (already applied).
  2. Also Perform: White List Input Validation.
  3. Also Disable: All unecesarry build in stored procedures.
  4. Also Remove: Execution rights from SQL (already applied but nat in all stored procedures).
  5. .NET specific recommendations:
  6. .NET – use parameterized queries like SqlCommand() or OleDbCommand() with bind variables
In rare circumstances, prepared statements can harm performance. When confronted with this situation, it is best to escape all user supplied input using an escaping routine specific to your database vendor as is described below, rather than using a prepared statement. Another option which might solve your performance issue is used a stored procedure instead.

Safe Coding with C# .NET Prepared Statement Example:

String query = "SELECT account_balance FROM user_data WHERE user_name = ?";
try {
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.Add(new OleDbParameter("customerName", CustomerName Name.Text));
OleDbDataReader reader = command.ExecuteReader();
// …
} catch (OleDbException se) {
// error handling


Note:You should be aware that some commonly employed and recommended mitigations for SQL injection vulnerabilities are not always effective:

  1. One common defense is to double up any single quotation marks appearing within user input before incorporating that input into a SQL query. This defense is designed to prevent malformed data from terminating the string in which it is inserted. However, if the data being incorporated into queries is numeric, then the defense may fail, because numeric data may not be encapsulated within quotes, in which case only a space is required to break out of the data context and interfere with the query. Further, in second-order SQL injection attacks, data that has been safely escaped when initially inserted into the database is subsequently read from the database and then passed back to it again. Quotation marks that have been doubled up initially will return to their original form when the data is reused, allowing the defense to be bypassed.
  2. Another often cited defense is to use stored procedures for database access. While stored procedures can provide security benefits, they are not guaranteed to prevent SQL injection attacks. The same kinds of vulnerabilities that arise within standard dynamic SQL queries can arise if any SQL is dynamically constructed within stored procedures. Further, even if the procedure is sound, SQL injection can arise if the procedure is invoked in an unsafe manner using user-controllable data.
Injection (Blind SQL Injection)



Impact:

Blind SQL Injection is used when a web application is vulnerable to an SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.

In the first url the Referer HTTP header might be vulnerable to SQL injection attacks. A single quote was submitted in the Referer HTTP header, and a general error message was returned. Two single quotes were then submitted and the error message disappeared. You should review the contents of the error message, and the application's handling of other input, to confirm whether vulnerability is present.

In the second url the password parameter appears to be vulnerable to SQL injection attacks. The payload 'waitfor%20delay'0%3a0%3a20'-- was submitted in the password parameter. The application took 20029 milliseconds to respond to the request, compared with 27 milliseconds for the original request, indicating that the injected SQL command caused a time delay.

Counter Measures: 



*** Same as SQL Injection ***



XSS 

Impact:

Cross-site scripting (XSS) allows malicious client-side script to be inserted into a response page returned by the application and that way make user traffic redirects or session hijacks and perform phi-sing scums or more simplistically speaking perform user impersonation or identity theft (the last one sounds more British e?).   


Counter Measures: 

Here is a list of the thinks that should be made:
  1. Make sure all un-trusted data (meaning all possible injection points) are properly sanitized, the following recommendations should be taken into consideration:
  2. Never Insert Untrusted Data Except in Allowed Locations
  3. HTML Escape Before Inserting Untrusted Data into HTML Element Content
  4. Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes
  5. JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values
  6. CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values
  7. URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values
  8. Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way
Based on OWASP recommendation it best to use an HTML Policy engine to validate or clean user-driven HTML in an outbound way (for more information check out the references).

OWASP AntiSamy sample code

import org.owasp.validator.html.*;

Policy policy = Policy.getInstance(POLICY_FILE_LOCATION);
AntiSamy as = new AntiSamy();
CleanResults cr = as.scan(dirtyInput, policy);
MyUserDAO.storeUserProfile(cr.getCleanHTML()); // some custom function

OWASP Java HTML Sanitizer sample code:

import org.owasp.html.Sanitizers;
import org.owasp.html.PolicyFactory;

PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
String cleanResults = sanitizer.sanitize("<p>Hello, <b>World!</b>");


References:
  1. https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
  2. http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/PercentCodec.java
  3. http://owasp-java-html-sanitizer.googlecode.com/svn/trunk/distrib/javadoc/org/owasp/html/Sanitizers.html
  4. Published ibrowser plugin XSS vulnerability: http://secunia.com/advisories/41634
  5. http://en.wikipedia.org/wiki/Risk (Wiki)