Skip to content

Security Headers Analyzer — C# source

Paste HTTP response headers to analyze security posture. Checks CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Security Headers - pure HTTP security-header analysis logic. No DOM,
// deterministic. Parses a raw response-header block (the "key: value" lines
// copied from DevTools' Network panel), grades each of 8 security headers
// A/B/C/F, and rolls a weighted overall score.
//
// Language: C# 12 / .NET 8 (standard library only)
// Source:   CosmoDev polyglot showcase port of the Security Headers tool,
//           ported from src/lib/security-headers.ts (the canonical TypeScript
//           implementation).
// License:  display source - part of CosmoDev's polyglot tool pages.
//
// Header names match case-insensitively, folded (indented) continuation lines
// join their parent value, and duplicate names join with ", ". Malformed
// lines and the HTTP status line are ignored. Never throws.

using System.Text.RegularExpressions;

/// <summary>Per-header grade: A best practice, B present but weak, C missing or dangerous, F actively harmful.</summary>
public enum HeaderGrade
{
    A,
    B,
    C,
    F,
}

/// <summary>One security header as analyzed: the parsed value plus its grade and guidance.</summary>
/// <param name="Name">Canonical name, e.g. "Strict-Transport-Security".</param>
/// <param name="Value">Raw value as parsed; null when the header is absent.</param>
/// <param name="Grade">The per-header grade.</param>
/// <param name="Explanation">Why this grade was given.</param>
/// <param name="Recommendation">How to improve, or "nothing to change" at grade A.</param>
public sealed record ParsedHeader(
    string Name,
    string? Value,
    HeaderGrade Grade,
    string Explanation,
    string Recommendation);

/// <summary>The full analysis result: per-header rows, the overall grade, and fix list.</summary>
public sealed record HeaderAnalysis(
    IReadOnlyList<ParsedHeader> Headers,
    HeaderGrade Grade,
    int Score,
    IReadOnlyList<string> Recommendations);

/// <summary>Catalog entry: canonical name, why the header matters, and its score weight.</summary>
public sealed record HeaderSpec(string Name, string Description, double Weight);

public static class SecurityHeaders
{
    /// <summary>The 8 security headers this analyzer grades, in display order.</summary>
    public static readonly IReadOnlyList<HeaderSpec> Catalog = new HeaderSpec[]
    {
        new("Strict-Transport-Security",
            "HSTS tells the browser 'only ever reach this site over HTTPS' for max-age seconds. It defeats SSL-strip attacks, which downgrade the very first plain-HTTP visit. includeSubDomains extends the guarantee to every subdomain; preload lets the site join the browser-built HSTS preload list so even the first visit is HTTPS.",
            1.5),
        new("Content-Security-Policy",
            "CSP is the strongest anti-XSS control available in a header: it declares which sources scripts, styles, and other resources may load from. 'unsafe-inline' and 'unsafe-eval' punch holes straight through it - they re-allow inline injection and string-to-code evaluation. A default-src directive is the baseline so resource types you forgot to list inherit a restrictive fallback instead of the browser's permissive one.",
            2),
        new("X-Frame-Options",
            "Stops other sites from embedding this page in an iframe, which is the basis of clickjacking: an attacker overlays invisible UI on your framed page and harvests the victim's clicks. DENY blocks all framing; SAMEORIGIN allows only your own origin. The modern replacement is the CSP frame-ancestors directive.",
            1),
        new("X-Content-Type-Options",
            "With the value nosniff, the browser must respect the declared Content-Type instead of 'helpfully' sniffing the payload. Sniffing turns an uploaded text file into executable JavaScript when its bytes look script-shaped - the classic content-type-confusion attack.",
            1),
        new("Referrer-Policy",
            "Controls how much of the URL the browser leaks in the Referer header when the user navigates to another site. Full URLs can carry IDs, tokens, or search queries to third parties. strict-origin-when-cross-origin sends only the origin cross-origin (the browser default since 2020); no-referrer and same-origin leak even less. unsafe-url sends the full URL everywhere, including on plain-HTTP requests.",
            1),
        new("Permissions-Policy",
            "Declares which browser features (camera, microphone, geolocation, payment, USB...) the page and its embedded iframes may use. An empty allowlist - feature=() - switches the feature off entirely; an =* wildcard re-allows it everywhere, defeating the point of declaring it.",
            1),
        new("X-XSS-Protection",
            "The 2010-era XSS Auditor: browsers inspected reflected input in the page and blocked obviously injected scripts. Chrome removed it in 2019 (its heuristics introduced cross-site leaks of their own) and every modern browser now ignores it. The header is deprecated - CSP is the real defense. Sites either omit it or send '0' to switch old browsers off.",
            0.5),
        new("Cross-Origin-Opener-Policy",
            "Isolates the page's window handle from other origins. Without COOP, a site that opened your page in a popup (or was opened by it) keeps a JS reference to it, enabling some cross-window attacks and Spectre-class side channels. same-origin cuts that shared handle; unsafe-none restores the old shared browsing context.",
            1),
    };

