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!

12.14.2009

GET vs POST in Java Servlets...

This is an issue that has come up many times before, and something that really grates on my nerves as a developer and makes the appsec part of me angry. If you have developed Servlets in Java you may or may not be aware of a design issue in the way HTTP Requests are processed. Here is the issue.

Data from the query string and the post body are aggregated into the request parameter set. Query string data is presented before post body data. For example, if a request is made with a query string of a=hello and a post body of a=goodbye&a=world, the resulting parameter set would be ordered a=(hello, goodbye, world).

So what is the issue here? It is quite simple really, if you POST to a Servlet it should ONLY return the value(s) for the parameter that were part of the POST Request, ignoring the GET values! The same is true for the opposite.

Even PHP has gotten this right by seperating parameters out into the $_POST and $_GET globals (the use of globals here is a whole seperate issue)

So why is this a big issue? Well for one, it makes it much easier for would-be hackers to try to do mean things to your application. There are lots of reasons that this is a bad idea, but the main one is that when you are posting parameters to a servlet, a great deal of the time, you are posting operational information, which can be changed by adding a GET parameter to the URL, maybe. And that's the kicker, you really have no idea whether the parameter(s) you are looking at were passed in on the URL or were part of the POST without additional work.

I suppose there are ways around this that could be implemented into a wrapped request, but he fact of the matter is that this is something that absolutely should be part of the spec. It is no secret that a lot of people want this to be added, and frankly it really irritates me that the community has not listened to the user base in the respect.

12.10.2009

Invocation is E.V.I.L., Mmkay?

This post is especially for anyone using Apache Tomcat for their application server. Today we will be discussing the EVIL InvokerServlet. What is so evil about the InvokerServlet? I mean it ships with Tomcat and has for a long time?

Let's analyze that question for a second. If you're like me, you have seen a lot of sci-fi and fantasy movies. I can think of very few examples where something being invoked was a good thing. As a matter of fact it is almost always the bad guys doing the invoking and they are almost always trying to do so to undermine and take over the world, or some other nefarious purpose in line with that.

So what does that have to do with Tomcat?

invoke (synonym: conjure)
to call forth by incantation

Let's apply this to Java:

invoke (synonym: conjure)
to call forth by FQN (Fully Qualified Name)

This is what the InvokerServlet allows you to do. By itself, in a controlled environment, it is not such a bad thing. But this is a servlet, which means, when enabled, is accesible to the entire internet, good guys and bad guys alike. All they need to do is discover the incantation, or in this case the FQN that need be uttered or passed in to make things happen.

Say for example you have a page on your site that contains a form that submits to a servlet by way of the invoker servlet. This code looks like this:

<html>
<head>
<title>This is the secret incantation page</title>
</head>
<body>
<form action="/servlet/com.yoursite.servlets.DoSomethingServlet" method="POST">
<!-- Form Elements go here -->
</form>
</body>
</html>

Any bad guy who has discovered the Right Click -> View Source option in every browsers context menu will be able to discover the secret incantation to invoke something which may be innocent enough. However, what this tells the attacker more than anything is that in your universe (website) he can learn all the secrets of your universe by trying different incantations.

Now, let's take this one step further and let's invoke the power of Google (God of the land of Search) to see what universes will easily allow us to start trying out some incantations.

Google Dork: inurl:servlet/com

Of course you can try this with net.*, org.*, or any other package descriptors you can think of. The sheer amount of results of people that are doing this and allowing this to happen are crazy.

So we still haven't really seen anything "dangerous" yet, you might be saying to yourself at this point. Well, actually you have. I have already demonstrated that you are exposing the internal structure of your source code by simply being forced to reference a class by it's FQN in a manner that is publicly accessible.

Things get even more interesting when you start tuning your query a little bit to get you more interesting results.

Google Dork: inurl:servlet/com +admin

Wow, that definately gives you some interesting stuff. Including the direct paths and information required to get admin access on a couple of sites, database usernames and passwords, and the aforementioned structure of your source code.

So let's keep going with this. Maybe using the invoker servlet, I can try to load a class that isn't a servlet at all, rather is just a POJO that lives in the classpath somewhere. To test this theory, let's try to load something that we know exists.

Url: http://hax0r-universe.org/servlet/java.lang.Object

Well, it tried to load and run the class as a servlet... Isn't that interesting. I wonder if what happens if I try to access something that I know isn't an object.

Url: http://hax0r-universe.org/servlet/java.lang.SecretIncantation

Hey, look at that, we got a 404 back from the server instead of the 500 we got when we tried to load a valid object that wasn't a Servlet.

Things are getting interesting now. I wonder if we could fingerprint and detect what libraries are running in the app server. Let's pick something that almost every application uses. Let's experiment with a Log4J class.

Url: http://hax0r-universe.org/servlet/org.apache.log4j.Logger

Hey! It tried to load it! Awesome!

I wonder if evilsite uses the version of <Insert Library Name Here> that had that really cool Buffer Overflow Vulnerability that let's me execute arbitrary code and get a shell to the server!

You see where this is going.

Using the invoker servlet opens your entire JVM to the world for discovery and probing. A dictionary powered crawl could provide a map of your entire source code tree. A vulnerable library could be exposed providing a mechanism for the bad guys to use to find that security hole in your otherwise inpenetrable fortress application. The possibilities here are endless.

So, why, after all of that, does the Apache Crew refuse to do away with the Invoker Servlet? I can't pretend to know the answer to that, but I can tell you that by default, there is no *explicit* mapping to the InvokerServlet (it is commented out in $TOMCAT_HOME/conf/web.xml) but there are a significant number of people that are uncommenting it to use it in their apps.

This is bad, mmkay. So let's stop the madness. If you are using the InvokerServlet, it is time to get over the lazyness of not adding explicit mappings to your servlets and get rid of it!

On a side note, I am investigating the possibility of including a SecureInvokerServlet (if such a thing could even be written) for inclusion in the ESAPI that provides the same kind of functionality but adds in the required Access Control, Path Whitelisting, and basic security controls that the standard InvokerServlet that ships with Tomcat lacks.

Update 1 - A good followup read is the Securing Tomcat page at OWASP