JSON hijacking in Rails

JSON hijacking is a relatively unkown (amongst developers) type of web application attack. Hence there aren’t many resources that tell you how to easily secure your Rails-based single page application that’s sending lots of JSON back and forth, I’ll do just that.

Talk is cheap, here’s the code.

class JsonProtect
  def initialize(app)
    @app = app
  end

  def call(env)
    dup._call(env)
  end

  def _call(env)
    @status, @headers, @response = @app.call(env)
    [@status, @headers, self]
  end

  def each(&block)
    if @headers['Content-Type'] && @headers['Content-Type'].include?('application/json')
      block.call('while(1);')
    end
    @response.each(&block)
  end
end

That’s a Rack middleware that adds while(1); in front of all your JSON output.

/* Parse JSON hijacking protected strings: while(1);{ "foo": 1 } */

(function() {
  var SECURITY_REG_EXP = /^while\(1\);([\s\S]*)\s*$/,
    ORIGINAL_PARSEJSON = $.parseJSON;

  $.extend($, {
    stripSecurity: function(string) {
    return string.replace(SECURITY_REG_EXP, "$1");
  },

  parseJSON: function(string) {
    return ORIGINAL_PARSEJSON($.stripSecurity(string));
    },
  });

  $.ajaxSetup({
    dataFilter: function(data, type) {
      return type === "json" ? $.stripSecurity(data) : data;
    }
  });
}());

That’s a pinch of JavaScript that will let jQuery understand this protected JSON input.

That’s all, folks. Stay safe!

Share on Twitter, Facebook
Prev Next