BASH
Implement a Robust Content Security Policy (CSP) for XSS Defense
Configure a Content Security Policy (CSP) HTTP header to mitigate Cross-Site Scripting (XSS) attacks by controlling which resources your web page is allowed to load.
# Example Apache .htaccess or Nginx configuration
# This header can also be set programmatically in your server-side language.
# Apache (.htaccess or httpd.conf)
# Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' https://fonts.gstatic.com;"
# Nginx configuration (inside http or server block)
add_header Content-Security-Policy "default-src 'self';\
script-src 'self' https://cdn.jsdelivr.net https://code.jquery.com;\
style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com;\
img-src 'self' data: https://*.googleusercontent.com;\
font-src 'self' https://fonts.gstatic.com;\
connect-src 'self' ws://localhost:3001;\
object-src 'none';\
frame-ancestors 'self';\
base-uri 'self';" always;
# Explanation of directives:
# default-src 'self': Only allow resources from the same origin by default.
# script-src: Specifies valid sources for JavaScript.
# style-src: Specifies valid sources for stylesheets. 'unsafe-inline' is often needed for dynamic styles but should be minimized.
# img-src: Specifies valid sources for images, 'data:' allows data URIs.
# font-src: Specifies valid sources for fonts.
# connect-src: Specifies valid targets for XMLHttpRequest (AJAX), WebSockets, etc.
# object-src 'none': Disables <object>, <embed>, and <applet> tags.
# frame-ancestors 'self': Prevents framing of the page by other sites (Clickjacking prevention).
# base-uri 'self': Prevents injection of base tags that can change the origin for relative URLs.
# CSP can also be set via a <meta> tag, but HTTP headers offer stronger protection.
# <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
How it works: This snippet illustrates how to implement a Content Security Policy (CSP) using an HTTP header (shown for Nginx, but applicable to Apache and server-side code). CSP acts as a powerful defense against Cross-Site Scripting (XSS) and other data injection attacks by explicitly whitelisting the origins from which your web application is allowed to load resources like scripts, stylesheets, images, and fonts. Directives like `script-src`, `style-src`, and `default-src` define these trusted sources, while `object-src 'none'` and `frame-ancestors 'self'` offer additional protections against embedding untrusted content and clickjacking.