Showing posts with label ESAPI. Show all posts
Showing posts with label ESAPI. Show all posts

5.11.2011

ESAPI 2.0GA IS RELEASED!

Friends, Romans, Countrymen - Lend me your ears!

It is my pleasure to announce the official release of ESAPI 2.0GA!

This release features some key enhancements over ESAPI 1.4.x including, 
but not limited to:

     * Upgrade baseline to use Java5
     * Completely redesigned and rewrote Encryptor
     * New and Improved Validation and Encoding Methods
     * Complete redesign of the ESAPI Locator and ObjectFactory
     * More unit tests
     * ESAPI Jar is now Signed with an OWASP Code Signing Certificate
     * ESAPI Jar is Sealed
     * And much, much more

We understand that a lot of you have been waiting a very long time for 
this, and so have we! It was important that we take our time with this 
release to make sure we had addressed everything possible prior to it 
going out. Included in that process was:

     * Peer review of the ESAPI Codebase
     * Code and Architecture Review of new Encryption
     * Adding and fixing unit tests
     * Tons of discussion and interaction with the OWASP Community and 
ESAPI Users

Without the feedback from our users, we could have never accomplished 
some of the awesome enhancements that have been made to the library 
since the last major release, so we owe you all a debt of gratitude for 
helping us design and implement controls that will ultimately help you 
write more secure applications.

We are currently in the process of getting a whole new suite of 
documentation, with a focus on integration tasks and actually using 
ESAPI in real applications - look for those documents over the next 
couple monthes, as well as a whole new contribs section in our 
repository aimed at providing turnkey components and solutions to some 
of the more commonly encountered integration points for ESAPI.

You can download the full distribution of ESAPI 2.0GA from our home on 
Google Code at:
http://code.google.com/p/owasp-esapi-java/downloads/list

The latest API Docs can always be found at:
http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/index.html

Within the next 24-48 hours the distribution to Maven Central should be 
updated as well and you should be able to start using 2.0GA in your 
Maven projects as soon as that happens. Maven dependency will be:

<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.0GA</version>


As always, we would love to hear your feedback on the release and if you 
have any questions at all, you can join the ESAPI-User Mailing List here:
https://lists.owasp.org/mailman/listinfo/esapi-user

Thanks again to the OWASP and ESAPI Community for helping us build and 
release the tools that help make the internet just a little bit more sane!

Sincerely,
The ESAPI Development and Management Teams

P.S. Please forward this along to any colleagues or distribution lists 
that may be interested.

4.18.2011

ESAPI4JS - Very good write-up by Marcus Niemietz

So late last week, I recieved the final copy of a paper written by Marcus Niemietz that takes a deep dive into the ESAPI4JS Proof of Concept I wrote over a year ago. I was quite surprised, to say the least - and a bit humbled by 20+ pages of text on the project.

It's funny, I was just thinking about digging in my heals this spring and running through this code again - clean it up, trim a bunch of fat - and possibly do some additional integration into further jQuery plugins. Seems that I am not the only one who has been thinking about this project lately and that is great news!

First and foremost - I have reposted the entire report (with the author's permission and OWASP's) over on the OWASP Site.

Marcus spends some time discussing the project and concept of the project as well as the ESAPI project as a whole first off. Ths lays the groundwork for his paper and is probably stuff that most of you (my readers) already know. He also corrects some mistakes in the installation guide (that will be reflected on the wiki as soon as time allows). In addition he also spends some time discussing the assessment criteria and specifically how they relate to this project.

Once we get passed all of that, we get into the real meat of the paper.

Section 3 focuses on improvements that could be made to the project and this is where I would like to spend most of my time in this post.

3.1.x - Retrofitting Security

Marcus calls out a point here that a mature SDL will have isolated the "risks" of the application prior to any development being done. This is generally very true for shops that have an established and mature SDL - but that statement definitely does not apply to the majority of software development shops that are writing applications for the web today. The idea of retrofitting security into an existing application is paramount to the idea behind ESAPI. It is imperative that developers have the ability to integrate ESAPI controls into existing applications because there are a lot more insecure existing applications on the internet right now then there are new applications being built. Several large shops have legacy applications that are no longer actively maintained unless there is a problem, some have such massive application portfolios that it isn't realistic to expect rewrites and large redesigns, and the majority of the applications that are live (and vulnerable) on the web today are smaller "Mom and Pop" applications. This is the target market for ESAPI!

