TOC

HSTS: HTTP Strict Transport Security

HSTS 全称 HTTP Strict Transport Security,中文就是 HTTP 严格传输安全

HSTS 的作用是通过特定的 HTTP 响应头告知浏览器,未来访问该网站时必须使用 HTTPS 连接,确保通信的安全性。这可以避免用户通过 HTTP 访问时的自动重定向,从而减少延迟。

对于同时支持 HTTP 和 HTTPS 的站点,HSTS 强制客户端始终使用 HTTPS,防止潜在的中间人攻击。主流浏览器都已全面支持 HSTS。

HSTS 于 2012 年成为互联网标准建议(RFC 6797),并逐渐被广泛采用。

背景

SSL 剥离攻击(SSLStrip),HTTP 降级攻击

受益于一整套相对可靠的公钥基础设施(PKI),直接的 HTTPS 通信是无法中间人攻击的。
中间人的伪造证书会被校验出来。

但是部分网站都是配置 HTTP 和 HTTPS 地址共存。

工作原理

通过 Strict-Transport-Security 响应头(下面称之为 HSTS 头),告诉客户端应该采用 HTTPS 连接。
客户端以后再访问这个网站就会自动重定向到 HTTPS(即使指定了 HTTP 协议)。

语法

Strict-Transport-Security: max-age=<expire-time>
Strict-Transport-Security: max-age=<expire-time>; includeSubDomains
Strict-Transport-Security: max-age=<expire-time>; includeSubDomains; preload
  • max-age 作用时长(秒),表示在这么长的时间之内都应该直接请求 HTTPS 协议。
  • includeSubDomains 对所有子域名生效
  • preload 添加到 HSTS 预加载列表需要的
    • 不是标准的一部分,但主流浏览器都支持

例如:

Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

表示两年之内,当前域名以及所有子域名,都通过 HTTPS 访问。

预加载列表

要求原文:

  1. Serve a valid certificate.
  2. Redirect from HTTP to HTTPS on the same host, if you are listening on port 80.
  3. Serve all subdomains over HTTPS.
    1. In particular, you must support HTTPS for the www subdomain if a DNS record for that subdomain exists.
  4. Serve an HSTS header on the base domain for HTTPS requests:
    1. The max-age must be at least 31536000 seconds (1 year).
    2. The includeSubDomains directive must be specified.
    3. The preload directive must be specified.
    4. If you are serving an additional redirect from your HTTPS site, that redirect must still have the HSTS header (rather than the page it redirects to).

问题

  1. 第一次访问不受 HSTS 保护
  2. 如果网站想回退到 HTTP,可能会受阻

Nginx HSTS 配置

  1. 80 rewrite 到 https

    server {
        listen 80;
        server_name example.com;
        # rewrite ^(.*)$ https://$host$1 permanent;
        return 301 https://$server_name$request_uri;
    }
    
  2. HSTS 头

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
    

PKP:Public Key Pinning

和 HSTS 类似,服务器告诉浏览器网站的证书指纹,浏览器缓存起来。
后面的每次访问都会计算证书指纹,如果和之前缓存的哈希不匹配,则向用户发出警告,存在中间人攻击风险。

计算证书指纹的方法:

  1. SPKI
  2. 哈希,对整个证书计算哈希值,更加安全

和 HSTS 类似的是工作方式,目的(提升安全性),不同的是手段,HSTS 是为了确保采用安全的协议,PKP 是确保证书不被伪造。

参考资料与拓展阅读

如果你有魔法,你可以看到一个评论框~