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

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

Need

Enforcement of secure content type options

Context

  • Usage of Scala for building scalable and functional applications
  • Usage of play.api.mvc for handling HTTP requests and responses in Play Framework

Description

Non compliant code

        import play.api.mvc._

object Application extends Controller {
  def index = Action {
    Ok("Hello, World!")
  }
}
        
        

This code represents a simple HTTP server that responds to requests at the root URL ("/") with the text "Hello, World!".

The Action function is used to handle HTTP requests and generate HTTP responses. In this case, the Ok function is used to generate an HTTP response with a 200 status code and the text "Hello, World!" as the body.

However, this code does not include the X-Content-Type-Options HTTP header in its response. The X-Content-Type-Options HTTP header is used to protect against MIME type confusion attacks, which can lead to security vulnerabilities. By not including this header, the server is potentially vulnerable to these types of attacks.

To include the X-Content-Type-Options HTTP header, you would need to modify the Ok function call to include it, like so:

                Ok("Hello, World!").withHeaders("X-Content-Type-Options" -> "nosniff")

            


This will include the X-Content-Type-Options HTTP header with the value "nosniff", which tells the browser to not try to interpret the content as a different MIME type than what is specified by the Content-Type HTTP header.

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

        import play.api.mvc._

object Application extends Controller {
  def index = Action { request =>
    Ok("Hello, World!").withHeaders("X-Content-Type-Options" -> "nosniff")
  }
}
        
        

The above code fixes the vulnerability by adding the X-Content-Type-Options HTTP header to the server's response. The value of the X-Content-Type-Options header is set to nosniff. This tells the browser to not try to interpret the content as something else other than the declared content type.

The withHeaders("X-Content-Type-Options" -> "nosniff") is used to add the HTTP header to the response. This 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. This can be done using browser developer tools or a tool like curl or Postman.

References