    /// <summary>Grade points used for the weighted overall score.</summary>
    private static readonly Dictionary<HeaderGrade, int> GradePoints = new()
    {
        [HeaderGrade.A] = 100,
        [HeaderGrade.B] = 70,
        [HeaderGrade.C] = 40,
        [HeaderGrade.F] = 0,
    };

    // One year in seconds - the minimum HSTS max-age worth calling strong.
    private const int OneYear = 31536000;

    private static readonly Regex MaxAgeRe = new("max-age\\s*=\\s*(\\d+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static readonly Regex IncludeSubdomainsRe = new(";\\s*includesubdomains", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static readonly Regex PreloadRe = new(";\\s*preload", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static readonly Regex UnsafeInlineRe = new("'unsafe-inline'", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static readonly Regex UnsafeEvalRe = new("'unsafe-eval'", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static readonly Regex DefaultSrcRe = new("(?:^|\\s)default-src\\s", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    private static readonly string[] ReferrerStrict = { "no-referrer", "same-origin", "strict-origin", "strict-origin-when-cross-origin" };
    private static readonly string[] ReferrerWeak = { "origin", "origin-when-cross-origin", "no-referrer-when-downgrade" };

    /// <summary>
    /// Parse a raw header block into a lowercased-name map. Lines are
    /// "name: value"; the "HTTP/1.1 200 OK" status line and any line without a
    /// colon are ignored. A line starting with space/tab continues the previous
    /// header (RFC 7230 obs-fold); a repeated name joins its values with ", ".
    /// </summary>
    public static Dictionary<string, string> ParseHeaders(string raw)
    {
        var headers = new Dictionary<string, string>();
        string? lastName = null;
        foreach (string line in (raw ?? string.Empty).Split('\n', '\r'))
        {
            if (line.Length > 0 && (line[0] is ' ' or '\t'))
            {
                // Folded continuation - append to the previous header, if any.
                if (lastName is not null)
                {
                    string prev = headers.TryGetValue(lastName, out string? existing) ? existing : string.Empty;
                    headers[lastName] = $"{prev} {line.Trim()}".Trim();
                }
                continue;
            }
            int colon = line.IndexOf(':');
            if (colon == -1) continue; // status line, blank line, or junk
            string name = line[..colon].Trim().ToLowerInvariant();
            if (name.Length == 0) continue;
            string value = line[(colon + 1)..].Trim();
            headers[name] = headers.TryGetValue(name, out string? prevValue)
                ? $"{prevValue}, {value}"
                : value;
            lastName = name;
        }
        return headers;
    }

    // --- Per-header graders: value (null when absent) -> grade + guidance ---

    /// <summary>The verdict fields every grader returns; folded into ParsedHeader.</summary>
    private sealed record Grading(HeaderGrade Grade, string Explanation, string Recommendation);

    private static Grading GradeHsts(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.",
                "Add: strict-transport-security: max-age=31536000; includeSubDomains; preload");
        }
        Match maxAgeMatch = MaxAgeRe.Match(value);
        if (!maxAgeMatch.Success)
        {
            return new Grading(HeaderGrade.B,
                $"Present but malformed - no readable max-age directive ({value}).",
                "Use: strict-transport-security: max-age=31536000; includeSubDomains");
        }
        long maxAge = long.Parse(maxAgeMatch.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
        if (maxAge == 0)
        {
            return new Grading(HeaderGrade.F,
                "max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.",
                "Raise max-age to at least 31536000 (one year).");
        }
        bool hasSubs = IncludeSubdomainsRe.IsMatch(value);
        if (maxAge < OneYear)
        {
            return new Grading(HeaderGrade.B,
                $"Present with max-age={maxAge}s (< 1 year){(hasSubs ? " and includeSubDomains" : "")} - a shorter window weakens the guarantee.",
                "Raise max-age to 31536000 (one year) or more.");
        }
        if (!hasSubs)
        {
            return new Grading(HeaderGrade.B,
                "Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.",
                "Append ; includeSubDomains once every subdomain serves HTTPS.");
        }
        bool hasPreload = PreloadRe.IsMatch(value);
        return new Grading(HeaderGrade.A,
            $"Strong: max-age >= 1 year + includeSubDomains{(hasPreload ? " + preload - eligible for the browser preload list." : ". Add preload to join the browser preload list.")}",
            "Best practice met - nothing to change.");
    }

