Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
Sanjay Prajapati Avatar asked Jul 15 '19 17:07

Sanjay Prajapati


1 Answers

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.

like image 168
B-M Avatar answered Oct 20 '22 06:10

B-M