6. September 2009

  • Spring MVC 3.0 MVC Binding rules

Spring MVC 3.0 MVC Binding rules

Following the work done on the O2 Cmd - Spring MVC module and the conversations we had at OWASP AppSec Ireland about the security implications of the Spring Framework MVC, I spent some time today looking at what is happening at its next major release (3.0.x)

From the MVC documentation section 15.3.2.3 Supported handler method arguments and return types section in Spring 3.0 (see 15.3 Implementing Controllers ) we can see (included at the end of this post) the Spring MVC rules to:

a) map web data into controllers and

b) send data from controllers to the views.

There are quite a number of new features/capabilities, and most have security implications!

For reference, here are a number of good articles & Blog Posts on Spring MVC 3.0

I find a bit worrying that the security implications of the way Spring MVC works (for both old and new features) is NOT properly documented in these articles (for example making references to Security implications of the Spring DataBinder (note-to-self: create page with my & others past research on this topic))

The list below (from 15.3 Implementing Controllers) is what we need to add to the next version of O2 Cmd - Spring MVC module so that it supports Spring MVC 3.0 (in fact I need to dig out the docs about Spring MVC 2.5 works, and start there :) )

15.3.2.3 Supported handler method arguments and return types

Handler methods that are annotated with __@RequestMapping_ can have very flexible signatures. They may have arguments of the following types, in arbitrary order. (except for validation results, which need to follow right after the corresponding command object, if desired):_

  • Request and/or response objects (Servlet API). Choose any specific request/response type, for example, __ServletRequest_ / _HttpServletRequest_._
  • Session object (Servlet API): of type __HttpSession_. An argument of this type enforces the presence of a corresponding session. As a consequence, such an argument is never _null_._
  • _org.springframework.web.context.request.WebRequest__ or _org.springframework.web.context.request.NativeWebRequest_. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API._
  • _java.util.Locale__ for the current request locale, determined by the most specific locale resolver available, in effect, the configured _LocaleResolver_ in a Servlet environment._
  • _java.io.InputStream__ / _java.io.Reader_ for access to the request’s content. This value is the raw InputStream/Reader as exposed by the Servlet API._
  • _java.io.OutputStream__ / _java.io.Writer_ for generating the response’s content. This value is the raw OutputStream/Writer as exposed by the Servlet API._
  • _@PathVariabe__ annotated parameters for access to URI template variables. See _Section 15.3.2.1, “URI Templates”_._
  • _@RequestParam__ annotated parameters for access to specific Servlet request parameters. Parameter values are converted to the declared method argument type. See _Section 15.3.2.4, “Binding request parameters to method parameters with @RequestParam”_._
  • _@RequestHeader__ annotated parameters for access to specific Servlet request HTTP headers. Parameter values are converted to the declared method argument type._
  • _@RequestBody__ annotated parameters for access to the request HTTP body. Parameter values are converted to the declared method argument type using _HttpMessageConverter__s. See __Section 15.3.2.5, “Mapping the request body with the @RequestBody annotation”_._
  • _java.util.Map__ / _org.springframework.ui.Model_ / _org.springframework.ui.ModelMap_ for enriching the implicit model that is exposed to the web view._
  • Command or form objects to bind parameters to: as bean properties or fields, with customizable type conversion, depending on __@InitBinder_ methods and/or the HandlerAdapter configuration. See the_webBindingInitializer_ property on _AnnotationMethodHandlerAdapter_. Such command objects along with their validation results will be exposed as model attributes by default., using the non-qualified command class name in property notation. For example, “orderAddress” for type “mypackage.OrderAddress”. Specify a parameter-level _ModelAttribute_ annotation for declaring a specific model attribute name._
  • _org.springframework.validation.Errors__ / _org.springframework.validation.BindingResult_ validation results for a preceding command or form object (the immediately preceding argument)._
  • _org.springframework.web.bind.support.SessionStatus__ status handle for marking form processing as complete, which triggers the cleanup of session attributes that have been indicated by the_@SessionAttributes_ annotation at the handler type level._

The following return types are supported for handler methods:

  • A __ModelAndView_ object, with the model implicitly enriched with command objects and the results of _@ModelAttribute_ annotated reference data accessor methods._
  • A __Model_ object, with the view name implicitly determined through a _RequestToViewNameTranslator_ and the model implicitly enriched with command objects and the results of _@ModelAttribute__annotated reference data accessor methods.
  • A __Map_ object for exposing a model, with the view name implicitly determined through a _RequestToViewNameTranslator_ and the model implicitly enriched with command objects and the results of_@ModelAttribute_ annotated reference data accessor methods._
  • A __View_ object, with the model implicitly determined through command objects and _@ModelAttribute_ annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a _Model_ argument (see above)._
  • A __String_ value that is interpreted as the view name, with the model implicitly determined through command objects and _@ModelAttribute_ annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a _Model_ argument (see above)._
  • _void__ if the method handles the response itself (by writing the response content directly, declaring an argument of type _ServletResponse_ / _HttpServletResponse_ for that purpose) or if the view name is supposed to be implicitly determined through a _RequestToViewNameTranslator_ (not declaring a response argument in the handler method signature)._
  • If the method is annotated with __@ResponseBody_, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using_HttpMessageConverter__s. See __Section 15.3.2.6, “Mapping the response body with the @ResponseBody annotation”_._
  • Any other return type is considered as single model attribute to be exposed to the view, using the attribute name specified through __@ModelAttribute_ at the method level (or the default attribute name based on the return type class name). The model is implicitly enriched with command objects and the results of _@ModelAttribute_ annotated reference data accessor methods._

Finally … here is how I have been analysing Spring MVC apps using O2

One of the greatest challenges I always had when reviewing Spring MVC applications, was to gain a full picture of its controllers, and more importantly its CommandClasses (i.e. the POJOs that are AutoBinded by Spring and who are a common source of high/critical vulnerabilities in Spring MVC apps).

The way I approach these problems (visualizing/understanding Spring, Struts, DWR, Sharepoint, etc…), is to write scripts that consume the Application’s articfacts (web.xml, *-servlet.xml, source-code, class files) and then consolidate that information in ‘easy’ (or easier) to undersand visualizations.

Unfortunally most of the great examples that I had in the past were built on top of Client code, so I couldn’t really share them. But finally, the O2 Scripts have reached a level of maturity that it was easy to create a generic version of them for Spring’s MVC Demo application: JPetStore.

Ironically, this demo application from Spring (which is used by Spring Developers to learn how to use Spring), is actually vulnerable to a number of security issues, including some spectacular cases of the Spring MVC AutoBinding issue.

I have created a number of Blog posts and videos that hopefully will help you to understand (and replicate) the issue:

The other important factor about these examples, is that I finally have a real example that can be used when talking with the Spring Framework team, other OWASP/AppSec FOSS tools and with AppSec vendors (tools and service-providers). Basically, from now on the message is: here is a complete scenario, now lets figure out how to use your technology to fix, detect or mitigate this.

**
**
This is also a part of O2 that I was waiting for, in order to be able to fully participate in the current OWASP ‘reach the developer’ efforts. In order to reach the developers, we need to speak their language, and with these examples (and technology) I can finally communicate properly with developers, and show them how their app works.

Note that the point here is not to push that everybody should be using using O2 to perform this type of analysis! My objective with O2 is to show what can/should be done, and to allow others to create more native implementations of these techniques (in this case, there should be an eclipse plug-in to do this or to consume this data). Ultimately if we want to reach the developers we need to communicate with them using tools and techniques they are already used to.

There is still a lot to document and to map out (including other tools that merge even further the black-box and white box worlds), so please take these scripts for a test drive, and help me to create a really powerful ‘Spring MVC Security Analsys ToolKit’ that can dramatically increase the security of Spring MVC applications :)

We also need to start thinking about creating an (Open) ‘Spring MVC Security Rule Pack’ which can be maintained by the community and consumed by the multiple tools/services.

Final note for the .NET Crowd, the ASP.NET MVC has the same problem, and I although I have not looked at a big ASP.NET MVC app, I will bet that they will create the same types of vulnerabilties (so … if you have access to such an app, try the O2’s ASP.NET MVC visualizer on it :) )

Reaching out to Spring Developers

I just posted an entry on the Spring Framework forums http://forum.springsource.org/showthread.php?111901-Security-Vulnerabilities-with-JPetStore-and-visualization-of-the-AutoBinding-Issues which hopefully will get some tracking from their side.

I will reach out to my contacts over there (Spring Source), but if you know somebody at SpringSource (or at a heavy user of Spring MVC) please put them in touch.

Thanks

Couple more blog posts on JPetStore and additional Spring MVC Autobinding vulnerabilities

On the Spring MVC topic, I added a couple more blog posts and video to the O2 developer blog:

I also noticed that using the same autobinding vulnerability, it is possible to change the quantity of the item being purchased to a **negative **value which has interesting implications on the current purchase and more importantly on the global (to JPetStore) ‘item stock quantity’ value.

I have not scripted this latest issue, but if you want looking at trying these scripts, why don’t you have a go at writing it?

:)

Visualizing Spring MVC Annotations based Controls (and Autobinding PetClinic’s vulnerabilities)

If you are reviewing a Spring MVC aplication that uses Java Annotations to define the controller’s behaviour, you can use an older version of O2 (packaged separately) which was published a couple years ago, but is still quite effective in its capabilities. You can get the installer from here or just execute the following script to download it and start the installation process: [sourcecode language=”csharp” wraplines=”false”] var path = "http://s3.amazonaws.com/O2_Downloads/O2_Cmd_SpringMvc.msi".uri().download(); path.startProcess(); [/sourcecode] Once it is installed, you will have a shortcut on your desktop called O2_Cmd_SpringMvc.exe which when executed looks like this: For the rest of this demo I’m going to use the PetClinc Spring MVC demo app, which you can download from SpringSource or from the O2 Demo Pack that I published (see Packaged Spring MVC Security Test Apps: JPetStore and PetClinic) Unzip the files to the C:O2Demos folder And drag and drop the petclinic.classes.zip file into the big red box (top left) from the O2 Spring MVC module, which will trigger the conversion process: Once the coversion is finished, you will see the Spring MVC mappings and its source code location: If you select a URL that uses @ModelAttribure, and go to the Spring MVC Bindable fields for selection tab, you will see a graphical representation of the fields that can be binded into (and that create another variation of the Spring Framework Autobinding vulnerabilities) Note that in order for the o2 engine to find some of these mappings, there are a couple cases where an extra comment needs to be added to the affected classes. For example, in the Owner.java class: [sourcecode language=”csharp” wraplines=”false”] public List<Pet> getPets() { /O2Helper:MVCAutoBindListObject:org.springframework.samples.petclinic.Pet/ [/sourcecode] This O2 tool also has a BlackBox analysis module, which allow the use of the mappings created to drive/test the website dynamically For example here is how to bypass the current SetDisallowedFields protection that is included in the controller for /editOwner.do [sourcecode language=”csharp” wraplines=”false”] @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields(new String[] {"id"}); } [/sourcecode] Note the extra field pets[0].owner.id=6 which save the current data into user #6 This app (together with JPetStore) presents good case-studies on the security vulnerabilities that are easily created with the Spring Autobinding capabilities. In the above example, the Edit Owner page should only allow 5 fields to be edited, while in fact it allows a VERY large number of fields to be edited In fact, in this case, there are infinite posibilites, since: the Owner class has a getPets method, which returns a Pets class, who has a getOwner method, who has a getPets method , etc…. This applicaition also has a large number of XSS vulnerabilities, including the ability to create a Pet with a XSS payload which (via autobinding) can be assigned to another user (i.e. via modifing the pet’s owner ID)

Current O2 support for analyzing Spring MVC

During the past week I spent some time documenting O2’s support for Spring MVC apps.

There is still quite a lot to do before we can do a proper security analysis of the JPetStore and PetClinic applications (for example ‘mapping the JSPs to the controllers’), but hopefully these blog posts show the kind of analysis that is possible using O2:

JPetStore and PetClinic are demo apps which can be downloaded from here Packaged Spring MVC Security Test Apps: JPetStore and PetClinc (includes tomcat), or from the main Spring Framework source distribution (look in the samples folder)

For more details on the Spring MVC Autobinding Vulnerabilities see: “Two Security Vulnerabilities in the Spring Framework’s MVC” pdf (from 2008)

What needs to be done to map Static Analysis Traces from Controllers and Views

Here is a reply I just posted on the O2 Mailing list, which provides a number of ideas on how to map/glue partial traces (i.e. traces that have sinks on Controllers and Sources on Views)


I think we are exactly on the same page, and welcome to the wonderful world of ‘Framework behaviour mapping’ :)

I’ve done this quite a lot in the past, so let see if I can help you here.

The first thing you must do is to make sure that you have ‘scriptable’ access to ALL required artifacts. Since you will need to be doing a lot ‘automagically’ glueing, you have to make sure that you can programatically access the data you need.

From what I understand you already have the traces for the controllers and the views. So what about the config files? Is everything on those config files, or will you also need to parse the java/class files for more metadata. Btw, this is J2EE right?

The next thing you need to do, is to figure out the exact formula that maps the controllers to the views. And before you go any further you need to have a visualization of this (which can be as simple as a treeview, or as complex as a full blow graph model (which you can also do with O2 :) ).

After that, you will need to look at your sinks and sources and see if they are easy to match (this has to be done after you matched the controllers with the view, or you will get a huge amount of mappings, most of which will never happen in the real-world). One of the beauties of the IO2Finding and O2Trace format is that I was able to join traces by simple doing string matches (there are even helper methods to do that).

The idea/concept for Joining traces, is that you rewrite the Sinks and Sources so that they match:

For example, if you had a Controller ‘Sink’ with

  • setAttribute(“A_KEY”, {taint value”})

and a **View ‘Source’ **with

  • getAttribute(“A_Key”)

Then I would rewrite them (in-memory or in disk (if there is a large number of findings)) as:

Controller ‘Sink’ -> getset_Attribute_A_KEY()

** View ‘Source’ ** ->** ** getset_Attribute_A_KEY()

and then just:

  • do a direct string Sink-to-Source match,
  • glue them with a one-to-many traces/finding generation mode (i.e you will need to create a new trace for each unique Sink-to-Source mapping),
  • look at the created findings (and finally you will be able to gain a better picture of what is going on)

This actually works very well, and scales spectacularly.

I have used this on lots of different ‘glue’ locations: Session/Global Variables, Interfaces, Database layers, Controllers->Views, Reflection, Aspect PointCuts, Validation routines, etc…

A good way forward is probably if we work together on doing this for Spring MVC’s JPetstore, since I’ve already started this process and it is a great case study. See the posts at http://o2platform.wordpress.com/category/java/spring-mvc/jpetstore/ , and my next step on this JPetStore security analysis is exactly to create a mapping for the JSPs (check out this post which talks about that: Finding the JSP views that are mapped to controlers in JPetStore (Spring MVC) )

Does this make sense?

Dinis Cruz

————————————– (end-of-email)