Urgent.News

What's breaking now, across hundreds of outlets.

Tech

CSP basics: allow only what you mean to run, not block everything

Someone told you to add CSP, so you pasted the one line default-src 'self' . What actually changed? It is easy to end up with no idea. CSP is not a way to block all scripts. It is an allowlist: you name what may run on the page, and everything else is stopped . Start from default-src 'self' and add only the sources you really use. What CSP is Picture the front desk at an event. There is a guest…

CSP (Content-Security-Policy) is a security measure that allows you to control which scripts, styles, images, and other resources a web page can load. It does not block all scripts by default, but instead creates an allowlist of trusted sources. Imagine a front desk at an event with a guest list – only people on that list are allowed entry, while everyone else is denied access. Similarly, CSP specifies where scripts, styles, images, and other resources may be loaded from, and blocks everything else.

Picture a malicious script being slipped into a form field on your web page. This is called an XSS (cross-site scripting) attack. If the malicious script is allowed to run, it can compromise user data and security. CSP helps prevent this by ensuring that only trusted scripts are executed on your web page.

To implement CSP, start with the default-src 'self' directive, which allows scripts only from the same origin (the same website). From there, add specific sources for scripts (script-src), styles (style-src), images (img-src), fetches (connect-src), fonts (font-src), and iframes (frame-src). It is a good practice to also add object-src 'none' and base-uri 'self' to further enhance security.

Avoid using wildcards (*), http:, unsafe-inline, or unsafe-eval in your CSP policy, as these can weaken the security provided by CSP. Instead, use nonces (one-time pass) or hashes for script and style tags to allow them to run securely. You can also use 'strict-dynamic' for scripts that are loaded later by trusted scripts.

Before enforcing CSP, it is recommended to run it in report-only mode. This allows you to see potential violations without blocking scripts. Monitor the reports for a week to identify any issues that might break your site. Once you have resolved these issues, switch to enforcing mode.

When checking your site's CSP using a tool like vuln, it will report any weaknesses found in the policy. If you see V02 indicating "Needs work", focus on fixing that first before proceeding. By implementing a well-configured CSP, you can significantly improve the security of your web pages and protect against various attacks.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

More from Friday 27 November →