Skip to content

Instantly share code, notes, and snippets.

@vishnumitraha
Created December 9, 2020 04:13
Show Gist options
  • Save vishnumitraha/0f575063fe64ee8032abfbc21458c9fd to your computer and use it in GitHub Desktop.
Save vishnumitraha/0f575063fe64ee8032abfbc21458c9fd to your computer and use it in GitHub Desktop.
Implement CSP frame-ancestors
Let’s take a look at the following implementation procedure.
Apache HTTP
mod_headers is the pre-requisite to inject any headers in Apache. Depending on the OS and version but if you are using Ubuntu and Apache 2.4 then you can use a2enmod headers to enable it.
root@geekflare:/etc/apache2# a2enmod headers
Enabling module headers.
To activate the new configuration, you need to run:
systemctl restart apache2
root@geekflare:/etc/apache2# systemctl restart apache2
root@geekflare:/etc/apache2#
Note: all the configuration you can do it in either httpd.conf file or any effective configuration file you are using.
DENY from ALL
Similar to X-Frame-Options DENY. If you don’t want any site (including self) to embed then add the following.
Header set Content-Security-Policy "frame-ancestors none;"
Save the file and restart the Apache HTTP to take effect.
csp-refusing
I tried to embed the site and as you can see it was getting blocked.
Allow from self but DENY others
Similar to X-Frame-Options SAMEORIGIN, you can add the following.
Header set Content-Security-Policy "frame-ancestors 'self';"
Allow from self and multiple domains
X-Frame-Options didn’t have an option to allow from multiple domains. Thanks to CSP, you can do as below.
Header set Content-Security-Policy "frame-ancestors 'self' geekflare.com gf.dev geekflare.dev;"
The above will allow the content to be embedded from self, geekflare.com, gf.dev, geekflare.dev. Change these domains with yours.
Nginx
The concept and directive are the same as above explained in the Apache HTTP section except for the way you add the header. Headers in Nginx should be added under the server block in a corresponding configuration file.
DENY all
add_header Content-Security-Policy "frame-ancestors none;";
DENY all but not self
add_header Content-Security-Policy "frame-ancestors 'self';";
Allow from multiple domains
add_header Content-Security-Policy "frame-ancestors yoursite.com example.com;";
The above example will allow embedding content on yoursite.com and example.come. After making changes, don’t forget to restart Nginx server to test the policy.
WordPress
It depends on how you are hosting WordPress.
If self-hosted like a cloud or VPS, then you might be using a web server such as Apache or Nginx. If so, then you can follow the above mentioned to implement in web server instead of WordPress. However, if you on shared hosting or no access to modify webservers, then you can leverage a plugin.
To implement CSP in WordPress, you can use the Content Security Policy Pro plugin.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment