What is csp_meta_tag in Rails 5.2.3 and how does it work?
Asked Answered
C

1

9

I was working with Rails 5.2.3 and got the below error:

undefined method content_security_policy? for class.

After looking at the error I found that it generates due to csp_meta_tag in layout application.html.erb.

So, what exactly it does mean and how does it help?

Congruent answered 15/7, 2019 at 17:43 Comment(0)
H
12

My interpretation is this: CSP is used to allow only trustable scripts in your app. Therefore, it's used to protect your application from unknown scripts that could be injected to damage (or hack) your app. But how does it do that?

Here is the code for csp_meta_tag:

def csp_meta_tag
  if content_security_policy?
    tag("meta", name: "csp-nonce", content: content_security_policy_nonce)
  end
end

According to the documentation:

Returns a meta tag “csp-nonce” with the per-session nonce value for allowing inline tags.

But what is a nonce and how is it used?

A nonce is a random string. It is cryptographically made by a secure function. The only way that a script would run in the user's browser was if the script had the nonce attach to it. Example:

<script nonce="AsnfAsf%28217%(*">
  <!-- Some code here -->
<script>

Therefore, an attacker that wants to inject a script in your app, won't be able to do it, because he/she doesn't have this random string. Furthermore, the nonce is regenerated every time the browser page is loaded, making the attack even more difficult.

Haematopoiesis answered 16/7, 2019 at 15:38 Comment(2)
But wouldn't the attacker be able to overcome this by running a script to fetch the nonce value and then inject script tag with the nonce value?Quintessa
@RamyTamer Wouldn't the attacker need to know the nonce value to run the script that detects the value and injects it into the scriptPulmonate

© 2022 - 2024 — McMap. All rights reserved.