Skip to content

Latest commit

 

History

History
187 lines (139 loc) · 7.57 KB

tab_codesnippets.md

File metadata and controls

187 lines (139 loc) · 7.57 KB
title displaytext layout tab order tags
codesnippets
Code Snippets
true
5
headers

Code Snippets

🧾 The following code collection provides various code snippets to make working with HTTP security headers easier.

Convert a Permissions-Policy back to Feature-Policy

As the Permissions-Policy header is still in development and is not yet well supported, it can be interesting to use the two formats to increase the coverage of browsers according to their support level for Permissions-Policy and Feature-Policy policy headers.

The following python3 code snippet can be useful to achieve such conversion.

📑 Source for the conversion rules was this one.

💻 Code snippet:

permissions_policy = 'fullscreen=(), geolocation=(self "https://game.com" "https://map.example.com"), gyroscope=(self), usb=*'
feature_policy_directives = []
# Collect directives
permissions_policy_directives = permissions_policy.split(",")
# Process each directive
for permissions_policy_directive in permissions_policy_directives:
    # Remove leading and trailing spaces
    directive = permissions_policy_directive.strip(" ")
    # Remove all double quotes
    directive = directive.replace("\"", "")
    # Replace disabling expression () by the corresponding one in Feature-Policy
    directive = directive.replace("()", "'none'")
    # Quote keywords: self
    directive = directive.replace("self", "'self'")
    # Replace the equals affectation character by a space
    directive = directive.replace("=", " ")
    # Remove parenthesis
    directive = directive.replace("(", "").replace(")", "")
    # Add the current directive to the collection
    feature_policy_directives.append(directive)
# Convert the collection of directives to a string with ; as directives separator
feature_policy = "; ".join(feature_policy_directives)
print(feature_policy)

💻 Execution example:

$ python code.py
fullscreen 'none'; geolocation 'self' https://game.com https://map.example.com; gyroscope 'self'; usb *

Test locally a Content-Security-Policy for weaknesses

It can be interesting to validate locally a Content-Security-Policy for presence of weaknesses prior to apply it on deployed web applications.

The following JavaScript code snippet can be useful to achieve such validation by leveraging the csp-evaluator NPM module provided by Google.

💻 Code snippet:

import {CspEvaluator} from "csp_evaluator/dist/evaluator.js";
import {CspParser} from "csp_evaluator/dist/parser.js";

const args = process.argv.slice(2)
if(args.length == 0){
    console.error("[!] Missing CSP!");
}else{
    const csp = args[0]
    console.info(`[+] CSP to evaluate:\n${csp}`);
    const parsed = new CspParser(csp).csp;
    console.info(`[+] Evaluation results:`);
    const results = new CspEvaluator(parsed).evaluate();
    results.forEach(elt => {
        let info = `[Directive '${elt.directive}' - Severity ${elt.severity}]: ${elt.description}`;
        console.info(info);
    });
}

💻 Execution example:

$ node code.js "default-src 'self'; object-src 'none'; frame-ancestors 'none'; upgrade-insecure-requests; block-all-mixed-content"
[+] CSP to evaluate:
default-src 'self'; object-src 'none'; frame-ancestors 'none'; upgrade-insecure-requests; block-all-mixed-content
[+] Evaluation results:
[Directive 'default-src' - Severity 50]: 'self' can be problematic if you host JSONP, Angular or user uploaded files.

Generate configuration code using the OSHP headers reference files

The following bash code snippet, leveraging jq, can be used to generate configuration code using the OSHP headers reference files.

💻 Code snippet and execution example:

# Generate the Nginx collection of instructions to add the recommended HTTP response headers
$ curl -sk https://owasp.org/www-project-secure-headers/ci/headers_add.json | jq -r '.headers[] | "add_header \(.name) \(.value);"'
add_header Cache-Control no-store, max-age=0;
add_header Clear-Site-Data "cache","cookies","storage";
add_header Cross-Origin-Embedder-Policy require-corp;
...

Quickly check security HTTP headers

The portable cross-platform tool Venom with the dedicated OSHP Validator test suites aligned with the OWASP Secure Headers Project can be used.

💻 Use the following example set of commands:

$ venom run --var="target_site=https://mozilla.org" --var="logout_url=/logout" tests_suite.yml
• HTTP security response headers test suites
    • Strict-Transport-Security SUCCESS
    • X-Frame-Options SUCCESS
    • X-Content-Type-Options SUCCESS
    • Content-Security-Policy FAILURE
    • X-Permitted-Cross-Domain-Policies SUCCESS
    • Referrer-Policy SUCCESS
    • Clear-Site-Data SUCCESS
    • Cross-Origin-Embedder-Policy SUCCESS
    • Cross-Origin-Opener-Policy SUCCESS
    • Cross-Origin-Resource-Policy SUCCESS
    • Permissions-Policy SUCCESS    
    • Cache-Control SUCCESS    
    • Feature-Policy SUCCESS
        [info] This header was split into Permissions-Policy and Document-Policy and will be considered deprecated once all impacted features are moved off of feature policy.
    • Public-Key-Pins SUCCESS
        [info] This header has been deprecated by all major browsers and is no longer recommended. Avoid using it, and update existing code if possible!
    • Expect-CT SUCCESS
        [info] This header will likely become obsolete in June 2021. Since May 2018 new certificates are expected to support SCTs by default. Certificates before March 2018 were allowed to have a lifetime of 39 months, those will all be expired in June 2021.
    • X-Xss-Protection SUCCESS
        [info] The X-XSS-Protection header has been deprecated by modern browsers and its use can introduce additional security issues on the client side.

Syntax for adding HTTP response headers on different web servers

Apache

💻 Directive:

Header always set [HEADER_NAME] [PROPOSED_VALUE]

🌎 References:

Nginx

💻 Directive:

add_header [HEADER_NAME] [PROPOSED_VALUE] always;

🌎 References:

Lighttpd

💻 Directive:

setenv.add-response-header = ("[HEADER_NAME]" => "[PROPOSED_VALUE]")

🌎 References:

IIS

💻 Directive:

<add name="[HEADER_NAME]" value="[PROPOSED_VALUE]" />

🌎 References: