Opened 39 hours ago
Last modified 37 hours ago
#36831 assigned Cleanup/optimization
Add validation for CSP directive names and values in build_policy() — at Initial Version
| Reported by: | Naveed Qadir | Owned by: | |
|---|---|---|---|
| Component: | Utilities | Version: | 6.0 |
| Severity: | Normal | Keywords: | csp, validation |
| Cc: | Naveed Qadir | Triage Stage: | Unreviewed |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
The build_policy() function in django/utils/csp.py does not validate directive names or values, allowing malformed CSP policies to be generated.
Problem
CSP policies use semicolons to separate directives. If a directive name or value contains a semicolon (e.g., from a misconfiguration), it can result in a malformed policy:
from django.utils.csp import build_policy, CSP # This produces a malformed CSP header policy = {"script-src": ["https://good.com; report-uri https://evil.com"]} build_policy(policy) # Returns: "script-src https://good.com; report-uri https://evil.com" # The semicolon splits what should be one directive into two!
While this requires developer misconfiguration (not user input), it's a hardening improvement to catch these errors early with a clear error message rather than silently producing invalid policies.
Solution
Add validation to build_policy() that raises ValueError if:
- Directive names contain semicolons,
\r, or\n - Values contain semicolons
The error messages guide developers to use proper list syntax for multiple values.
Patch
A patch with tests is ready and will be submitted as a PR.