04 Apr, 2014

Too much information (TMI) & Rails as_json method

by Ken Johnson

At nVisium, we spend a fair chunk of time developing, researching, securing, and assessing Ruby on Rails applications. Recently, we added a few new tutorials to Railsgoat. If you are not familiar with the project,  check it out. One such tutorial covers model attribute exposure.

Rails provides a helper method named as_json. The method is useful because it is a quick way to turn a model object into a JSON response. There are a decent number of tutorials around the web that demonstrate using this method. Some, not all, of these tutorials discuss the additional options available with the as_json method. We would like to discuss the security enhancements a developer can leverage.

We’ve created an API within Railsgoat (recently). The API allows a user with a valid API token to request information specific to their profile:

The important thing to note here is that by calling as_json as is (no additional options), we return the full User model object:

Now, as you can see, Jack’s entire profile is returned, including his encrypted password. If the profile had some special token used for access decisions or some other sensitive attributes, they would be exposed as well. In addition to that, we render Jack’s admin setting, a dead give-away to attempt mass-assignment on that particular field.

To fix this, we override the as_json method within the User model:

The gist here is that we specify only those attributes we would like to return as well as call super to instantiate the super class’s as_json method.

The response is something a little less verbose and a bit more safe:

We hope this helps you secure your Rails applications or, if you are reviewing code, catch this finding and report it accordingly :-)

Thanks!