haiku code

JSON hijacking in Rails

September 27, 2012

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. That’s a Rack middleware that adds while(1); in front of all your JSON output:

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

And that’s a pinch of JavaScript that will let jQuery understand this protected JSON input:

/* 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 all, folks. Stay safe!


Written by Wojciech Ogrodowczyk who takes photos, climbs mountains, and runs Brains & Beards to help companies deliver better mobile applications faster.

© 2012 - 2024, built in a 🚐 with Gatsby and ☀️