    private static Grading GradeCsp(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.",
                "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ...");
        }
        bool inline = UnsafeInlineRe.IsMatch(value);
        bool evaluates = UnsafeEvalRe.IsMatch(value);
        if (inline && evaluates)
        {
            return new Grading(HeaderGrade.F,
                "Actively harmful - 'unsafe-inline' + 'unsafe-eval' together re-allow inline injection and string evaluation, gutting the policy while it still looks present.",
                "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts.");
        }
        if (inline || evaluates)
        {
            string culprit = inline ? "'unsafe-inline'" : "'unsafe-eval'";
            return new Grading(HeaderGrade.B,
                $"Present but weak - {culprit} punches a hole through the anti-XSS guarantee.",
                $"Remove {culprit}; use nonces or hashes for legitimate inline code.");
        }
        if (!DefaultSrcRe.IsMatch(value))
        {
            return new Grading(HeaderGrade.B,
                "Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.",
                "Start the policy with default-src 'none' or 'self', then allow what you need.");
        }
        return new Grading(HeaderGrade.A,
            "Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.",
            "Best practice met - nothing to change.");
    }

    private static Grading GradeFrameOptions(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - any site can embed this page in an iframe and overlay it (clickjacking).",
                "Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)");
        }
        string v = value.Trim().ToUpperInvariant();
        if (v is "DENY" or "SAMEORIGIN")
        {
            return new Grading(HeaderGrade.A,
                $"Strong - {v} blocks framing by other origins.",
                "Best practice met - nothing to change.");
        }
        if (v.StartsWith("ALLOW-FROM", StringComparison.Ordinal))
        {
            return new Grading(HeaderGrade.B,
                "ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.",
                "Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback).");
        }
        return new Grading(HeaderGrade.B,
            $"Unrecognized value ({value}) - browsers ignore it, leaving the page frameable.",
            "Use DENY or SAMEORIGIN.");
    }

    private static Grading GradeContentTypeOptions(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - browsers may sniff uploaded content into executable types.",
                "Add: x-content-type-options: nosniff");
        }
        if (value.Trim().ToLowerInvariant() == "nosniff")
        {
            return new Grading(HeaderGrade.A,
                "Strong - MIME sniffing is off; the declared Content-Type is final.",
                "Best practice met - nothing to change.");
        }
        return new Grading(HeaderGrade.B,
            $"Present but the value ({value}) is not nosniff, so browsers ignore the header.",
            "Send exactly: x-content-type-options: nosniff");
    }

    private static Grading GradeReferrerPolicy(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - older browsers default to leaking the full URL to whatever site the user navigates to.",
                "Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)");
        }
        string v = value.Trim().ToLowerInvariant();
        if (v == "unsafe-url")
        {
            return new Grading(HeaderGrade.F,
                "Actively harmful - unsafe-url sends the full URL (including IDs and tokens in query strings) to every destination, even on plain HTTP.",
                "Use strict-origin-when-cross-origin or no-referrer instead.");
        }
        if (ReferrerStrict.Contains(v))
        {
            return new Grading(HeaderGrade.A,
                $"Strong - {v} leaks at most the origin cross-origin.",
                "Best practice met - nothing to change.");
        }
        if (ReferrerWeak.Contains(v))
        {
            return new Grading(HeaderGrade.B,
                $"Present but leaky - {v} still shares the full URL in some same- or cross-origin cases.",
                "Tighten to strict-origin-when-cross-origin, strict-origin, same-origin, or no-referrer.");
        }
        return new Grading(HeaderGrade.B,
            $"Unrecognized value ({value}) - browsers fall back to their default policy.",
            "Use one of the standard directives, e.g. strict-origin-when-cross-origin.");
    }

    private static Grading GradePermissionsPolicy(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.",
                "Add: permissions-policy: camera=(), microphone=(), geolocation=()");
        }
        string v = Regex.Replace(value, "\\s+", "").ToLowerInvariant();
        if (v.Length == 0)
        {
            return new Grading(HeaderGrade.B,
                "Present but empty - no feature is restricted, so it declares nothing.",
                "List the features to switch off, e.g. camera=(), microphone=().");
        }
        if (v == "*" || v.Contains("=*"))
        {
            return new Grading(HeaderGrade.B,
                "Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.",
                "Use an empty allowlist () or a specific origin instead of *.");
        }
        return new Grading(HeaderGrade.A,
            "Strong - the policy restricts at least one powerful feature.",
            "Best practice met - nothing to change.");
    }

    private static Grading GradeXssProtection(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.A,
                "Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.",
                "Nothing to change - rely on Content-Security-Policy instead.");
        }
        string v = value.Trim();
        if (v == "0" || v.StartsWith("0;", StringComparison.Ordinal))
        {
            return new Grading(HeaderGrade.A,
                "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.",
                "Nothing to change - or remove the header entirely.");
        }
        if (v.StartsWith('1'))
        {
            return new Grading(HeaderGrade.B,
                "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.",
                "Send '0' or drop the header; use Content-Security-Policy for XSS defense.");
        }
        return new Grading(HeaderGrade.B,
            $"Present with an unrecognized value ({value}) - remove the deprecated header.",
            "Send '0' or drop the header entirely.");
    }

    private static Grading GradeCoop(string? value)
    {
        if (value is null)
        {
            return new Grading(HeaderGrade.C,
                "Missing - pages that open or are opened by other origins share a browsing context with them.",
                "Add: cross-origin-opener-policy: same-origin");
        }
        string v = value.Trim().ToLowerInvariant();
        if (v == "same-origin")
        {
            return new Grading(HeaderGrade.A,
                "Strong - the window handle is isolated from cross-origin openers.",
                "Best practice met - nothing to change.");
        }
        if (v == "same-origin-allow-popups")
        {
            return new Grading(HeaderGrade.B,
                "Partially isolated - popups you open keep a reference to this window.",
                "Use same-origin unless you genuinely need cross-origin popup handles.");
        }
        if (v == "unsafe-none")
        {
            return new Grading(HeaderGrade.B,
                "Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.",
                "Use same-origin unless a documented integration requires shared handles.");
        }
        return new Grading(HeaderGrade.B,
            $"Unrecognized value ({value}) - browsers treat it as no COOP.",
            "Use same-origin.");
    }

    // Compile-time-complete grader table: every catalog name has a grader.
    private static readonly Dictionary<string, Func<string?, Grading>> Graders = new()
    {
        ["Strict-Transport-Security"] = GradeHsts,
        ["Content-Security-Policy"] = GradeCsp,
        ["X-Frame-Options"] = GradeFrameOptions,
        ["X-Content-Type-Options"] = GradeContentTypeOptions,
        ["Referrer-Policy"] = GradeReferrerPolicy,
        ["Permissions-Policy"] = GradePermissionsPolicy,
        ["X-XSS-Protection"] = GradeXssProtection,
        ["Cross-Origin-Opener-Policy"] = GradeCoop,
    };

    /// <summary>Map a weighted 0-100 score to the overall A/B/C/F grade.</summary>
    private static HeaderGrade OverallGrade(int score) => score switch
    {
        >= 90 => HeaderGrade.A,
        >= 70 => HeaderGrade.B,
        >= 45 => HeaderGrade.C,
        _ => HeaderGrade.F,
    };

    /// <summary>
    /// Analyze a raw HTTP response-header block. Every catalog header gets a
    /// ParsedHeader row (in catalog order); the overall score is the
    /// weight-adjusted average of per-header grade points, and recommendations
    /// list one fix per header that is not at grade A.
    /// </summary>
    public static HeaderAnalysis AnalyzeHeaders(string raw)
    {
        Dictionary<string, string> parsed = ParseHeaders(raw);
        var headers = new List<ParsedHeader>();
        foreach (HeaderSpec spec in Catalog)
        {
            string? value = parsed.TryGetValue(spec.Name.ToLowerInvariant(), out string? v) ? v : null;
            Grading g = Graders[spec.Name](value);
            headers.Add(new ParsedHeader(spec.Name, value, g.Grade, g.Explanation, g.Recommendation));
        }
        double totalWeight = Catalog.Sum(spec => spec.Weight);
        double weighted = headers.Select((h, i) => GradePoints[h.Grade] * Catalog[i].Weight).Sum();
        int score = (int)Math.Round(weighted / totalWeight, MidpointRounding.AwayFromZero);
        List<string> recommendations = headers
            .Where(h => h.Grade != HeaderGrade.A)
            .Select(h => h.Recommendation)
            .ToList();
        return new HeaderAnalysis(headers, OverallGrade(score), score, recommendations);
    }
}

Also available in 8 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →