计算机网络 · 第 7 / 11 章 · 本章 3 小节
7HTTPS 与 TLS
7.1 握手做了什么
客户端 服务端 |--- ClientHello (支持的版本/套件, SNI=api.example.com) --->| |<-- ServerHello (选定套件) + 证书链 + 签名 -----------------| | ↑ 客户端在此校验:证书是否可信、是否过期、域名是否匹配 |--- Finished --------------------------------------------->| |<-- Finished ----------------------------------------------| ============ 之后所有数据用协商出的密钥加密 ============ TLS 1.3 只需 1 个 RTT(1.2 需要 2 个),还支持 0-RTT 会话恢复。
- SNI(Server Name Indication):客户端在握手时明文告知要访问的域名,服务器据此返回对应证书。 没有 SNI 就无法在同一 IP 上托管多个 HTTPS 站点。
- 证书链:服务器必须返回「站点证书 + 中间证书」。只发站点证书会导致部分客户端(尤其是 Android 旧版本、Java 客户端) 校验失败——浏览器往往有缓存,所以「浏览器能开、程序连不上」是证书链不全的典型症状。
- mTLS(双向认证):服务端也验证客户端证书,用于服务间零信任通信,Istio/Linkerd 默认开启。
7.2 证书检查与自动续期
# 看服务端返回的完整证书链与关键信息 $ openssl s_client -connect api.example.com:443 -servername api.example.com < /dev/null 2>/dev/null \ | openssl x509 -noout -subject -issuer -dates subject=CN = api.example.com issuer=C = US, O = Let's Encrypt, CN = R3 notBefore=May 1 00:00:00 2024 GMT notAfter=Jul 30 23:59:59 2024 GMT # ← 到期时间,必须监控 # 检查证书链是否完整(有无 "unable to get local issuer certificate") $ openssl s_client -connect api.example.com:443 -servername api.example.com < /dev/null 2>&1 | grep -i verify # 剩余天数(一行版,可放进巡检脚本) $ echo | openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null \ | openssl x509 -noout -enddate | cut -d= -f2
证书过期是最好预防、却最常发生的 P0 故障
它有三个特点:必然发生(时间在走)、可以提前 30 天知道、影响面是全站不可用。既然可预测,就必须监控。
最低要求:① 巡检脚本每天检查所有域名证书剩余天数,少于 30 天告警;② Let's Encrypt 用 certbot 自动续期并验证续期后 reload 生效; ③ 把证书到期时间做成 Grafana 面板上的一个红绿格子。
7.3 四个高频 TLS 错误
| 报错 | 原因 | 排查 |
|---|---|---|
certificate has expired | 证书过期 | openssl s_client 看 notAfter;确认续期任务是否在跑 |
unable to get local issuer certificate | 证书链不完整(缺中间证书) | 用 SSL Labs 或 openssl s_client -showcerts 看返回了几张证书 |
hostname mismatch | 证书域名与访问域名不一致 | 检查是否用 IP 访问、SNI 是否正确传递 |
certificate is not yet valid | 本机时间不对(时钟漂移) | timedatectl status,确认 NTP 同步正常 |
开发中的实际运用
接入第三方支付、短信、对象存储等外部 HTTPS 服务时,最常见的坑是对方轮换了证书而你这边信任库没更新, 或者你的 JDK/镜像里的 CA 根证书太旧。表现是「本地测试正常,线上容器里连不上」。
排查顺序:容器里执行 openssl s_client -connect host:443,对比本地结果。