Implementation of secure and appropriate HTTP headers, specifically the Referrer-Policy header
import play.api.mvc._
class HomeController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {
def index() = Action { implicit request: Request[AnyContent] =>
Ok("Welcome to our application!")
}
}
In this code, we have a simple HomeController that returns a welcome message when the index endpoint is hit. However, this code is vulnerable because it does not set the Referrer-Policy HTTP header.
The Referrer-Policy HTTP header controls how much referrer information (sent via the Referer header) should be included with requests. If this header is not set or is configured unsafely, it could potentially leak sensitive information. For instance, if a user clicks on a link on your site that leads to another page, the URL of your page could be sent in the Referer header, potentially revealing sensitive information.
In our vulnerable code, the Referrer-Policy HTTP header is not set at all. This means that when a user navigates from our site to another site, the full URL of our page could be sent in the Referer header, potentially leaking sensitive information.
import play.api.mvc._
import play.filters.headers.SecurityHeadersFilter
class HomeController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {
def index() = Action { implicit request: Request[AnyContent] =>
Ok("Welcome to our application!").withHeaders(SecurityHeadersFilter.REFERRER_POLICY -> "strict-origin-when-cross-origin")
}
}
The above code fixes the vulnerability by adding the
Referrer-Policy
HTTP header to the server's response. This is done using the
withHeaders
method of the
Result
class, which allows adding additional HTTP headers to the response.
The
SecurityHeadersFilter.REFERRER_POLICY
is a constant provided by the Play framework that represents the
Referrer-Policy
header. The value
"strict-origin-when-cross-origin"
is a secure value for the
Referrer-Policy
header. This value means that a full URL, stripped for use as a path, is sent as referrer information when making same-origin requests, only send the origin of the document as referrer to a-priori as-much-secure destination (HTTPS->HTTPS), and no referrer information is sent to less secure destinations (HTTPS->HTTP).
This ensures that the
Referrer-Policy
header is properly configured in the server's HTTP headers configuration, thus fixing the vulnerability.