3.2.x - Modification of Objects


I heartily agree this is a huge issue - and one that I have passionately spoken out about whenever the opportunity arises. The fact of the matter is that until Javascript accepts the fact that some objects just *need* to be immutable, security will always be just another stepping stone for the attacker to (easily) overcome in the browser. In specific Marcus refers to the ability to overwrite objects in the DOM by referencing HTML Elements with the same id in Internet Explorer. While this is indeed a problem, the issue is much larger and depends 100% on the forced implementation of Immutable Objects in ALL browsers as described in the ECMAScript 5 Specification

3.3.x - Redundancy


This is a tricky issue in some regards, while most of this is due to the fact that I was simply creating a proof of concept that this could be done in Javascript - I also am a firm believer that all implementations of the ESAPI (regardless of language) should follow a well defined API specification. Because of this, it is to be expected that there will be some redundancy in some languages - some methods that perhaps just don't make sense in the language (such as the illustrated escape/unescape methods) will be implemented anyhow just to enforce the contract (implied in JS of course) of the API.

Adding more Validation!


I  agree with this to a certain extent - I think that all the suggested validators should be "available", but there is no need for my user registration form on my small used book store to require validation of International Bank Account Numbers - it does however make sense to provide ISBN validation. This problem (I believe anyhow) is addressed very well in the jQuery Plugin architecture and I would ultimately like to see this same type of architecture implemented into future ESAPI4JS implementations.

Summary


All in all, I think Marcus did a great job researching and presenting his case in this paper, and I highly recommend that everyone give it a read and comment. I look forward to reading your comments and rebuttals  - this is how we change the world people. One small debate at a time. :)

11.20.2010

Call To Arms: ESAPI Documentation Team!

We are in desperate need of some people to aid in updating and completing the documentation for ESAPI 2.0GA Release (upcoming).

If you are a technical writer, or interested in writing at all, we could use your help! After all, how many of you would actually want your developers to also write your technical documentation?

That being said - here are the primary areas we are looking for help with documentation:

  1. Installation and Configuration
    This area of the documentation has been done and done again, but still needs to be clarified and updated to reflect changes in 2.0 and consolidate some of the developer documentation (crypto) into the core documentation.
  2. Integration
    This area of the documentation needs a lot of love and attention. This area is also the least defined as far as what goes here. I envision a basic outline of:

    • Integrating Core Componenets (Encoder, Logger, Validator, etc.)
    • Extending Core Components (Adding custom validators - etc.)
    • Creating Adaptors (Authenticators, Access Control, etc.)
    • Integrating with Popular Frameworks
      • Spring
      • Struts
      • Grails
      • GWT
      • etc
  3. Real-World Solutions
    Collection of Examples of how to solve real issues encountered in applications

These are only a few that I could think of off-hand, so if you are interested in helping - get in touch with us on the ESAPI-Developers or ESAPI-Users Mailing Lists and let us know. You can always get a feel for what we have already by visiting the wiki at The ESAPI Homepage.

Dave Wichers has offered to head up this effort and work on a documentation roadmap - and he has been with the project since the beginning offering thoughts, patches, and guidance.

7.31.2010

ESAPI at AppSecUS

If you follow my Tweets you probably are already aware that my talk on ESAPI was accepted and is scheduled to happen at AppSecUS 2010 in California this September. I am super excited about it!

I will be streamlining my Presentation from FROC 2010 and trying to cram a lot of information into a 45 minute presentation, and so I wanted to reach out to the community, especially to those who are thinking about coming to AppSecUS to see exactly what you guys would like me to spend my time on.

It seemed like a good deal of the questions after the presentation at FROC and the presentation(s) I had the pleasure of helping give at UberConf with Ken Sipe had to do with the following areas:

* Configuration
* Using specific components
* Cross Language Compatibility
* Encoding and Validation

So my initial plan is to reformat the presentation to address these concerns primarily and leave room for elaboration and code demos real-time.

I would love to hear what you all think and if you would like to see other areas covered as well.

I am also still in the planning phases of an ESAPI Bootcamp Training session that will either be a Webcast and/or hard-core weekend training event located in Denver, so I will keep you all posted on that.

I know I promised in my last posting that I would be throwing up some recipes and sample ideas from the book (which I have started and am working on) - however with work, life, and conference season in full swing, I have decided to put this off until this fall, when I will have more time to focus on it and more input from the community (and hopefully - a NSA reviewed GA release of ESAPI 2.0)

Hope to see everyone in California in a little over a month, and looking forward to reading your input and ideas!

1.24.2010

ESAPI4JS - v0.1.3 Now Available

The newest installment of the ESAPI4JS is now available! In light of that, I decided it may be helpful to throw out some examples of how this framework can be used to help protect clients from browser based attacks like DOM Based XSS, and how the API could help to provide some additional client side security.

First let's take a look at the biggest benefit to using ESAPI4JS - The ability to mitigate client-side DOM Based XSS attacks. This is something that no other framework that I am aware of is yet to tackle, and as such, I think that we will begin to see this vector being exploited more and more in the wild.

Let us start at the beginning.

What is DOM Based XSS?

Who better to answer that question, than the experts at OWASP?

DOM Based XSS (or as it is called in some texts, “type-0 XSS”) is an XSS attack wherein the attack payload is executed as a result of modifying the DOM “environment” in the victim’s browser used by the original client side script, so that the client side code runs in an “unexpected” manner. That is, the page itself (the HTTP response that is) does not change, but the client side code contained in the page executes differently due to the malicious modifications that have occurred in the DOM environment. - OWASP

The most common type of vulnerable code that this affects is code which uses the information that is in the window.location global object.

Let's work through an example of the vulnerable code, and how it could be mitigated using ESAPI4JS.

<html>
<head>
   <title>My Vulnerable Webpage</title>
   <script type="text/javascript">
      var getParameter = function( name ) {
         var startIdx = window.location.href.indexOf( name ) + name.length + 1;
         var endIdx = window.location.href.indexOf( '&', startIdx );
         if ( endIdx = -1 ) endIdx = window.location.href.length;
         return window.location.href.substring( startIdx, endIdx );
      }

      var firstName = getParameter('firstName');
   </script>
</head>
<body onload="function(){document.getElementById('nameplace').innerHTML = firstName; }">
  <h1>Hello <div id="nameplace"></div>, Welcome to my Vulnerable Page!</h1>
</body>
</html>

If you were to hit this page with the following URL: http://host.com/vulnerable.html?firstName=Chris

The resultant page would display: Hello Chris, Welcome to my Vulnerable Page!

However, what if you were to hit this page with a URL that looked like: http://host.com/vulnerable.html?<sript>alert('xss');</script>

You guessed it! You will get a pretty little popup. So what you say, server-side XSS controls can mitigate that risk easily, and you would be correct, however, what if the url looked like this: http://host.com/vulnerable.html#firstName=<script>alert('xss');lt;/script>

If you said that server-side mitigation wouldn't catch this, you are right! When a browser sends a request to the server, anything after the '#' is not sent as part of the request, as this is meant for browser control to jump to an anchor in the page.

So how do we fix this problem? Simple with ESAPI4JS - the page could be rewritten as follows:

<html>
<head>
   <title>My Vulnerable Webpage</title>
   <!-- Dependencies -->
   <script type="text/javascript" language="JavaScript" src="/js/esapi4js/lib/log4js.js"></script>
   <script type="text/javascript" language="JavaScript" src="/js/esapi4js/resources/i18n/ESAPI_Standard_en_US.properties.js"></script>
   <script type="text/javascript" language="JavaScript" src="/js/esapi4js/esapi.js"></script>
   <script type="text/javascript" language="JavaScript" src="/js/esapi4js/resources/Base.esapi.properties.js"></script>
   <script type="text/javascript">
      org.owasp.esapi.ESAPI.initialize();
      var firstName = $ESAPI.httpUtilities().getParameter("firstName");
      try {
         // Will throw an exception if there are multiple encodings in the value
         firstName = $ESAPI.encoder().canonicalize(firstName);
      } catch (e) {
         $ESAPI.logger('VulnerablePage').warn( org.owasp.esapi.Logger.EventType.SECURITY_FAILURE, e.getLogMessage() );
         alert( e.getUserMessage() );
         firstName = 'Guest';
      }
   </script>
</head>
<body onload="function(){document.getElementById('nameplace').innerHTML = $ESAPI.encoder().encodeForHTML(firstName); }">
  <h1>Hello <div id="nameplace"></div>, Welcome to my Vulnerable Page!</h1>
</body>
</html>

We have successfully mitigated DOM Based XSS attacks against our vulnerable page. Of course, in the real world, the vulnerable code will not be *quite* as obvious in most places, but the resolution is still the same.

Let's move on to the next piece, using ESAPI logging. You probably noticed the call in the above section of code to $ESAPI.logger

There are a few things to deal with when setting up logging for ESAPI4JS. The first is to pick your Logging framework. The Log4JS framework is used by the Reference Implementation and so that will be used for the first part of this demonstration. A subsequent blog post will discuss how to implement other logging frameworks into your ESAPI.

The first step is to setup your logging configuration. For the purposes of this example, we will only be setting up a single logger, and we will continue to use our vulnerable.html example from above. Without further ado:

Base.esapi.properties.logging["VulnerablePage"] = {
    Level: org.owasp.esapi.Logger.ALL,
    Appenders: [ new Log4js.AjaxAppender('/jsLog') ],
    LogUrl: true,
    LogApplicationName: true,
    EncodingRequired: true
};

// Since we specify that we want the application name logged in our configuration, let us give our application a name:
Base.esapi.properties.applicaton.Name = 'Vulnerable Application'; 

Now this will POST your log entry to the path /jsLog which should be mapped to some handler servlet or php controller on the server side. More details on using this appender can be found here

Now any calls to $ESAPI.logger('VulnerablePage') will go to this logger.

There are six methods for logging (trace, debug, info, warn, error, fatal) each with the signature .method( org.owasp.esapi.EventType eventType, String message, Exception exception );

You can define custom event types by instantiating new instances of the org.owasp.esapi.Logger.EventType class or reference the static predefined events

  • org.owasp.esapi.Logger.EventType.SECURITY_FAILURE - Used to log when something fails to pass a security control
  • org.owasp.esapi.Logger.EventType.SECURITY_SUCCESS - Used to log when something passes a security control
  • org.owasp.esapi.Logger.EventType.EVENT_FAILURE - Used to log when something fires an event, and that event does not complete successfully.
  • org.owasp.esapi.Logger.EventType.EVENT_SUCCESS - Used to log when something fires an event, and that event completes successfully.

Creating a custom EventType is simple.
var customEventType = new org.owasp.esapi.Logger.EventType( "Custom Event", false );

// ... later

$ESAPI.logger('VulnerablePage').info( customEventType, "Something happened!" );

HTTPUtilities

The HTTPUtilities object is meant to provide shortcuts for doing common tasks that have to do with the browser and the response. Right now, the available methods are:

  • addCookie( org.owasp.esapi.net.Cookie cookie )< - Adds a single cookie to the cookie jar/li>
  • getCookie( String name ) - Gets the String value of a cookie


  • killCookie( String name ) - Deletes a cookie if it exists in the current cookie jar


  • killAllCookies( String name ) - Removes all the cookies from the current cookie jar


  • getParameter( String name ) - Gets the value of a parameter on the URL



This should be enough to get you started using ESAPI4JS. I will make a seperate post at a later time going over the i18n framework.

Enjoy and feel free to share comments!

1.15.2010

ESAPI4JS - The new hotness!

So I have been hard at work on the ESAPI4JS code for the last couple of weeks, and have gotten it to a point where people can start to play with it. It will be in alpha for a bit yet, as not all the functionality is there, but here is a little of what you can do with it so far.

Download the script(s)
http://owasp-esapi-js.googlecode.com/files/esapi-compressed.js
http://owasp-esapi-js.googlecode.com/files/esapi.js

Import the Compressed or Uncompressed JS File on your page
<!-- Uncompressed Version -->
<script type="text/javascript" language="JavaScript" src="esapi.js"></script>
<!-- Compressed Version -->
<script type="text/javascript" language="JavaScript" src="esapi-compressed.js"></script>

Initialize the ESAPI
$ESAPI_Initialize();

Do some cool stuff!
var val = "<div&gt;Test</div>";
alert( $ESAPI.encoder().encodeForHTML( val ) );
try {
   alert( $ESAPI.encoder().canonicalize( val ) );
} catch (e) {
   alert( e.getUserMessage() );
}

I should be getting some documentation written up this weekend that explains how to configure the ESAPI for JavaScript and how to use the functionality that is complete.

In the meantime, you can see the source for the ESAPI4JS Encoder which is fully implemented.

If you are interested in getting involved in the project, shoot me an email and we will see how you can help out!

Development conversation about the ESAPI happens on the esapi-dev mailing list

User support is available on the esapi-user mailing list.

1.11.2010

What is the ESAPI?

It has been great to see so much buzz about the OWASP ESAPI in the tubes lately. It is very exciting for me to be involved in a project that has people excited and even more important it is fantastic to have people evaluating it and pointing out where it needs work. This is some of the most invaluable feedback a developer can get!

That being said, I have seen some questions floating around to the effect of "Why use ESAPI for authentication and access control when we already use *insert framework here*?"

This is a very valid question, and I think that some people may have gotten the wrong idea about what the ESAPI is really trying to accomplish.

There are some fantastic frameworks out there for logging, authentication, cryptography and all the things that the ESAPI does, and it is not the intention of the ESAPI to replace these frameworks, but rather to provide a central interface for developers to access the functionality of those frameworks in a simple fashion.

While we provide a reference implementation of ESAPI, a good deal of the code provided is to provide an example, or a plug and play environment for the ESAPI itself. It is not only intended but even reccomended that if you are using the ESAPI in a production application, that you use the pieces of the reference implementation that work for you, but also create wrapper objects to use your existing security controls through the ESAPI. This provides several things that are deeply important to having a secure application, especially in an agile environment.

  1. Provides a standard and central API for developers to access security controls which makes the job of the developer simpler. If the developer knows that anytime he needs to log a user in he should call ESAPI.authenticator().login( request, response ) it makes it easier to remember and easy to implement.
  2. Decouples the application from the security frameworks in use. This is probably the most important piece of the puzzle, at least in my mind. Things like access control checks, output encoding, and logging are sprinkled throughout the entire codebase of an application, which makes it a very painful process to migrate to a new framework if you ever need to. Imagine you have an application which consists of several hundred class files and and several hundred JSP files. One day you decide that you want to migrate from using Spring ACEGI to JAAS. You now have to change the code in every class file where you access that library to use the new library. If you were using the ESAPI, you would have a wrapper implementation of Authenticator and AccessController that delegated to your framework. Now you just have to write a new wrapper class and change a properties file and your job is done!

It has been said that ESAPI should be used to "fill in the gaps" where other security controls do not work, such as output and input encoding. I think that should be rephrased to reflect the Reference Implementation of the ESAPI and not the ESAPI itself.

That being said perhaps it would be helpful if there was an incubator project under the ESAPI umbrella that provided wrappers for the more popular frameworks. Having that could allow the developers have the ability to drop in the ESAPI then use wrapper jars as *plug-ins* to the API. So if you were using JAAS under the covers for your authentication and access control framework, you could drop in ESAPI.jar and ESAPI-JAAS.jar into your classpath, update your ESAPI.properties to use org.owasp.esapi.provider.authentication.JAASAuthenticator and you are off to the races.

What do you think?

12.20.2009

Almost There - Sealed Objects in JavaScript

The last blog entry I wrote last week was a huge call out to anyone that could help me find the solution to the problem of writing secure objects is JavaScript. Unfortunately, the call went unanswered so I set out over the weekend to see if I could find the answer, and well, I haven't completely found the solution yet - but I am close.

Let me jump right into it:

Step 1 - We need to implement a "watch" function for browsers that don't support it
        Object.prototype.watch = function (prop, handler) {
            var oldval = this[prop], newval = oldval,
            getter = function () {
                    return newval;
            },
            setter = function (val) {
                    oldval = newval;
                    return newval = handler.call(this, prop, oldval, val);
            };
            if (delete this[prop]) { // can't watch constants
                    if (Object.defineProperty) // ECMAScript 5
                            Object.defineProperty(this, prop, {
                                    get: getter,
                                    set: setter
                            });
                    else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy
                            Object.prototype.__defineGetter__.call(this, prop, getter);
                            Object.prototype.__defineSetter__.call(this, prop, setter);
                    }
            }
        };

Step 2 - Now that we have that in place, we can create our seal method
        Object.prototype.seal = function() {
            for ( var e in this ) {
                this.watch( e, function(newVal,oldVal) {
                    var caller = arguments.callee.caller;
                    throw 'Attempt was name to alter a sealed object [' + this + '] from [' + oldVal + '] to [' + newVal + ']' + 'from [' + caller + ']';
                });
            };
        };
VIOLA!


That is it. This solution is currently working in FF3.5 and Chrome for Linux, I haven't gotten it to work at all in IE7 or 8 yet (Once again, thank you Microsoft) but I suspect once I throw this over the fence to some of the hardcore IE/Compatibility gurus at the office tomorrow, I will have the answer to that problem.

If you would like to see a working demo of this in action, you can checkout the demo page I put together for it at http://software.digital-ritual.net/js-secure-demo/.

I absolutely welcome any and all comments, and will test this out on more browsers as time permits tomorrow. Hopefully this could solve the problem, at least provided something doesn't stop the JavaScript RTE from running the Object.seal method on all objects that need to be sealed; but that is for load testing. For now this seems to be the best approach I can come up with.

12.15.2009

JavaScript? Hello? Is anyone there?

So I am still in the architectural design phase of ESAPI4JS, and have come across an interesting problem. Well, to be honest, there are lots of problems with JavaScript and trying to make it secure - but there is one that I have yet to find a way to overcome. This, in my opinion, is one of the biggest shortcomings of JavaScript that I have encountered to date.

On with the problem...

Say that you have a class that you are creating with JavaScript. You want to ensure that the "private" methods and properties of that class cannot be altered by code running in the same window.

This is a relatively trivial thing to do in javascript using closures:

var MyUnchangeableClass = function(){
   var MyUnchangeableClassImpl = function() {
      var _myPrivate = "Private";

      return {
         getPrivate: function() {
            return _myPrivate;
         }
      };
   };

   var _singletonInstance = new MyUnchangeableClass();

   return {
      getPrivate: function() {
         return _singletonInstance.getPrivate();
      }
   };
}

var unchangeableClass = new MyUnchangeableClass();
alert( unchangeableClass.getPrivate() ); // alerts 'Private'

Using a closure like this creates an interesting scoping situation where the property _myPrivate is locally scoped to the constructor and the 'Object' being returned by the function thus privatizing it both from the global scope and the scope of the closure itself. This scoping situation is called Closure Scope.

This is all fine and great, however, the top level globally scoped reference is always vulnerable to be altered. For instance, we know now that calling getPrivate() on the instantiated closure object will return the innermost value which happens to be "Private", but what happens if I alter the outermost globally accessible reference like this:

unchangeableClass.getPrivate = function() { return "Overwritten"; };
alert( unchangeableClass.getPrivate() ); // alerts 'Overwritten'

We have effectively subverted the entire point of the closure by substituting what the outermost function actually does (coincedentally, the references to anything Closure Scoped will disappear in this case as well, and will be ultimately GC'd, effectively removing the data from the Runtime entirely)

The one thing that is truly holding JavaScript back from being a language that has any hope in a secure world is the fact that there is NO RELIABLE way to SEAL an object. In Java, you can make a class final to ensure that the class cannot be extended to alter it's behavior, you can make properties and methods private to ensure that their behavior and values cannot be altered. There are similar strategies in just about every language that provides OOP or OOP-Like functionality (even PHP!).

I have come up with some somewhat hacky ways to accomplish this, but they can all be subverted by other code running the same runtime. I have even thought about creating a trusted JS plugin for browsers that basically keeps the JavaScript inside a sealed/signed jar after it has been downloaded (so processes outside of the browser cannot modify the cached javascript) and having the initial javascript source tell the plugin which object should be sealed, then have the plugins use the underlying C API to ensure that they cannot be changed. This is a huge undertaking and frankly is open to a ton of potential attacks.

The idea behind the ESAPI4JS library is good - basically providing end users with protection from server side code that has been compromised as a second level of defense. This is something that I think will become increasingly important as time goes on, but without the ability to create secure JS code that cannot be altered, it simply won't live up to it's full potential.

It will provide a second level of defense that can ultimately in most cases still protect the end user, afterall, the code to subvert the server-side code will be the main focus of the nefarious individual doing so, and they may not even realize that there is another layer of protection against potential front-end victims that also needs to be subverted.

I still think it is a great idea, and am excited to see where it goes, but I throw this out to the JavaScript community as both a challenge and a plea. This is something that JavaScript sorely needs (I am sure most JS library writers will agree) and the only way that we will ever see it is if the community demands it.

So Testify! To Securify!

Onward!

11.05.2009

Is Role Based Access Control dead?

This question has been coming up a lot in different circles lately and it seems like there isn't a great deal of online buzz or conversation about it, so I would like to bring it to the online collective for discussion and debate.

I have contested lately that RBAC (Role Based Access Control) just flat out doesn't work in today's world. There was once upon a time, when applications were much simpler that this concept fit very well in the application security world, but we no longer live in that world.

The problem with RBAC is that it is a big hammer. It is what I like to refer to as an all-or-nothing solution to a problem that deserves a much finer grained answer. To elaborate on this, let me first explain the concept of RBAC.

1. Applications have users.
2. Users need to be be able to perform actions.
3. Actions are associated with Roles that are allowed to perform said actions.
4. Users belong to one or more Roles.

This is a very *simple* solution to the problem of access control in an application, and in simple applications, it works quite well. RBAC is widely supported by vendors and comes built in to most web application containers. It also happens to be the access control mechanism used by most OS vendors (Replace Role with Group and Voila!). There are tons of implementations for J2EE applications such as Spring ACEGI, JAAS, etc.

When you want to check if a user can perform some action you simply use a quick check

   if ( user.isInRole( Roles.ADMINISTRATOR ) ) {
      doAdminStuff();
   }

So what is the problem with this simple, widely supported, very popular means of access control? It's simple really, RBAC has no awareness of the context request for access.

To illustrate this point, consider the following situation.

You have just completed coding a wonderful project management application for Big Humungous Inc. that filled all the requirements, is unhackable, and even has a list of features far exceeding the clients requests. One day you recieve a call that your client is creating a special group of representatives that need to have administrative access to customer accounts that belong to Group A between 2pm and 3pm every Monday, Wednesday, and Friday.

Now you have a problem. A role is an all-or-nothing access mechanism. So you can't just add the users to the Administrator Role, so your only option is to go back into the code and add a new check in the code that says am I in this role, and do I meet all these other requisites to do the requested action. Then you need to implement that code in every place where you would normally ask is the user an administrator?

Now let me introduce to a different approach to Access Control. It goes by many names. Some call it Activity Based Access Control, I call it Context Based Access Control. The concept is simple.

Make your Access Control mechanism aware of context!

There are any number of ways to do this, but I will address that in a subsequent article as this is more about the interface it provides. Adding context can allow you to specify any number of dynamic situation that are taken into account when determining whether a user has access to perform an action. Consider the following:

public interface AccessContext {
   boolean isAllowed( User u );
}

public interface AccessRole {
   // Some methods
}

public interface User {
   // ... Other user'ish stuff
}

public interface AccessController {
   boolean canUserPerformAction( User u, Context c, Action a );
}

public interface Action {
   void performAction();
}

This is a simple outline of how a Context Based Access Control API might look. Now in your code you might have something that looks like this:

   User user = RequestHelper.getUser();
   Context requestContext = RequestHelper.getContext();
   if ( accessController.canUserPerformAction( user, requestContext, new Action( "Delete User" ) );

Of course this is a very simple and open ended example, but it gets the point across rather well and illustrates the ability to solve problems in a manner that allows the AC layer to be as fine-grained or big hammer as it needs to be in any given situation.

To summarize:

1. Role Based Security doesn't address the problems of today's applications.
2. Context or Activity Based Security has the power to address those problems, but there is no force driving it forward.

I have proposed to the ESAPI team that we are in the perfect position to address this problem at the API level. Designing a clean interface that addresses the simple as well as complex control situations is really the difficult part in this concept.

An interesting read if you have a second - it looks like Microsoft had the same idea 2 years ago, too bad they patented it and did absolutely nothing with it.

http://www.freepatentsonline.com/y2007/0143823.html


I would love to hear what the 'verse has to say about this so let's get some conversation going around this topic and see what we can come up with!

8.04.2009

Synchronizing the HttpSession

This is something that I have heard a great deal of debate over the last 2 years about. The servlet spec was somewhat recently amended to clarify that there is no guarantee that multiple calls to HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) will return the same object. This holds especially true in containers that return a facade object that wraps around the actual HttpSession object that you are working with, like Tomcat.

Why would you want to synchronize a session anyway?
The answer is pretty simple actually. Consider the following theoretical block of code:

public class WithdrawFundsServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User u = ESAPI.authenticator().getCurrentUser();
String withdrawAmt = request.getParameter("withdrawAmt");
float amt;
Account acct = session.getAttribute("acct_"+u.getAccount());
try
{
amt = Float.parseFloat(withdrawAmt);
}
catch ( Throwable t )
{
ESAPI.log().info( Logger.SECURITY_FAILURE, "Non-Numeric value passed as Withdraw Amount");
try {
ESAPI.httpUtilities().sendForward(request, response, "/error" );
} catch (AccessControlException ignored) { }
}

// Calling Withdraw will queue a check to be printed and mailed to the customer.
AccountFacade.withdraw( acct, amt );

try
{
ESAPI.httpUtilities().sendForward(request, response, "/success" );
}
catch (AccessControlException ignored) { }

return;
}
}


