Insecure or unset HTTP headers - X-Content-Type-Options - Ruby

Insecure or unset HTTP headers - X-Content-Type-Options - Ruby

Need

Enforcement of secure content type options through the X-Content-Type-Options HTTP header

Context

  • Usage of Ruby for building dynamic and object-oriented applications

Description

Non compliant code

        # app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
end
        
        

In the above code, the ApplicationController is a Ruby on Rails controller that is the parent class of all other controllers in the application. This is where we can set HTTP headers that will be applied to all responses from this application.

However, this code is vulnerable because it does not set the X-Content-Type-Options HTTP header. The X-Content-Type-Options header is used to protect against MIME type confusion attacks. It prevents the browser from doing MIME-type sniffing
- a technique that can open up the site to attacks when the server does not send a MIME type in the Content-Type HTTP header, or sends an incorrect or generic one.

If the X-Content-Type-Options header is not set, or if it is set with a value other than nosniff, the browser will try to interpret the content on its own, potentially leading to security vulnerabilities.

In this code, the absence of the X-Content-Type-Options header makes the application vulnerable to such attacks.

Steps

  • Add the X-Content-Type-Options HTTP header to the server's response.
  • Set the value of the X-Content-Type-Options header to 'nosniff'.
  • Ensure that the X-Content-Type-Options header is set for all responses, including error responses.
  • Verify that the X-Content-Type-Options header is correctly set by inspecting the server's response headers.

Compliant code

        # app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_headers

  private

  def set_headers
    response.headers['X-Content-Type-Options'] = 'nosniff'
  end
end
        
        

The above code fixes the vulnerability by setting the X-Content-Type-Options HTTP header to nosniff for all responses from the server. This is done using a before_action callback in the ApplicationController, which ensures that the set_headers method is called before every action in every controller in the application.

The set_headers method sets the X-Content-Type-Options header in the server's response to nosniff. This tells the browser to not try to interpret content differently from the declared content type, which can help prevent certain types of attacks, such as MIME type confusion attacks.

This fix ensures that the X-Content-Type-Options header is set for all responses, including error responses. After implementing this fix, you should verify that the X-Content-Type-Options header is correctly set by inspecting the server's response headers.

References