Among attacks against websites Cross-Site Scripting or XSS is one of the most widespread. In such attacks an attacker tries to inject malicious code into a site page and execute it in other users browsers. As a result sessions, passwords and personal data can be stolen. One of the most effective protection methods is using the Content Security Policy header.
How CSP Works
CSP is a special HTTP header that tells the browser which resources can be loaded on the page and which cannot. The server passes a list of allowed sources and the browser loads resources only from there. Even if an attacker somehow injects malicious script, the browser will not execute it.
The strength of CSP is that protection works at browser level and requires no additional server logic. After header configuration all defense runs on the client side which is fast and reliable. CSP controls not only scripts but also images, styles, frames and other resources.
Main Directives
The CSP header uses several directives each with its own task. Default-src is a general fallback defining where resources can be loaded from by default. Script-src targets scripts specifically and must be set separately because scripts are the main XSS target. Style-src is for styles, img-src for images, frame-src for frames.
Configuration Examples
For a regular site a starter CSP can look like this. Default-src allows only the current site, script-src adds Google Fonts and analytics, style-src uses the same sources. This is enough to protect most simple sites and block typical XSS attacks.
For complex sites nonce or hash mechanisms are needed. Nonce is a random token that changes on each page load and is used to allow inline scripts. This is powerful because an attacker cannot know the nonce value in advance.
Common Mistakes
The first common mistake is adding unsafe-inline to script-src. This almost completely disables CSP protection because it allows all inline scripts which are the main XSS attack tool. If inline scripts are needed use nonce or hash instead.
Report-only Mode
Enabling CSP in enforce mode immediately is risky because some resources might be blocked and the site could break. It is recommended to run report-only mode for the first week. Violations are logged but resources are not blocked allowing safe error fixing.
Sayt.uz Practice
Among our hosting users 73 percent of sites do not have CSP configured and this is a serious security concern. Sites with configured CSP show on average 89 percent reduction in XSS incidents according to our statistics. The Sayt.uz panel offers automatic CSP header setup with standard configurations. For complex sites we offer a CSP audit service from 320 thousand sums.