Please visit the original link: sysin.org/article/sec… To view the latest version. Reprint please retain the source.

Author: GC (at)sysin.org, homepage: www.sysin.org

Common security Header definition

1. Strict-Transport-Security (HSTS)

HTTP Strict Transport Security (often referred to simply as HSTS) is a Security feature that tells the browser to access the current resource only through HTTPS, not HTTP.

What it does: Access an HTTPS web site, requiring that the browser always access it over HTTPS.

Grammar:

strict-transport-security: max-age=<expire-time>
strict-transport-security: max-age=<expire-time>; includeSubDomains
strict-transport-security: max-age=<expire-time>; includeSubDomains; preload
Copy the code

Example:

strict-transport-security: max-age=31536000; includeSubDomains; preload
Copy the code

Definition:

  • max-age=<expire-time>Set HTTPS to be used for all requests under this domain name within seconds after the browser receives the request.
  • includeSubDomainsOptional. If this parameter is specified, this rule also applies to all subdomains of the site.
  • preloadOptional. Add it to the preload list

Google maintains an HSTS preload service. After successfully submitting your domain name following the instructions below, the browser will never use an unsecured way to connect to your domain. Although the service is provided by Google, all browsers intend to use the list (or already use it). However, this is not part of the HSTS standard and should not be considered official.

  • HSTS preloaded list for Chrome & Chromium: www.chromium.org/hsts
  • Firefox HSTS preload list: nsstspreloadList.inc

Enter Chrome ://net-internals/# HSTS to enter the HSTS management interface. You can add, delete, or query HSTS records. Add the site to the preload list: hstspreload.org/

HTTP Strict Transport Security (HSTS)

2. Public-key-pins (HPKP)

Effect: Prevents man-in-the-middle attacks. It is a security mechanism used by HTTPS websites to prevent attackers from carrying out man-in-the-middle attacks using the certificate incorrectly issued by the CA. It is used to prevent THE CA from being hacked or other situations that may cause the CA to issue unauthorized certificates.

The server passes HTTP Public Key fixation information to the browser via public-key-pins (or public-key-report-onKY for monitoring) headers.

Grammar:

Public-Key-Pins: pin-sha256="base64=="; max-age=expireTime [; includeSubdomains][; report-uri="reportURI"]
Copy the code

Parameter Meaning:

  • Pin-sha256: the certificate fingerprint can appear more than once. In fact, at least two certificates should be specified
  • Max-age: indicates the expiration time
  • IncludeSubdomains: whether to includeSubdomains
  • Report-uri: indicates the address reported when authentication fails

Reference: Public – Key – Pins

3. Content-security-policy (CSP)

X-content-security-policy (old version)/content-security-Policy

CSP is a computer security symbol, mainly used to prevent XSS, click hijacking, SQL injection and other attacks; CSP prevents the loading of malicious code by defining where and what to run load scripts.

Function: Defines the resources that can be loaded on a page, reduces and reports XSS attacks, and prevents packet sniffing attacks.

Header:

  • Content-Security-Policy
  • X-Content-Security-Policy
  • X-Webkit-CSP

Usage:

Content-Security-Policy: default-src 'self'
Copy the code
  • A policy consists of a series of policy directives, each of which describes a policy for a particular type of resource and its scope of effect.
  • Default-src is a CSP directive. Multiple directives are separated by semicolons (;).
  • Self is an instruction value separated by English Spaces.
  • Supported CSP directives.

The element can also be used to configure CSP:

instruction Instruction value example instructions
default-src ‘self’ cnd.a.com Defines a default load policy for all types of resources. If no separate policy is defined for a type of resource, the default is used
script-src ‘self’ js.a.com Define loading policies for JavaScript
style-src ‘self’ css.a.com Define the loading strategy for the style
img-src ‘self’ img.a.com Define loading policies for images
connect-src ‘self’ Load strategy for Ajax, WebSocket, etc. When not allowed, the browser simulates a response with a status of 400
font-src font.a.com Load strategy for WebFont
object-src ‘self’ <object>, <embed>, <applet> and other tags for the introduction of flash plug-in loading strategy
media-src media.a.com HTML multimedia loading strategy for tags such as <audio> and <video>
frame-src ‘self’ Load policy for frame
sanbox allow-forms Enable sandbox for the requested resource (similar to the sandbox property of iframe)
report-uri /report-uri Tells the browser which address to submit log information to if the request is not allowed by the policy. If you want the browser to Report Only logs without blocking anything, use the Content-security-policy-report-only header instead

An instruction value can consist of the following:

Instruction value Instruction value example instructions
img-src Allow anything
‘none’ img-src ‘none’ No content is allowed
‘self’ img-src ‘self’ Allow content from the same source (same protocol, domain name, and port)
data: img-src data: Allow data: protocols (such as Base64 encoded images)
www.a.com img-src img.a.com Allows resources of a specified domain name to be loaded
.a.com img-src .a.com Allows to load resources from any subdomain of a.com
img.com img-src img.com Allows HTTPS resources for img.com to be loaded
https: img-src https: HTTPS resources can be loaded
‘unsafe-inline’ script-src ‘unsafe-inline’ Allows loading of inline resources (such as common style attributes, onclick, inline JS, inline CSS)
‘unsafe-eval’ script-src ‘unsafe-eval’ Allows loading of dynamic JS code, such as eval()

Violation report

  • Document-uri: URI of the document where the violation occurred.
  • Referrer: The address of the document reference where the violation occurred
  • Blocked – URI: resource URI blocked by CS P. If the blocked URI is from a different source than the document URI, the blocked resource URI is stripped, keeping only the protocol, host, and port numbers.
  • Proffer -directive: name of the violated policy
  • Original-policy: Indicates the original policy specified in the Content-security-policy HTTP header.

Example: Enable the browser to automatically upgrade a request and replace it with an HTTPS request when accessing an HTTP resource

Content-Security-Policy: upgrade-insecure-requests
Copy the code

Reference: Content security Policy CSP

4. Referrer-Policy

Used to regulate which access source information — sent in the Referer — should be included in the generated request. (Note that Referer is actually a misspelling of the word “referrer.” The referreer-policy header does not continue this misspelling.

Role: Increased privacy protection.

grammar

Referrer-Policy: no-referrer
Referrer-Policy: no-referrer-when-downgrade
Referrer-Policy: origin
Referrer-Policy: origin-when-cross-origin
Referrer-Policy: same-origin
Referrer-Policy: strict-origin
Referrer-Policy: strict-origin-when-cross-origin
Referrer-Policy: unsafe-url
Copy the code

Configurable value:

  • No-referrer: not allowed to be recorded.
  • Origin: Records only the origin, that is, the domain name.
  • Strict-origin: indicates that the origin is recorded only between HTTPS -> HTTPS.
  • Strict-origin-when -cross-origin: Indicates that the same origin request sends the complete URL. HTTPS->HTTPS, sending source; Demote does not send this header.
  • No-referrer-when -downgrade(default) : same as strict-origin.
  • Origin-when -cross-origin: For same-origin requests, the full URL is sent as the reference address, but for non-same-origin requests, only the source of the file is sent.
  • Same-origin: For same-origin requests, the full URL is sent. For non-same-origin requests, the referer is not sent.
  • Unsafe-url: The unsafe-url (after removing parameter information) is sent as the reference address for both same-origin and non-same-origin requests. (Sensitive information may be disclosed).

Reference: the Referrer – Policy

5. Expect-CT

The Expect-CT header allows sites to selectively report and/or enforce Certificate Transparency requirements to prevent the undetected use of wrongly issued web site certificates. When a site turns on the Expect-CT header, it is asking the browser to check whether any of the site’s certificates appear in the public certificate transparency log.

Another interpretation: the timestamp used to instruct the browser or client to validate the signed certificate

grammar

Expect-CT: report-uri="<uri>";
           enforce;
           max-age=<age>
Copy the code

instruction

  • max-age

    This directive specifies the number of seconds after receiving the Expect-CT head, during which the user agent should treat the host receiving the message as a known Expect-CT host. If the cache receives a value greater than what it can represent, or if it subsequently computes an overflow, the cache will consider the value to be 2147483648 (the 31st power of 2) or the largest positive integer it can easily represent.

  • The report – a uri = “optional”

    This directive specifies the URI to which the user agent should report the Expect-CT failure. When both the Enforce and report-URI directives exist, this configuration is called the enforce and report configuration, implying that the user agent should both enforce compliance with the certificate transparency policy and report violations.

  • Enforce the optional

    This directive implies that the user agent should enforce compliance with the certificate transparency policy (rather than just reporting compliance) and that the user agent should reject subsequent connections that violate the certificate transparency policy. When both the Enforce and report-URI directives exist, this configuration is called the enforce and report configuration, implying that the user agent should both enforce compliance with the certificate transparency policy and report violations.

The sample

The following example specifies a 24-hour certificate transparency implementation and reports violations to foo.example.

Expect-CT: max-age=86400; enforce; report-uri="https://foo.example/report"
Copy the code

Reference: Expect – CT

6. Access-Control-Allow-Origin

The access-Control-allow-Origin response header specifies whether the resources for the response are allowed to be shared with the given Origin. Cross-source sharing (CORS) allows web sites to share content between them. In order to secure cross-domain Access between web sites, you can set access-Control-allow-Origin to Allow specific web sites to cross-domain Access to local resources.

Only when the response of the target page contains the access-Control-allow-origin header and the value contains the domain name of the target page, the browser allows the target page to obtain the data of the page.

For example, only “10.10.10.10” is allowed to access local resources

Access - Control - Allow - Origin: http://10.10.10.10Copy the code

grammar

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
Copy the code

instruction

*

For requests that do not require credentials, the server uses * as the wildcard character, allowing all domains to access resources.

<origin>

Specify a URL to access the resource.

Reference: Access – Control – Allow – Origin

7. Cache-Control

Cache-control A generic header field used to specify directives to implement caching in HTTP requests and responses. Cache directives are one-way, which means that directives set in the request are not necessarily included in the response.

The cache mechanism can reduce the occupation of network bandwidth, improve the access speed, and improve user experience. The cache mechanism can improve security when certain requests are prohibited.

grammar

Instructions are case insensitive and have optional arguments, which can be token or quoted string syntax. Multiple instructions are separated by commas.

  • Cache request instruction

A standard cache-control directive that clients can use in HTTP requests.

Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]
Cache-Control: min-fresh=<seconds>
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: only-if-cached
Copy the code
  • Cache response instruction

Standard cache-control instructions that the server can use in response.

Cache-control: must-revalidate
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: public
Cache-control: private
Cache-control: proxy-revalidate
Cache-Control: max-age=<seconds>
Cache-control: s-maxage=<seconds>
Copy the code
  • extensionCache-Controlinstruction

The extended cache directive is not part of the core HTTP cache standard document. Please check compatibility before using it.

Cache-control: immutable
Cache-control: stale-while-revalidate=<seconds>
Cache-control: stale-if-error=<seconds>
Copy the code

instruction

  • The cache can be

    • public

      Indicates that the response can be cached by any object (including the client that sent the request, the proxy server, and so on), even content that is not normally cacheable. (E.g. 1. The response does not have a Max-age directive or Expires header; 2. The request method corresponding to this response is POST.

    • private

      Indicates that the response can only be cached by a single user and not as a shared cache (that is, the proxy server cannot cache it). The private cache can cache the response content, for example, the corresponding user’s local browser.

    • no-cache

      The cache is forced to submit the request to the original server for validation (negotiated cache validation) before the cache copy is published.

    • no-store

      The cache should not store anything about the client request or the server response, that is, no cache is used.

  • Due to

    • max-age=<seconds>

      Sets the maximum period for which the cache is stored, after which the cache is considered expired in seconds. In contrast to Expires, time is the time relative to the request.

    • s-maxage=<seconds>

      Overrides max-age or Expires headers, but only for shared caches (such as individual agents) and private caches ignore them.

    • max-stale[=<seconds>]

      Indicates that the client is willing to accept an expired resource. An optional number of seconds can be set to indicate that the response cannot be out of date beyond that given time.

    • min-fresh=<seconds>

      Indicates that the client wants to get a response that will keep it up to date for a specified number of seconds.

    • stale-while-revalidate=<seconds>

      Indicates that the client is willing to accept stale responses while asynchronously checking for new ones in the background. The second value indicates how long the customer is willing to accept stale responses.

    • stale-if-error=<seconds>

      Indicates that the customer is willing to accept the stale response if the new check fails. The second value represents how long the customer is willing to accept stale responses after the initial expiration.

  • Revalidate and reload

    • must-revalidate

      Once a resource expires (such as if it has exceeded max-age), the cache cannot respond to subsequent requests with the resource until it is successfully validated to the original server.

    • proxy-revalidate

      It has the same effect as must-revalidate, but applies only to shared caches (such as proxies) and is ignored by private caches.

    • immutable

      Indicates that the response body does not change over time. Resources (If not expired) do not change on the server, so the client should not send a revalidation request header (such as if-none-match or if-modified-since) to check for updates, even If the user explicitly refreshes the page. In Firefox, immutable is only used in https:// transactions. See here for more information.

  • other

    • no-transform

      Resources may not be converted or converted. HTTP headers such as content-encoding, content-range, and Content-Type cannot be modified by the proxy. For example, an opaque proxy or something like Google’s Light Mode might convert image formats to save cache space or reduce traffic on slow links. The no-transform directive does not allow this.

    • only-if-cached

      Indicates that the client accepts only cached responses and does not check with the original server for newer copies.

Reference: cache-control

8. Set-Cookie

Cookies are sent from the server to the client

Grammar:

Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly

Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Strict
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax

// Multiple directives are also possible, for example:
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
Copy the code

Safety related:

  • HttpOnly: Prevents the use of javascript (such as document.cookie) to access cookies
  • Secure: Forces cookies to be transmitted only in THE HTTPS environment

Reference: the Set – cookies

9. X-Frame-Options

Tags that allow a page to be displayed in < frame >, < iframe >, < embed >, or < object >. (Note: there is no space between <>, which will cause the content of the article to be distorted if it is written in HTML)

  • Frame tag: Frame tag that places an HTML document (page)

  • Iframe tag: Inline frame tag that displays (inserts) another HTML page in one HTML page

  • Embed tag: Audio element tag that inserts an audio element

  • Object tag: Container tag that defines external content

Purpose: Reduce/avoid clickjacking attacks.

Grammar:

X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
X-Frame-Options: ALLOW-FROM https://example.com/
Copy the code

The response header supports three configurations:

  • DENY: indicates that the page is not allowed to be displayed in the frame, even if the page is nested in the same domain name.
  • SAMEORIGIN: indicates that the page can be displayed in the frame of the same domain name page.
  • Allow-from URI: indicates that the page can be displayed in the frame FROM the specified source.

Reference: X – Frame – the Options

10. X-XSS-Protection

HTTP X-XSS-protection response header is a feature of Internet Explorer, Chrome, and Safari that stops the browser from loading the page when a cross-site scripting attack (XSS) is detected. If a site has a good Content-security-policy to disable inline JavaScript (‘unsafe-inline’), these protections are less needed in modern browsers, but can still be protected for users of older browsers that do not yet support CSP.

Function: Defends against XSS attacks.

PS: This is an old property that can be replaced basically by CSP, but still provides a layer of protection for browsers that don’t yet support CSP. XSS protection is enabled by default in all major browsers.

Grammar:

X-XSS-Protection: 0
X-XSS-Protection: 1
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=<reporting-uri>
Copy the code

Definition:

  • 0: disables XSS filtering.
  • 1: Enable XSS filtering (usually the default for browsers). If a cross-site scripting attack is detected, the browser wipes out the page (removing unsafe portions).
  • 1; Mode =block: XSS filtering is enabled. If an attack is detected, the browser will not clear the page, but block the page from loading.
  • 1; Report = (Chromium only) : Enable XSS filtering. If a cross-site scripting attack is detected, the browser clears the page and uses CSPreport-uriCommand function sends violation reports.

Reference: X – XSS – Protection

11. X-Content-Type-Options

X-content-type-options THE HTTP header is a flag that the server uses to tell the client that it must adhere to the MIME Type specified in the content-Type header and that it cannot be modified. This disables the MIME type sniffing behavior of the client.

Action: Disables the content-type guessing behavior of the browser.

Background: Browsers typically identify resource types based on the content-Type field in the response header. Some resources have incorrect or undefined content-Types. The browser will enable MIME-Sniffing to guess the type of resource, parse the content, and execute. Using this feature, an attacker can cause a request that should be parsed as a picture to be parsed as JavaScript.

Usage:

X-Content-Type-Options: nosniff
Copy the code

Reference: X – the content-type – Options

12. X-Permitted-Cross-Domain-Policies

Used to specify the type of cross-domain policy files that clients can access.

A cross-domain policy file is an XML file used to grant Web client applications permission to process cross-domain data, such as Adobe Flash and Adobe Reader. When a client requests content hosted on a domain other than its own, the remote domain needs to configure a cross-domain policy file to authorize access to the requesting domain so that the client can continue to interact accordingly.

grammar

X-Permitted-Cross-Domain-Policies: none
X-Permitted-Cross-Domain-Policies: master-only
X-Permitted-Cross-Domain-Policies: by-content-type
X-Permitted-Cross-Domain-Policies: by-ftp-filename
X-Permitted-Cross-Domain-Policies: all
Copy the code

paraphrase

  • None: Policy files are not allowed anywhere on the target server, including the main policy file
  • Master-only: only the master policy file can be used
  • By-content-type: specifies the policy file provided by content-type: text/x-cross-domain-policy. This parameter is valid only for HTTP or HTTPS
  • By-ftp-filename: applies only to FTP. Only the crossdomain-xml policy file can be used
  • All: All policy files in the target domain can be used

13. Permissions-Policy (feature-policy)

On July 16, 2020, the W3C released the specification, and the Feature Policy was officially renamed as Permissions Policy. (See: feature-policy exit, Permissions-Policy welcome!)

Feature Policy is a new HTTP response header property that allows a site to enable or disable some browser properties and apis to better ensure site security and privacy. It is similar to content security policies, but it controls browser characteristics rather than security behavior.

As with any other HTTP security response header setup, you just need to specify the page’s specific restriction policy and return the corresponding policy in the HTTP response header:

Feature-Policy: vibrate 'self'; usermedia '*'; sync-xhr 'self' example.com
Copy the code

grammar

Feature-Policy: <feature> <allowlist>
Copy the code

List of browser properties and apis that are enabled or disabled

The list of browser attributes and apis that are enabled or disabled is not yet fully finalized. For example, Mozilla can use the see Features list:

    Accelerometer
    Ambient light sensor
    Autoplay
    Camera
    Encrypted media
    Fullscreen
    Geolocation
    Gyroscope
    Magnetometer
    Microphone
    Midi
    PaymentRequest
    Picture-in-picture
    USB
    VR / XR
Copy the code

For now, there are a couple of ways to see what features are controllable.

  • Check out our Feature Policy Kitchen Sink of demos. It has examples of each policy that’s been implemented in Blink.

  • Check Chrome’s source for the list of feature names.

  • Query document.featurePolicy.allowedFeatures() on about:blank to find the list:

    ["geolocation",
     "midi",
     "camera",
     "usb",
     "magnetometer",
     "fullscreen",
     "animations",
     "payment",
     "picture-in-picture",
     "accelerometer",
     "vr",
    ...
    Copy the code
  • Check [chromestatus.com] (www.chromestatus.com/features#co… Blink>FeaturePolicy) for the policies that have been implemented or are being considered in Blink.

Value, you can take multiple values at the same time

  • * : Both pages and embedded iframes are allowed.
  • ‘self’ : allowed on the page, only allowed within embedded iframes for same-origin resources.
  • ‘SRC’ : an attribute that is valid only within an IFrame. Only resources whose SRC attribute is valid within an IFrame are allowed to be used with the same set header.
  • ‘None’ : Disables all on the page and inline.

  • : Allows use within a specific origin, where multiple origins can be separated by Spaces.
    (s)>

‘*’ and ‘none’ are used alone, while ‘self’ and ‘SRC’ can be used alongside one or more origins

The sample

If the camera and positioning API are disabled, the following HTTP headers defining feature policy can be passed in the response returned:

Feature-Policy: camera 'none'; geolocation 'none'
Copy the code

Reference: Feature – the Policy

Grammar changes

Original feature-policy example:

Feature-Policy: geolocation 'self' https://example.com; microphone 'none'
Copy the code

Permissions-Policy syntax changed to:

Permissions-Policy: geolocation=(self "https://example.com"), microphone=()
Copy the code

For example, the Header deployed by this site:

"Feature-Policy": "camera 'none'; microphone 'none'"
Copy the code

Also changed to:

"Permissions - Policy" : "camera = (), microphonee = ()"Copy the code

2. Configuration method

To add the following Header example:

x-frame-options: SAMEORIGIN
Copy the code

1. Application delivery controller

  • F5 BIG-IP (iRules)

    when HTTP_RESPONSE {
      HTTP::header insert X-Frame-Options "SAMEORIGIN"
    }
    Copy the code

    Remove and replace the original Header

    when HTTP_RESPONSE {
      HTTP::header replace Server "SYSIN.ORG/2.0"
      HTTP::header remove X-AspNet-Version
      HTTP::header remove X-Powered-By
    }
    Copy the code
  • Ctrix ADC (AppExpert)

    add rewrite action insert_x-frame-options_act insert_http_header X-Frame-Options "\"SAMEORIGIN\""
    Copy the code

    Remove and replace the original Header

    add rewrite action server-header-remove-act delete_http_header X-Powered-By
    add rewrite action server-header-remove-act delete_http_header X-AspNet-Version
    Copy the code

2. Web server

  • To configure Apache, send x-frame-options response headers on all pages. You need to configure the following in site:

    Header always set X-Frame-Options "SAMEORLGIN"
    Copy the code

    Remove and replace the original Header

    Header always unset "x-powered-by" Header unset "x-powered-by"Copy the code

    Grammar: Header [condition] add|append|echo|edit|edit*|merge|set|setifempty|unset|note header [[expr=]value [replacement] [early|env=[!]varname|expr=expression]]

    Replace the Server

    Apache mod_security module (For CentOS: yum install mod_security)

    ServerTokens Prod SecServerSignature "Your Server - Name"Copy the code
  • Configure Nginx to send x-frame-options headers on all pages. Add the following to the HTTP,server, or location configuration:

    add_header X-Frame-Options "SAMEORLGIN" always;
    Copy the code

    You can also use the module more_set_headers

    Clear Header: more_clear_headers

    more_clear_headers 'X-Hidden-*'; # support wildcard more_clear_headers' X-powered-by ';Copy the code

    Remove Server Header

    Install

    # Debian/Ubuntu the first
    ~/$> sudo apt-get install nginx-extras
    
    # RHEL and Amazon Linux
    ~/$> yum install nginx-plus-module-headers-more
    Copy the code

    Remove Server Header

    # /etc/nginx/nginx.conf
    
    http {
        # Basic Settings
        more_set_headers 'Server: ';
    Copy the code

    Override Server Header

    # /etc/nginx/nginx.conf
    
    http {
        # Basic Settings
        more_set_headers 'Server: None Of Your Business';
    Copy the code

    Remove Server Version from Header

    # /etc/nginx/nginx.conf
    
    http {
        # Basic Settings
        server_tokens off;
    Copy the code
  • Configure IIS by adding the following to the web. config file:

    <system.webServer>
      <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" value="SAMEORLGIN" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
    Copy the code

    Alternatively, choose Internet Information Services (IIS) Manager > HTTP Response Headers to add the HTTP Response Headers.

    Delete and modify the Server Header

    Download and install UrlScan and edit the configuration file urlScans.ini (located at %WINDIR%\System32\Inetsrv\ UrlScan)

    RemoveServerHeader=0 # Default, change the value to 1 and do not send ServerHeader AlternateServerName= the name to be replacedCopy the code

    Delete or modify x-powered-by

    Internet Information Services (IIS) Manager > HTTP Response Headers: Modify or delete the HTTP Response Headers.

    Remove X – AspNet – Version

    Add it under the <system.web> node in the web.config file of the site

    <httpRuntime enableVersionHeader="false" />
    Copy the code

3. Apps

Here are some examples:

  • JAVA

    Spring Security supports adding various Security headers to responses. The default response Security header is as follows:

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: 0
    X-Content-Type-Options: nosniff
    Strict-Transport-Security: max-age=31536000 ; includeSubDomains
    X-Frame-Options: DENY
    X-XSS-Protection: 1; mode=block
    Copy the code

    Example: Spring Security allows iframes to be in the same domain with “X-frame-options: SAMEORIGIN”.

    @EnableWebSecurity
    public class WebSecurityConfig extends
    WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
      // ....headers() .frameOptions() .sameOrigin(); }}public class WebSecurityConfig extends
    WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
      // ....headers() .frameOptions() .sameOrigin(); }}Copy the code

    See more: www.baeldung.com/spring-resp…

  • PHP

    
            
    header( 'x-frame-options: SAMEORIGIN');
    ? >
    Copy the code
    # In this example a HTTP header X-PHP-Version is added to the HTTP request. The value of this header is the version string of the PHP interpreter that is running the instance of HTTP_Request.
    
            
    require_once "HTTP/Request.php";
    
    $req= &new HTTP_Request("http://example.com/");
    $req->addHeader("X-PHP-Version", phpversion());
    
    $response = $req->sendRequest();
    
    if (PEAR::isError($response)) {
        echo $response->getMessage();
    } else {
        echo $req->getResponseBody();
    }
    ? >
    Copy the code
  • C#

    using System;
    using System.Text;
    using Microsoft.Web.Administration;
    
    internal static class Sample
    {
      private static void Main()
      {
          using (ServerManager serverManager = new ServerManager())
          {
            Configuration config = serverManager.GetWebConfiguration("Default Web Site");
            ConfigurationSection httpProtocolSection = config.GetSection("system.webServer/httpProtocol");
            ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");
    
            ConfigurationElement addElement = customHeadersCollection.CreateElement("add");
            addElement["name"] = @"x-frame-options";
            addElement["value"] = @"SAMEORIGIN"; customHeadersCollection.Add(addElement); serverManager.CommitChanges(); }}}Copy the code
  • VB.net

    Imports System
    Imports System.Text
    Imports Microsoft.Web.Administration
    
    Module Sample
    
      Sub Main()
          Dim serverManager As ServerManager = New ServerManager
          Dim config As Configuration = serverManager.GetWebConfiguration("Default Web Site")
          Dim httpProtocolSection As ConfigurationSection = config.GetSection("system.webServer/httpProtocol")
          Dim customHeadersCollection As ConfigurationElementCollection = httpProtocolSection.GetCollection("customHeaders")
    
          Dim addElement As ConfigurationElement = customHeadersCollection.CreateElement("add")
          addElement("name") = "x-frame-options"
          addElement("value") = "SAMEORIGIN"
          customHeadersCollection.Add(addElement)
    
          serverManager.CommitChanges()
      End Sub
    
    End Module
    Copy the code
  • JavaScript

    var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
    adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST/Default Web Site";
    var httpProtocolSection = adminManager.GetAdminSection("system.webServer/httpProtocol"."MACHINE/WEBROOT/APPHOST/Default Web Site");
    var customHeadersCollection = httpProtocolSection.ChildElements.Item("customHeaders").Collection;
    
    var addElement = customHeadersCollection.CreateNewElement("add");
    addElement.Properties.Item("name").Value = "x-frame-options";
    addElement.Properties.Item("value").Value = "SAMEORIGIN";
    customHeadersCollection.AddElement(addElement);
    
    adminManager.CommitChanges();
    Copy the code

Suggestions for setting security response headers

Check out some of the leading examples of web sites for configuration.

Usually, you need to modify, remove, and add the following headers:

1. Header that you want to modify

Server
Copy the code

2. The Header to be removed

X-Powered-By
X-AspNet-Version
Copy the code

3. You are advised to add headers

Strict-Transport-Security
X-Content-Type-Options
Content-Security-Policy
X-Xss-Protection
X-Frame-Options
Referrer-Policy
Feature-Policy
Copy the code

Example:

"Content-Security-Policy": "upgrade-insecure-requests",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains; preload",
"X-Xss-Protection": "1; mode=block",
"X-Frame-Options": "SAMEORIGIN",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Feature-Policy": "camera 'none'; microphone 'none'",
Copy the code

Through 4.Security HeadersSite inspection

Note the key points in the FAQ:

Frequently asked questions

How do I get an A+ grade?

To get an A+ grade your site needs to issue all of the HTTP response headers that we check for. This indicates a high level of commitment to improving security for your visitors.

What headers do you check for?

Over a HTTP connection we check for Content-Security-Policy, X-Content-Type-Options, X-Frame-Options and X-XSS-Protection. Over a HTTPS connection we check for 2 additional headers which are Strict-Transport-Security and Public-Key-Pins.

4. Resource websites

MDN HTTP Headers

Veracode Blog: Application Security Research, News, and Education

5. Testing tools

  • Check online: securityHeaders.com/ (recommended, with configuration suggestions)

  • Command line tools:

    Curl: curl -I https://sysin.org

    Hsecscan (Python)

  • The browser comes with developer tools or third-party Header extensions