Monday, June 10, 2013

SQL Injection Prevention - Binding "IN" Clause Parameters

Most people know that using bound parameters is the best way to prevent SQL Injection vulnerabilities. However, the one place I still see problems are when developers need to utilize the IN clause:

However, it is possible to use bound parameters for use with an IN clause. If using SQL Server and ADO.NET one can use a user defined table type. Let's go through an example. First, we will create a sample table and populate some test data:

Next, I'll show how to create a user defined table type and use this in a stored procedure:

Finally, within your CSharp you can use the following code to bind the table type:

Using techniques like this one can bind correctly typed data when calling a stored procedure that uses an IN clause. Unfortunately, this functionality hasn't made it into Linq or the Entity Framework. If you are using Java and an Oracle DB there is similar functionality using arrays (one example can be found here).

Hopefully, people find this useful. Let me know if you have any questions.


Thursday, November 15, 2012

TLD Generator

I recently found a very useful project if you are building a Java library that contains tags or functions that you would like to expose within a JSP. TLD Generator - this tool allows one to configure your TLD by annotating your code and then it generates the TLD using an annotation processor. I thought that this was very useful so I worked with the author to get this published to maven central. If you wanted to use this in your maven project simply add a dependency like this:
The option element is key here in that Maven will not include the tld-generator as a dependent library - but it will put it on the class path during compile time so that the annotation processor will run. See the documentation on the TLD Generator's wiki for information how to annotate your code to generate the TLDs.

Wednesday, November 7, 2012

Remediation of XSS: Nested Contexts (part two)

In part one of this series I covered the correct use of JavaScript encoding and how this already covers the issue of the “nested” contexts. Now, onto a better solution – don’t use HTML Event attributes! Given the vulnerable code:
<div onclick="showError('<%=request.getParameter("error")%>')">
An error occurred, click here to see the details</div>
Instead of adding encoding to a complicated location within the DOM like the onclick event attribute - hook all of your events via JavaScript (example below uses JQuery):
<div id="errorBanner">An error occurred, click here to see the details
   <div id="errorDetails" style="display:none">
      <%=Encode.forHtml(request.getParameter("error")) %>
<script type="text/javascript">
The key here is to avoid placing dynamic data into "nested contexts" such as an event handler. This makes the remediation much simpler in many cases and lowers the amount of security knowledge a developer needs to understand how to fix the vulnerability.

The additional benefit of using JS to hook your events is that you can then externalize your JavaScript and define a Content Security Policy (CSP) for you site. CSP is by no means a magic bullet – but restrictive CSP policy can limit the damage potential of an XSS exploit.

Remediation of XSS: Nested Contexts (part one)

I have seen some solutions for XSS involving nested contexts that are not ideal. Partly because they are complicated and require a deep understanding of how the browser processes the HTML/DOM and they are likely inefficient; there are better solutions. This is the first post in a two part series.

First, what do I mean be nested contexts? Some examples would be writing dynamic data into an event handler such as onclick.
<div onclick="showError('<%=request.getParameter("error")%>')" >An error occurred, click here to see the details</div>
When the browser processes this it will first HTML decode the contents of the onclick attribute and then it will pass the results to the JavaScript Interpreter. As such, the advice I have seen (and previously given) is to apply “layered” encoding: 1) JavaScript encode and then 2) HTML Attribute Encode:
<div onclick="showError('<%= Encoder.encodeForHtml(Encoder.encodeForJavaScript( request.getParameter("error")%>')))" >An error occurred, click here to see the details</div>
Wow – that is completely unfriendly. Additionally, after thinking about this solution it seems unnecessarily complicated if you are using a robust JavaScript encoder (i.e. one that will JavaScript encode the '&' character) – then even though you are in an “HTML Attribute” context the following should be sufficient:
<div onclick="showError('<%= Encoder.encodeForJavaScript( request.getParameter("error")%>'))" >An error occurred, click here to see the details</div>
The reason that the above is sufficient is the Encode.forJavaScript will encode the '&' character so that when the browser HTML Decodes the attribute there is nothing to decode. However, this only applies to robust JavaScript encoders.

The encoder used above is from the OWASP Java Encoder Project.

Next post will cover refactoring the use of nested contexts rather than just encoding the data. As we will see, this has some very nice benefits.

Tuesday, January 10, 2012

Content Security Policy (CSP)

Content Security Policy (CSP) is a technology, that at the time of writting this is still a working draft, which will allow a web page to limit where external content can be loaded from. It allows the web page to define which domains image files, CSS files, JavaScript files, etc. can be loaded from. Additionally, inline JavaScript and style is not allowed; all JavaScript and style must be externalized. This externalization of JavaScript and style is the one feature I am most excited about; more on this later.

CSP has been discussed by others indicating it is not a complete solution to the XSS/Content Injection problem. A couple of the better posts about this are Postcards from the post-XSS world by Michal Zalewki and HTML scriptless attacks by Gareth Hayes. Both of these posts discuss what can be done with XSS/Injection Attacks that don’t require JavaScript. Even the introduction of the CSP draft states that it is “not intended as a first line of defense against content injection vulnerabilities.” Morale of the story, CSP will definitely help, but developers still need to validate input and encode output.

So why am I a big fan of CSP, specifically with regards to having to externalize JavaScript? Doing this means that several of the complicated encoding scenarios go away. Knowing what type of encoding to perform becomes, in the majority of cases, simple again. You no longer have event attributes such as onclick which will HTML decode the value of the attribute before passing the data to the JavaScript interpreter. With JavaScript externalized you no longer have the “javascript:” protocol used in HREFs, which are HTML Attribute decoded prior to determining what protocol is in use, then because the javascript protocol is used the data is URL Decoded prior to being passed to the JavaScript Interpreter. Basically, with JavaScript and style externalized you don’t have nested contexts where the web page is passing data through several different parsers!

Given the lack of nested contexts in the rendered HTML doesn’t mean all the XSS/Content Injection issues go away. Data still needs to be correctly encoded for whatever context it is being written to (see the OWASP XSS Prevention Cheat Sheet). Additionally, when using JavaScript to manipulate the DOM – this still needs to be done correctly using safe APIs such as setting innerText instead of innerHtml; there are several other articles discussing this so I’ll leave it at that.

I also believe there will be issues with dynamically generated style sheets and JavaScript (e.g. the CSS and JavaScript being generated by templating technologies such as JSP so that dynamic data can be inserted). However, I still believe overall it becomes easier to choose the correct encoding and filtering techniques when writting data into these types of files.
CSP can limit the damage potential of XSS/Content Injection Attacks (some) and it requires cleaner HTML which makes writing pages that utilize the correct encoding easier. This cleaner HTML will hopefully lead to less XSS/Content Injection vulnerabilities.


Wednesday, December 21, 2011

Struts 2 Session Tampering via SessionAware/RequestAware WW-3631

UPDATE: This post was updated on 1/2/2012 to correct the post to take into account the fact that the interfaces mentioned below bind request parameters to String[] rather then String. See the post for exact details.

NOTE 1: I am not the original reporter of this issue. The issue below, with regards to the SessionAware, was originally reported to the Struts 2 team as WW-2264 by Hisato Killing. At that time, it was decided by the Struts 2 team that this was "Not A Problem". Back in May 2011 I identified the identical issue without previous knowledge of Hisato’s bug report and I reported it to the Struts 2 team as WW-3631 (CVE-2011-5057). A former colleague of mine, Abraham Kang who is now a Principal Security Researcher at Fortify an HP Company, urged me to include a reference to the RequestAware Interface and also indicated other *Aware interfaces could also be dangerous.

NOTE 2: This issue does not affect every application that uses Struts 2 - only those that have Actions that implement SessionAware, RequestAware, and possibly other *Aware interfaces either directly or indirectly, and make no attempt to block the auto-binding of the request or session collections.

NOTE 3: Regarding the Secunia Advisor for this issue 47109 - it is listed as "Not Critical". I completely agree as there are very few Struts 2 applications that implement these interfaces. However, if your application does implement these interfaces it is likely a big problem, luckily the solution is fairly easy.

Example implementation of SessionAware:
public class VulnerableAction extends ActionSupport 
implements Action, SessionAware {

  protected Map session;
  public void setSession(final Map session) {
    this.session = session;

As one would expect from the auto-binding of Struts2 that if an Action implements either of these interfaces it allows the auto-binding of data to the current session or request using the most common implementation (any changes made via the auto-binding may not persist past this single request, read on for more details). This could allow unexpected data to exist within the session by passing in request parameters such as "?session.key=value" or "?request.session.key=value" - these types of request parameters would be auto-bound to the current requests session map (generally a class level variable). When Struts2 binds these parameters they are bound as String arrays rather then a simple String. As such, the impact of this vulnerability is somewhat reduced - however, it is possible to use this technique to auto-bind to public setters of objects stored in the session.

If an object has a setValue(String) method and is stored within the session using the key "data" ; if one passed the following query string parameter "?"; this would alter the field and set the value to "authorized". Note, when binding to public setters on objects within the session Struts2 does not force them to be String[].

While the two interfaces only require the implementation of the setSession and setRequest respectively, if one also implemented either getSession or getRequest respectively then the changes to the contents of the session will be persisted to users' actual session - rather than just the current request (e.g. the local member variable).

Doing a Google code search will reveal some open source packages that are vulnerable to this:

Any system that implements Apache 2.x SessionAware, RequestAware, and/or other *Aware interfaces is affected by this unless they explicitly implemented something to block the parameter auto-binding to the implemented setters. Implementing getSession, getRequest, or a getter corresponding to the implemented setter makes the problem worse. The impact of this specific vulnerability is completely dependent upon the application that implements the interface and what the application uses the session data for.

There is an easy solution to this problem. Prevent auto-binding of the request and session via the default parameter interceptor by placing them into the ignored parameter list. Second, a warning should be placed in the JavaDoc for SessionAware, RequestAware, and possibly other *Aware interfaces indicating the possible issues with implementing this class and recommend that any Action that implements these interfaces also implement com.opensymphony.xwork2.interceptor.ParameterNameAware interface and checking to ensure that any parameters starting with “session” and/or “request” are not being auto-bound.

This was reported via Apache's JIRA system in May 2011: The Struts 2 team stated that a fix would be in version 3.x; and they agreed with me that there is an easy fix and any application implementing these interfaces could easily fix the issue themselves. However, as people are obviously using these interfaces in their code and not implementing the fix - I'd like to post this in a little more public fashion to ensure people are aware of the possible issues if they do implement these interfaces.

I should point out a listing of other *Aware interfaces that are likely of interest:
  • org.apache.struts2.interceptor.ApplicationAware
    • may lead to application context tampering
  • org.apache.struts2.interceptor.RequestAware
    • Request collection and/or Session collection tampering
  • org.apache.struts2.interceptor.ServletRequestAware
    • Request collection and/or Session collection tampering and possibly other concerns
  • org.apache.struts2.interceptor.ServletResponseAware
  • org.apache.struts2.interceptor.ParameterAware

An additional research item is the DirectRenderFromEventAction as this implements the SessionAware Interface.

This has also been reported under CVE-2011-5057.
--Jeremy Long