github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/handshake_server_tls13.go (about) 1 // Copyright (c) 2022 zhaochun 2 // gmgo is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 /* 10 gmtls是基于`golang/go`的`tls`包实现的国密改造版本。 11 对应版权声明: thrid_licenses/github.com/golang/go/LICENSE 12 */ 13 14 package gmtls 15 16 import ( 17 "bytes" 18 "context" 19 "crypto" 20 "crypto/hmac" 21 "crypto/rsa" 22 "errors" 23 "hash" 24 "io" 25 "sync/atomic" 26 "time" 27 28 "gitee.com/zhaochuninhefei/zcgolog/zclog" 29 "github.com/hxx258456/ccgo/x509" 30 ) 31 32 // maxClientPSKIdentities is the number of client PSK identities the server will 33 // attempt to validate. It will ignore the rest not to let cheap ClientHello 34 // messages cause too much work in session ticket decryption attempts. 35 const maxClientPSKIdentities = 5 36 37 type serverHandshakeStateTLS13 struct { 38 c *Conn 39 ctx context.Context 40 clientHello *clientHelloMsg 41 hello *serverHelloMsg 42 sentDummyCCS bool 43 usingPSK bool 44 suite *cipherSuiteTLS13 45 cert *Certificate 46 sigAlg SignatureScheme 47 earlySecret []byte 48 sharedKey []byte 49 handshakeSecret []byte 50 masterSecret []byte 51 trafficSecret []byte // client_application_traffic_secret_0 52 transcript hash.Hash 53 clientFinished []byte 54 } 55 56 // tls1.3在接收到ClientHello之后的握手过程 57 func (hs *serverHandshakeStateTLS13) handshake() error { 58 c := hs.c 59 60 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. 61 62 // 处理ClientHello,协商密码套件,计算共享密钥 63 if err := hs.processClientHello(); err != nil { 64 return err 65 } 66 // 检查会话恢复 67 if err := hs.checkForResumption(); err != nil { 68 return err 69 } 70 // 选择服务端证书 71 if err := hs.pickCertificate(); err != nil { 72 return err 73 } 74 c.buffering = true 75 // 发送 ServerHello,DummyChangeCipherSpec,EncryptedExtensions 76 if err := hs.sendServerParameters(); err != nil { 77 return err 78 } 79 // 发送 certificateRequestMsgTLS13,certificateMsgTLS13,certificateVerifyMsg 80 if err := hs.sendServerCertificate(); err != nil { 81 return err 82 } 83 // 发送 ServerFinished 84 if err := hs.sendServerFinished(); err != nil { 85 return err 86 } 87 // Note that at this point we could start sending application data without 88 // waiting for the client's second flight, but the application might not 89 // expect the lack of replay protection of the ClientHello parameters. 90 if _, err := c.flush(); err != nil { 91 return err 92 } 93 // 读取客户端证书,验证后发送 sessionTicket 94 if err := hs.readClientCertificate(); err != nil { 95 return err 96 } 97 // 读取 ClientFinished 98 if err := hs.readClientFinished(); err != nil { 99 return err 100 } 101 102 atomic.StoreUint32(&c.handshakeStatus, 1) 103 104 return nil 105 } 106 107 // 对 ClientHello 进行处理, 协商密码套件并计算共享密钥 108 func (hs *serverHandshakeStateTLS13) processClientHello() error { 109 c := hs.c 110 111 hs.hello = new(serverHelloMsg) 112 // 兼容性对应 113 // TLS 1.3 froze the ServerHello.legacy_version field, and uses 114 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. 115 hs.hello.vers = VersionTLS12 116 // 扩展信息 supportedVersion 使用之前协商好的tls协议版本 117 hs.hello.supportedVersion = c.vers 118 119 if len(hs.clientHello.supportedVersions) == 0 { 120 _ = c.sendAlert(alertIllegalParameter) 121 return errors.New("gmtls: client used the legacy version field to negotiate TLS 1.3") 122 } 123 124 // Abort if the client is doing a fallback and landing lower than what we 125 // support. See RFC 7507, which however does not specify the interaction 126 // with supported_versions. The only difference is that with 127 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] 128 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, 129 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to 130 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before 131 // supported_versions was not better because there was just no way to do a 132 // TLS 1.4 handshake without risking the server selecting TLS 1.3. 133 for _, id := range hs.clientHello.cipherSuites { 134 if id == TLS_FALLBACK_SCSV { 135 // Use c.vers instead of max(supported_versions) because an attacker 136 // could defeat this by adding an arbitrary high version otherwise. 137 if c.vers < c.config.maxSupportedVersion() { 138 _ = c.sendAlert(alertInappropriateFallback) 139 return errors.New("gmtls: client using inappropriate protocol fallback") 140 } 141 break 142 } 143 } 144 145 if len(hs.clientHello.compressionMethods) != 1 || 146 hs.clientHello.compressionMethods[0] != compressionNone { 147 _ = c.sendAlert(alertIllegalParameter) 148 return errors.New("gmtls: TLS 1.3 client supports illegal compression methods") 149 } 150 151 hs.hello.random = make([]byte, 32) 152 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { 153 _ = c.sendAlert(alertInternalError) 154 return err 155 } 156 157 if len(hs.clientHello.secureRenegotiation) != 0 { 158 _ = c.sendAlert(alertHandshakeFailure) 159 return errors.New("gmtls: initial handshake had non-empty renegotiation extension") 160 } 161 162 if hs.clientHello.earlyData { 163 // See RFC 8446, Section 4.2.10 for the complicated behavior required 164 // here. The scenario is that a different server at our address offered 165 // to accept early data in the past, which we can't handle. For now, all 166 // 0-RTT enabled session tickets need to expire before a Go server can 167 // replace a server or join a pool. That's the same requirement that 168 // applies to mixing or replacing with any TLS 1.2 server. 169 _ = c.sendAlert(alertUnsupportedExtension) 170 return errors.New("gmtls: client sent unexpected early data") 171 } 172 173 hs.hello.sessionId = hs.clientHello.sessionId 174 hs.hello.compressionMethod = compressionNone 175 // 协商密码套件 176 preferenceList := defaultCipherSuitesTLS13 177 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 178 preferenceList = defaultCipherSuitesTLS13NoAES 179 } 180 for _, suiteID := range preferenceList { 181 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) 182 if hs.suite != nil { 183 break 184 } 185 } 186 if hs.suite == nil { 187 _ = c.sendAlert(alertHandshakeFailure) 188 return errors.New("gmtls: no cipher suite supported by both client and server") 189 } 190 c.cipherSuite = hs.suite.id 191 hs.hello.cipherSuite = hs.suite.id 192 zclog.Debugf("===== 服务端协商密码套件: %s", CipherSuiteName(hs.suite.id)) 193 // 使用密码套件的散列函数作为握手数据摘要函数 194 hs.transcript = hs.suite.hash.New() 195 196 // Pick the ECDHE group in server preference order, but give priority to 197 // groups with a key share, to avoid a HelloRetryRequest round-trip. 198 var selectedGroup CurveID 199 var clientKeyShare *keyShare 200 GroupSelection: 201 for _, preferredGroup := range c.config.curvePreferences() { 202 for _, ks := range hs.clientHello.keyShares { 203 if ks.group == preferredGroup { 204 selectedGroup = ks.group 205 clientKeyShare = &ks 206 break GroupSelection 207 } 208 } 209 if selectedGroup != 0 { 210 continue 211 } 212 for _, group := range hs.clientHello.supportedCurves { 213 if group == preferredGroup { 214 selectedGroup = group 215 break 216 } 217 } 218 } 219 if selectedGroup == 0 { 220 _ = c.sendAlert(alertHandshakeFailure) 221 return errors.New("gmtls: no ECDHE curve supported by both client and server") 222 } 223 // 未能获取客户端共享密钥 224 if clientKeyShare == nil { 225 // 请求客户端重新发送ClientHello以获取共享密钥 226 if err := hs.doHelloRetryRequest(selectedGroup); err != nil { 227 return err 228 } 229 clientKeyShare = &hs.clientHello.keyShares[0] 230 } 231 // var curve elliptic.Curve 232 var curveOk bool 233 var curveName string 234 if curveName, curveOk = CheckCurveNameById(selectedGroup); !curveOk { 235 _ = c.sendAlert(alertInternalError) 236 return errors.New("gmtls: CurvePreferences includes unsupported curve") 237 } 238 // 生成服务端的密钥交换算法参数,即对应曲线的公私钥 239 params, err := generateECDHEParameters(c.config.rand(), selectedGroup) 240 if err != nil { 241 _ = c.sendAlert(alertInternalError) 242 return err 243 } 244 zclog.Debugf("===== 服务端使用曲线 %s 生成密钥交换算法参数", curveName) 245 // 设置服务端密钥交换算法参数(曲线ID + 服务端公钥) 246 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()} 247 // 根据客户端公钥与服务端公钥计算预主密钥 248 zclog.Debugf("===== 服务端使用曲线 %s 与客户端公钥计算预主密钥", curveName) 249 hs.sharedKey = params.SharedKey(clientKeyShare.data) 250 if hs.sharedKey == nil { 251 _ = c.sendAlert(alertIllegalParameter) 252 return errors.New("gmtls: invalid client key share") 253 } 254 255 c.serverName = hs.clientHello.serverName 256 return nil 257 } 258 259 // 检查会话恢复 260 func (hs *serverHandshakeStateTLS13) checkForResumption() error { 261 c := hs.c 262 263 if c.config.SessionTicketsDisabled { 264 return nil 265 } 266 267 modeOK := false 268 for _, mode := range hs.clientHello.pskModes { 269 if mode == pskModeDHE { 270 modeOK = true 271 break 272 } 273 } 274 if !modeOK { 275 return nil 276 } 277 278 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { 279 _ = c.sendAlert(alertIllegalParameter) 280 return errors.New("gmtls: invalid or missing PSK binders") 281 } 282 if len(hs.clientHello.pskIdentities) == 0 { 283 return nil 284 } 285 // 尝试从 ClientHello的pskid集合中选取一个作为本次会话的公钥密钥。 286 // 如果客户端就是本代码实现的客户端,那么pskIdentities中最多只会有一个 pskIdentitie 287 for i, identity := range hs.clientHello.pskIdentities { 288 if i >= maxClientPSKIdentities { 289 break 290 } 291 // 对pskIdentitie的label解密得到sessionStateTLS13的序列化明文 292 plaintext, _ := c.decryptTicket(identity.label) 293 if plaintext == nil { 294 continue 295 } 296 // 反序列化为sessionStateTLS13 297 sessionState := new(sessionStateTLS13) 298 if ok := sessionState.unmarshal(plaintext); !ok { 299 continue 300 } 301 // 检查sessionTicket最大存活时间 302 createdAt := time.Unix(int64(sessionState.createdAt), 0) 303 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 304 continue 305 } 306 307 // We don't check the obfuscated ticket age because it's affected by 308 // clock skew and it's only a freshness signal useful for shrinking the 309 // window for replay attacks, which don't affect us as we don't do 0-RTT. 310 311 // 选取该会话的密码套件 312 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) 313 if pskSuite == nil || pskSuite.hash != hs.suite.hash { 314 continue 315 } 316 317 // PSK connections don't re-establish client certificates, but carry 318 // them over in the session ticket. Ensure the presence of client certs 319 // in the ticket is consistent with the configured requirements. 320 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 321 needClientCerts := requiresClientCert(c.config.ClientAuth) 322 if needClientCerts && !sessionHasClientCerts { 323 continue 324 } 325 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 326 continue 327 } 328 // 使用会话状态中保存的恢复用机密扩展为psk 329 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", 330 nil, hs.suite.hash.Size()) 331 // 再基于psk派生早期机密 332 hs.earlySecret = hs.suite.extract(psk, nil) 333 // 再基于早期机密派生绑定者密钥 334 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) 335 // 复制一个转录散列函数 336 // Clone the transcript in case a HelloRetryRequest was recorded. 337 transcript := cloneHash(hs.transcript, hs.suite.hash) 338 if transcript == nil { 339 _ = c.sendAlert(alertInternalError) 340 return errors.New("gmtls: internal error: failed to clone hash") 341 } 342 // 向转录散列写入不带pskBinders的ClientHello 343 transcript.Write(hs.clientHello.marshalWithoutBinders()) 344 // 生成pskBinders: 使用绑定者密钥和转录散列生成的Finished消息散列 345 pskBinder := hs.suite.finishedHash(binderKey, transcript) 346 // 检查clientHello与服务端计算出的pskBinder的认证码是否一致 347 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 348 _ = c.sendAlert(alertDecryptError) 349 return errors.New("gmtls: invalid PSK binder") 350 } 351 // 向连接写入会话恢复标识 352 c.didResume = true 353 // 检查客户端短证书 354 if err := c.processCertsFromClient(sessionState.certificate); err != nil { 355 return err 356 } 357 // 在ServerHello中填写会话恢复相关字段 358 hs.hello.selectedIdentityPresent = true 359 hs.hello.selectedIdentity = uint16(i) 360 hs.usingPSK = true 361 return nil 362 } 363 364 return nil 365 } 366 367 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 368 // interfaces implemented by standard library hashes to clone the state of in 369 // to a new instance of h. It returns nil if the operation fails. 370 func cloneHash(in hash.Hash, h x509.Hash) hash.Hash { 371 // Recreate the interface to avoid importing encoding. 372 type binaryMarshaler interface { 373 MarshalBinary() (data []byte, err error) 374 UnmarshalBinary(data []byte) error 375 } 376 marshaler, ok := in.(binaryMarshaler) 377 if !ok { 378 return nil 379 } 380 state, err := marshaler.MarshalBinary() 381 if err != nil { 382 return nil 383 } 384 out := h.New() 385 unmarshaler, ok := out.(binaryMarshaler) 386 if !ok { 387 return nil 388 } 389 if err := unmarshaler.UnmarshalBinary(state); err != nil { 390 return nil 391 } 392 return out 393 } 394 395 // 选择服务端证书 396 func (hs *serverHandshakeStateTLS13) pickCertificate() error { 397 c := hs.c 398 399 // Only one of PSK and certificates are used at a time. 400 if hs.usingPSK { 401 return nil 402 } 403 404 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 405 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 406 return c.sendAlert(alertMissingExtension) 407 } 408 409 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 410 if err != nil { 411 if err == errNoCertificates { 412 _ = c.sendAlert(alertUnrecognizedName) 413 } else { 414 _ = c.sendAlert(alertInternalError) 415 } 416 return err 417 } 418 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 419 if err != nil { 420 // getCertificate returned a certificate that is unsupported or 421 // incompatible with the client's signature algorithms. 422 _ = c.sendAlert(alertHandshakeFailure) 423 return err 424 } 425 hs.cert = certificate 426 427 return nil 428 } 429 430 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 431 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 432 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 433 if hs.sentDummyCCS { 434 return nil 435 } 436 hs.sentDummyCCS = true 437 438 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 439 return err 440 } 441 442 // 向客户端发送 HelloRetryRequest , 请求重新发送 ClientHello 443 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 444 c := hs.c 445 // 将ClientHello散列后重新写入握手数据摘要 446 // The first ClientHello gets double-hashed into the transcript upon a 447 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 448 hs.transcript.Write(hs.clientHello.marshal()) 449 chHash := hs.transcript.Sum(nil) 450 hs.transcript.Reset() 451 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 452 hs.transcript.Write(chHash) 453 // 创建 HelloRetryRequest 454 helloRetryRequest := &serverHelloMsg{ 455 vers: hs.hello.vers, 456 random: helloRetryRequestRandom, // 客户端通过该random值判断是否HelloRetryRequest 457 sessionId: hs.hello.sessionId, 458 cipherSuite: hs.hello.cipherSuite, 459 compressionMethod: hs.hello.compressionMethod, 460 supportedVersion: hs.hello.supportedVersion, 461 selectedGroup: selectedGroup, 462 } 463 // 将HelloRetryRequest写入握手数据摘要 464 hs.transcript.Write(helloRetryRequest.marshal()) 465 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil { 466 return err 467 } 468 zclog.Debug("===== 服务端发送 HelloRetryRequest") 469 if err := hs.sendDummyChangeCipherSpec(); err != nil { 470 return err 471 } 472 // 读取下一条消息, 客户端重新发送的 ClientHello 473 msg, err := c.readHandshake() 474 if err != nil { 475 return err 476 } 477 clientHello, ok := msg.(*clientHelloMsg) 478 if !ok { 479 _ = c.sendAlert(alertUnexpectedMessage) 480 return unexpectedMessageError(clientHello, msg) 481 } 482 zclog.Debug("===== 服务端读取到客户端重新发送的 ClientHello") 483 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 484 _ = c.sendAlert(alertIllegalParameter) 485 return errors.New("gmtls: client sent invalid key share in second ClientHello") 486 } 487 488 if clientHello.earlyData { 489 _ = c.sendAlert(alertIllegalParameter) 490 return errors.New("gmtls: client indicated early data in second ClientHello") 491 } 492 493 if illegalClientHelloChange(clientHello, hs.clientHello) { 494 _ = c.sendAlert(alertIllegalParameter) 495 return errors.New("gmtls: client illegally modified second ClientHello") 496 } 497 498 hs.clientHello = clientHello 499 return nil 500 } 501 502 // illegalClientHelloChange reports whether the two ClientHello messages are 503 // different, with the exception of the changes allowed before and after a 504 // HelloRetryRequest. See RFC 8446, Section 4.1.2. 505 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 506 if len(ch.supportedVersions) != len(ch1.supportedVersions) || 507 len(ch.cipherSuites) != len(ch1.cipherSuites) || 508 len(ch.supportedCurves) != len(ch1.supportedCurves) || 509 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 510 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 511 len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 512 return true 513 } 514 for i := range ch.supportedVersions { 515 if ch.supportedVersions[i] != ch1.supportedVersions[i] { 516 return true 517 } 518 } 519 for i := range ch.cipherSuites { 520 if ch.cipherSuites[i] != ch1.cipherSuites[i] { 521 return true 522 } 523 } 524 for i := range ch.supportedCurves { 525 if ch.supportedCurves[i] != ch1.supportedCurves[i] { 526 return true 527 } 528 } 529 for i := range ch.supportedSignatureAlgorithms { 530 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 531 return true 532 } 533 } 534 for i := range ch.supportedSignatureAlgorithmsCert { 535 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 536 return true 537 } 538 } 539 for i := range ch.alpnProtocols { 540 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 541 return true 542 } 543 } 544 return ch.vers != ch1.vers || 545 !bytes.Equal(ch.random, ch1.random) || 546 !bytes.Equal(ch.sessionId, ch1.sessionId) || 547 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 548 ch.serverName != ch1.serverName || 549 ch.ocspStapling != ch1.ocspStapling || 550 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 551 ch.ticketSupported != ch1.ticketSupported || 552 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 553 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 554 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 555 ch.scts != ch1.scts || 556 !bytes.Equal(ch.cookie, ch1.cookie) || 557 !bytes.Equal(ch.pskModes, ch1.pskModes) 558 } 559 560 // 发送 ServerHello,DummyChangeCipherSpec,EncryptedExtensions 561 func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 562 c := hs.c 563 // 向握手数据摘要写入ClientHello与ServerHello 564 hs.transcript.Write(hs.clientHello.marshal()) 565 hs.transcript.Write(hs.hello.marshal()) 566 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 567 return err 568 } 569 zclog.Debug("===== 服务端发送 ServerHello") 570 if err := hs.sendDummyChangeCipherSpec(); err != nil { 571 return err 572 } 573 zclog.Debug("===== 服务端发送 DummyChangeCipherSpec") 574 // 如果是会话恢复,这里已经存在早期密钥,如果不存在,则初始化早期密钥 575 earlySecret := hs.earlySecret 576 if earlySecret == nil { 577 earlySecret = hs.suite.extract(nil, nil) 578 } 579 // 使用 HKDF-Extract, 根据之前计算出的预主密钥与早期密钥计算出握手阶段密钥。 580 // hs.sharedKey 是预主密钥; 581 // 用deriveSecret函数从earlySecret、"derived"派生出盐值。 582 hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 583 hs.suite.deriveSecret(earlySecret, "derived", nil)) 584 // 使用 HKDF-Expand, 根据握手阶段密钥与目前的握手数据摘要计算出客户端会话密钥,并设置到连接通道 585 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, 586 clientHandshakeTrafficLabel, hs.transcript) 587 c.in.setTrafficSecret(hs.suite, clientSecret) 588 // 使用 HKDF-Expand, 根据握手阶段密钥与目前的握手数据摘要计算出服务端会话密钥,并设置到连接通道 589 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 590 serverHandshakeTrafficLabel, hs.transcript) 591 c.out.setTrafficSecret(hs.suite, serverSecret) 592 593 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) 594 if err != nil { 595 _ = c.sendAlert(alertInternalError) 596 return err 597 } 598 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 599 if err != nil { 600 _ = c.sendAlert(alertInternalError) 601 return err 602 } 603 // 生成加密扩展信息 604 encryptedExtensions := new(encryptedExtensionsMsg) 605 // 协商ALPN协议 606 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 607 if err != nil { 608 _ = c.sendAlert(alertNoApplicationProtocol) 609 return err 610 } 611 encryptedExtensions.alpnProtocol = selectedProto 612 c.clientProtocol = selectedProto 613 // 向握手数据摘要写入加密扩展信息 614 hs.transcript.Write(encryptedExtensions.marshal()) 615 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil { 616 return err 617 } 618 zclog.Debug("===== 服务端发送 EncryptedExtensions") 619 620 return nil 621 } 622 623 func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 624 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 625 } 626 627 // 发送 certificateRequestMsgTLS13,certificateMsgTLS13,certificateVerifyMsg 628 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 629 c := hs.c 630 631 // Only one of PSK and certificates are used at a time. 632 if hs.usingPSK { 633 return nil 634 } 635 636 if hs.requestClientCert() { 637 // Request a client certificate 638 certReq := new(certificateRequestMsgTLS13) 639 certReq.ocspStapling = true 640 certReq.scts = true 641 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms 642 if c.config.ClientCAs != nil { 643 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 644 } 645 // 向握手数据摘要写入 certificateRequestMsgTLS13 646 hs.transcript.Write(certReq.marshal()) 647 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 648 return err 649 } 650 zclog.Debug("===== 服务端发送 certificateRequestMsgTLS13") 651 } 652 653 certMsg := new(certificateMsgTLS13) 654 655 certMsg.certificate = *hs.cert 656 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 657 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 658 // 向握手数据摘要写入 certificateMsgTLS13 659 hs.transcript.Write(certMsg.marshal()) 660 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 661 return err 662 } 663 zclog.Debug("===== 服务端发送 certificateMsgTLS13") 664 certVerifyMsg := new(certificateVerifyMsg) 665 certVerifyMsg.hasSignatureAlgorithm = true 666 certVerifyMsg.signatureAlgorithm = hs.sigAlg 667 668 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 669 if err != nil { 670 return c.sendAlert(alertInternalError) 671 } 672 673 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 674 signOpts := crypto.SignerOpts(sigHash) 675 if sigType == signatureRSAPSS { 676 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash.HashFunc()} 677 } 678 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 679 if err != nil { 680 public := hs.cert.PrivateKey.(crypto.Signer).Public() 681 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 682 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 683 _ = c.sendAlert(alertHandshakeFailure) 684 } else { 685 _ = c.sendAlert(alertInternalError) 686 } 687 return errors.New("gmtls: failed to sign handshake: " + err.Error()) 688 } 689 certVerifyMsg.signature = sig 690 // 向握手数据摘要写入 certificateVerifyMsg 691 hs.transcript.Write(certVerifyMsg.marshal()) 692 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 693 return err 694 } 695 zclog.Debug("===== 服务端发送 certificateVerifyMsg") 696 return nil 697 } 698 699 // 发送 ServerFinished 700 func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 701 c := hs.c 702 703 finished := &finishedMsg{ 704 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 705 } 706 // 向握手数据摘要写入 ServerFinished 707 hs.transcript.Write(finished.marshal()) 708 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 709 return err 710 } 711 zclog.Debug("===== 服务端发送 ServerFinished") 712 // Derive secrets that take context through the server Finished. 713 // 从握手阶段密钥派生新的预主密钥并提取出主密钥 714 hs.masterSecret = hs.suite.extract(nil, 715 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 716 // 重新派生客户端通信密钥,但暂时不设置到连接通道 717 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 718 clientApplicationTrafficLabel, hs.transcript) 719 // 重新派生服务端通信密钥,并设置到连接通道 720 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 721 serverApplicationTrafficLabel, hs.transcript) 722 c.out.setTrafficSecret(hs.suite, serverSecret) 723 724 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 725 if err != nil { 726 _ = c.sendAlert(alertInternalError) 727 return err 728 } 729 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 730 if err != nil { 731 _ = c.sendAlert(alertInternalError) 732 return err 733 } 734 735 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 736 737 // If we did not request client certificates, at this point we can 738 // precompute the client finished and roll the transcript forward to send 739 // session tickets in our first flight. 740 if !hs.requestClientCert() { 741 if err := hs.sendSessionTickets(); err != nil { 742 return err 743 } 744 } 745 746 return nil 747 } 748 749 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 750 if hs.c.config.SessionTicketsDisabled { 751 zclog.Debug("===== config.SessionTicketsDisabled is true") 752 return false 753 } 754 755 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 756 for _, pskMode := range hs.clientHello.pskModes { 757 if pskMode == pskModeDHE { 758 return true 759 } 760 } 761 return false 762 } 763 764 // 发送 newSessionTicketMsgTLS13 765 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 766 c := hs.c 767 768 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 769 finishedMsg := &finishedMsg{ 770 verifyData: hs.clientFinished, 771 } 772 hs.transcript.Write(finishedMsg.marshal()) 773 774 if !hs.shouldSendSessionTickets() { 775 zclog.Debug("===== shouldSendSessionTickets is false") 776 return nil 777 } 778 // 派生会话恢复用密钥 779 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, 780 resumptionLabel, hs.transcript) 781 // 创建 newSessionTicketMsgTLS13 782 m := new(newSessionTicketMsgTLS13) 783 var certsFromClient [][]byte 784 for _, cert := range c.peerCertificates { 785 certsFromClient = append(certsFromClient, cert.Raw) 786 } 787 state := sessionStateTLS13{ 788 cipherSuite: hs.suite.id, 789 createdAt: uint64(c.config.time().Unix()), 790 resumptionSecret: resumptionSecret, 791 certificate: Certificate{ 792 Certificate: certsFromClient, 793 OCSPStaple: c.ocspResponse, 794 SignedCertificateTimestamps: c.scts, 795 }, 796 } 797 var err error 798 // 序列化 newSessionTicketMsgTLS13 并加密 799 m.label, err = c.encryptTicket(state.marshal()) 800 if err != nil { 801 return err 802 } 803 m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 804 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 805 return err 806 } 807 zclog.Debug("===== 服务端发出 newSessionTicketMsgTLS13") 808 return nil 809 } 810 811 // 读取并验证客户端证书,并发送本次会话票据信息给客户端。 812 func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 813 c := hs.c 814 815 if !hs.requestClientCert() { 816 // Make sure the connection is still being verified whether or not 817 // the server requested a client certificate. 818 if c.config.VerifyConnection != nil { 819 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 820 _ = c.sendAlert(alertBadCertificate) 821 return err 822 } 823 } 824 return nil 825 } 826 827 // If we requested a client certificate, then the client must send a 828 // certificate message. If it's empty, no CertificateVerify is sent. 829 // 读取 ClientCertificate 830 msg, err := c.readHandshake() 831 if err != nil { 832 return err 833 } 834 certMsg, ok := msg.(*certificateMsgTLS13) 835 if !ok { 836 _ = c.sendAlert(alertUnexpectedMessage) 837 return unexpectedMessageError(certMsg, msg) 838 } 839 zclog.Debug("===== 服务端读取到 ClientCertificate") 840 hs.transcript.Write(certMsg.marshal()) 841 // 检查客户端证书 842 if err := c.processCertsFromClient(certMsg.certificate); err != nil { 843 return err 844 } 845 846 if c.config.VerifyConnection != nil { 847 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 848 _ = c.sendAlert(alertBadCertificate) 849 return err 850 } 851 } 852 853 if len(certMsg.certificate.Certificate) != 0 { 854 // 读取 ClientCertVerify 855 msg, err = c.readHandshake() 856 if err != nil { 857 return err 858 } 859 certVerify, ok := msg.(*certificateVerifyMsg) 860 if !ok { 861 _ = c.sendAlert(alertUnexpectedMessage) 862 return unexpectedMessageError(certVerify, msg) 863 } 864 zclog.Debug("===== 服务端读取到 ClientCertVerify") 865 // See RFC 8446, Section 4.4.3. 866 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) { 867 _ = c.sendAlert(alertIllegalParameter) 868 return errors.New("gmtls: client certificate used with invalid signature algorithm") 869 } 870 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 871 if err != nil { 872 return c.sendAlert(alertInternalError) 873 } 874 if sigType == signaturePKCS1v15 || sigHash == x509.SHA1 { 875 _ = c.sendAlert(alertIllegalParameter) 876 return errors.New("gmtls: client certificate used with invalid signature algorithm") 877 } 878 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 879 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 880 sigHash, signed, certVerify.signature); err != nil { 881 _ = c.sendAlert(alertDecryptError) 882 return errors.New("gmtls: invalid signature by the client certificate: " + err.Error()) 883 } 884 885 hs.transcript.Write(certVerify.marshal()) 886 } 887 // 在需求验证客户端证书且验证Ok之后,向客户端发送本次会话新创建的票据信息。 888 // 该消息属于握手消息,但是在客户端完成握手之后才会接收。 889 // PS : 如果要使用会话恢复功能,服务端就必须验证客户端身份。 890 // If we waited until the client certificates to send session tickets, we 891 // are ready to do it now. 892 if err := hs.sendSessionTickets(); err != nil { 893 return err 894 } 895 896 return nil 897 } 898 899 // 读取 ClientFinished 900 func (hs *serverHandshakeStateTLS13) readClientFinished() error { 901 c := hs.c 902 // 读取 ClientFinished 903 msg, err := c.readHandshake() 904 if err != nil { 905 return err 906 } 907 finished, ok := msg.(*finishedMsg) 908 if !ok { 909 _ = c.sendAlert(alertUnexpectedMessage) 910 return unexpectedMessageError(finished, msg) 911 } 912 zclog.Debug("===== 服务端读取到 ClientFinished") 913 if !hmac.Equal(hs.clientFinished, finished.verifyData) { 914 _ = c.sendAlert(alertDecryptError) 915 return errors.New("gmtls: invalid client finished hash") 916 } 917 // 将之前重新生成的客户端通信密钥设置到连接in通道 918 c.in.setTrafficSecret(hs.suite, hs.trafficSecret) 919 920 return nil 921 }