Now there are a couple things that I will point out that I am sure you will notice if you are paying attention. The first is that yes, this example is using the ESAPI. Call it a shameless plug :). The second is that I am ignoring AccessControlExceptions. This is purely to keep this example scenario short and to the point, and in any production code, you would never want to do this. There would also be some validation code in there as well.

Aside from those things, it looks innocent enough right? Well let's consider this for a second with a scenario.

Joe needs to have a check cut to him from his account at SomeBodiesBank. So he gets online and hits the form for the above servlet. Joe is not that savvy of a computer user, and like most novice internet users will do, he has the tendency to double-click on everything. He fills out the form to withdraw $500 from his account and double-clicks the submit button. So somewhere on the backend, we'll say in the AccountFacade.withdraw method, the software validates that Joe has enough money to cover the check, it discovers he has $750 in his Checking account so everything looks good. But wait a minute, Joe double-clicked remember?

Do you know what happens when you double click the submit button on a form? Well, 2 requests get submitted one after the other. Hmmmmmm.. So now I have 2 requests entering this method at the exact same time, both requests check Joe's balance and discover that he has $750 in his account, so they both queue up a request to print a check for the requested amount. There's only one problem, these are cashiers checks, the bank has withdrawn $1000 dollars (or in some circumstances, maybe only withdrew the original $500 from his account) but Joe ended up with $1000 in cashiers checks!

The checks show up in the mail, and Joe being the responsible individual he is, reports this to the bank. The bank will likely write this off as an anomoly and the bug will remain until one day when Joe is down on his luck and remembers the bug. He finds a program called JMeter and submits 1000 requests to the servlet as fast as he can for $1000 withdrawals. When his 1,000,000 in cashiers checks arrive, he promptly leaves the country and disappears in the backwoods of New Zealand never to be heard from again.

So the moral of the story is that this problem could have been easily avoided simply by adding thread-safety measures to the code. Granted the example cited is extreme and the consequence of the example even more extreme, but I can promise you that something similar to the situation has already happened and even moreso I can guarantee that something similar will happen again.

So, with this knowledge, what is the correct means to add thread safety around manipulating the session. It's quite simple even.


final Object lock = request.getSession().getId().intern();
synchronized(lock) {
AccountFacade.withdraw( acct, amt );
}


Would do the trick in this simple example.

It's important when using synchronization to always lock on immutable objects. It is also important to use the same lock when locking in multiple places where you are working with the same data. Thread-safety is an entire subject on it's own that is will beyond the scope of this blog posting, so I will cut to the chase here.

This is incorrect, and not guaranteed:

synchronized (request.getSession()) {
// do stuff
}


While this method is proven and works:

synchronized (request.getSession().getId().intern()) {
// do stuff
}


Some interesting stats to close out with:

Google Code Search Results found approximately 4000 uses of different ways to say 'synchronized(session)'

The scary part is this was only the first 5 ways I came up with to search for it.