Getting Started with CSP Implementation

Getting Started with CSP Implementation

Beginning your CSP journey requires a methodical approach. Rather than attempting to implement a perfect policy immediately, start with monitoring and gradually tighten restrictions as you understand your application's needs.

Step 1: Audit Your Current Resources Before implementing CSP, catalog all the resources your application uses:

// Script to audit resource origins
const resources = {
    scripts: new Set(),
    styles: new Set(),
    images: new Set(),
    fonts: new Set()
};

// Monitor script sources
document.querySelectorAll('script[src]').forEach(script => {
    resources.scripts.add(new URL(script.src).origin);
});

// Monitor stylesheet sources
document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
    resources.styles.add(new URL(link.href).origin);
});

// Monitor image sources
document.querySelectorAll('img').forEach(img => {
    if (img.src) resources.images.add(new URL(img.src).origin);
});

console.log('Resource Audit:', resources);

Step 2: Create a Basic Policy Start with a permissive policy that reflects your current resource usage:

Content-Security-Policy-Report-Only: 
    default-src 'self';
    script-src 'self' 'unsafe-inline' https://cdn.example.com;
    style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
    img-src 'self' data: https:;
    font-src 'self' https://fonts.gstatic.com;
    connect-src 'self' https://api.example.com;
    report-uri /csp-report-endpoint;

Step 3: Deploy in Report-Only Mode Using Content-Security-Policy-Report-Only allows you to test your policy without breaking functionality:

// Express.js middleware for CSP reporting
app.use((req, res, next) => {
    res.setHeader('Content-Security-Policy-Report-Only', 
        "default-src 'self'; " +
        "script-src 'self' https://trusted-cdn.com; " +
        "report-uri /csp-violations"
    );
    next();
});

// Endpoint to receive CSP violation reports
app.post('/csp-violations', express.json({ type: 'application/csp-report' }), (req, res) => {
    console.log('CSP Violation:', req.body);
    // Log to your monitoring system
    res.status(204).end();
});

Step 4: Analyze Reports and Refine Monitor violation reports to identify legitimate resources and potential attacks:

// Sample CSP violation report
{
    "csp-report": {
        "blocked-uri": "https://unknown-analytics.com/track.js",
        "document-uri": "https://example.com/page",
        "violated-directive": "script-src",
        "effective-directive": "script-src",
        "original-policy": "default-src 'self'; script-src 'self' https://trusted-cdn.com"
    }
}