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 访问。
预加载列表
- 提交:https://hstspreload.org/
- https://hg.mozilla.org/mozilla-central/raw-file/tip/security/manager/ssl/nsSTSPreloadList.inc
-
作用:强行指定相关域名采用 HTTPS 访问协议
- 谷歌维护,其他浏览器厂商也采纳了这个列表
- max-age 至少一年,且必须 includeSubDomains
- 如果监听了 80 端口,重定向到相同域名的 HTTPS 服务(443 端口)
要求原文:
- Serve a valid certificate.
- Redirect from HTTP to HTTPS on the same host, if you are listening on port 80.
- Serve all subdomains over HTTPS.
- In particular, you must support HTTPS for the www subdomain if a DNS record for that subdomain exists.
- Serve an HSTS header on the base domain for HTTPS requests:
- The max-age must be at least 31536000 seconds (1 year).
- The includeSubDomains directive must be specified.
- The preload directive must be specified.
- 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).
问题
- 第一次访问不受 HSTS 保护
- 如果网站想回退到 HTTP,可能会受阻
Nginx HSTS 配置
-
80 rewrite 到 https
server { listen 80; server_name example.com; # rewrite ^(.*)$ https://$host$1 permanent; return 301 https://$server_name$request_uri; }
-
HSTS 头
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
PKP:Public Key Pinning
和 HSTS 类似,服务器告诉浏览器网站的证书指纹,浏览器缓存起来。
后面的每次访问都会计算证书指纹,如果和之前缓存的哈希不匹配,则向用户发出警告,存在中间人攻击风险。
计算证书指纹的方法:
- SPKI
- 哈希,对整个证书计算哈希值,更加安全
和 HSTS 类似的是工作方式,目的(提升安全性),不同的是手段,HSTS 是为了确保采用安全的协议,PKP 是确保证书不被伪造。
参考资料与拓展阅读
- MDN, Strict-Transport-Security
- Wikipedia, HTTP Strict Transport Security