简述下 TLS 握手过程
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 393
Author 回答者: shfshanyue
TLS 握手的详细过程可参考下图:
以上图片来自 high-performance-browser
从 wireshark
抓包,也可以看到握手的详细流程,建议抓包加强理解,以下是抓包 https://q.shanyue.tech
时的握手流程
通过 curl -vvv --head
来查看握手信息:
$ curl -vvv --head https://q.shanyue.tech
* Trying 111.6.180.235...
* TCP_NODELAY set
* Connected to q.shanyue.tech (111.6.180.235) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/cert.pem
CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: CN=q.shanyue.tech
* start date: Dec 2 00:00:00 2019 GMT
* expire date: Dec 1 12:00:00 2020 GMT
* subjectAltName: host "q.shanyue.tech" matched cert's "q.shanyue.tech"
* issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=Encryption Everywhere DV TLS CA - G1
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7f95ba80dc00)
握手过程
在 TLS 1.2 中,握手协议过程需要耗费两个 RTT,过程如下
- [OUT] Client Hello,客户端选出自身支持的 TLS 版本号、cipher suites、Client Random、SessionId 传送给服务器端 (有可能可复用 Session)
- [IN] Server Hello,服务器端选出双方都支持的 TLS 版本,cipher suite 、Server Random、SeesionId 给客户端
- [IN] Certificate,服务器端给客户端发送证书,用以身份验证及提供公钥
- [IN] Server Key Exchange,服务器端给客户端发送密钥交换算法的一些参数
- [IN] Server Finished
- [OUT] Client Key Exchange,客户端给服务器端发送密钥交换算法的一些参数,计算出预主密钥 (
pre master secret
),使用密钥交换算法(一般是 ECDHE)传递给服务器端。双方根据(Client Random、Server Random、Pre Master Secret)三个随机数生成对称加密中的密钥(master secret
)。(再根据master secret
生成Session Keys
,包括Client MAC Key
、Client Write Key
、Server MAC Key
、Server Write Key
。用以以后对的通信加密。) - [OUT] Change Cipher Spec,告知以后的消息开始对称加密通信
- [OUT] Finished,加密消息并完整性验证,标志着握手阶段成功并结束(对握手消息使用
Client Write Key
加解密,并使用Client MAC Key
进行完整性校验) - [IN] Change Cipher Spec,告知以后的消息开始对称加密通信。此时服务器端通过密钥交换算法拿到
pre master secret
,并根据三个随机数生成master secret
。 - [IN] Finished,加密消息并完整性验证,标志着握手阶段成功并结束
注,对于()内容在面试中可以忽略不答