gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/handshake_server.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm 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 "context" 18 "crypto" 19 "crypto/ecdsa" 20 "crypto/ed25519" 21 "crypto/rsa" 22 "crypto/subtle" 23 "errors" 24 "fmt" 25 "gitee.com/ks-custle/core-gm/ecdsa_ext" 26 "hash" 27 "io" 28 "sync/atomic" 29 "time" 30 31 "gitee.com/ks-custle/core-gm/sm2" 32 "gitee.com/ks-custle/core-gm/x509" 33 ) 34 35 // serverHandshakeState contains details of a server handshake in progress. 36 // It's discarded once the handshake has completed. 37 type serverHandshakeState struct { 38 c *Conn 39 ctx context.Context 40 clientHello *clientHelloMsg 41 hello *serverHelloMsg 42 suite *cipherSuite 43 ecdheOk bool 44 ecSignOk bool 45 rsaDecryptOk bool 46 rsaSignOk bool 47 sessionState *sessionState 48 finishedHash finishedHash 49 masterSecret []byte 50 cert *Certificate 51 } 52 53 // 服务端握手 54 // serverHandshake performs a TLS handshake as a server. 55 func (c *Conn) serverHandshake(ctx context.Context) error { 56 fmt.Println("===== 开始服务端握手过程") 57 // 读取 ClientHello 58 clientHello, err := c.readClientHello(ctx) 59 if err != nil { 60 return err 61 } 62 // GMSSL目前采用tls1.3的处理 63 if c.vers == VersionTLS13 || c.vers == VersionGMSSL { 64 fmt.Println("===== 服务端执行tls1.3或gmssl的握手过程") 65 hs := serverHandshakeStateTLS13{ 66 c: c, 67 ctx: ctx, 68 clientHello: clientHello, 69 } 70 return hs.handshake() 71 } 72 fmt.Println("===== 服务端执行tls1.2或更老版本的握手过程") 73 hs := serverHandshakeState{ 74 c: c, 75 ctx: ctx, 76 clientHello: clientHello, 77 } 78 return hs.handshake() 79 } 80 81 // tls1.2及更老版本在读取ClientHello之后的握手过程 82 func (hs *serverHandshakeState) handshake() error { 83 c := hs.c 84 85 if err := hs.processClientHello(); err != nil { 86 return err 87 } 88 89 // For an overview of TLS handshaking, see RFC 5246, Section 7.3. 90 c.buffering = true 91 if hs.checkForResumption() { 92 // The client has included a session ticket and so we do an abbreviated handshake. 93 c.didResume = true 94 if err := hs.doResumeHandshake(); err != nil { 95 return err 96 } 97 if err := hs.establishKeys(); err != nil { 98 return err 99 } 100 if err := hs.sendSessionTicket(); err != nil { 101 return err 102 } 103 if err := hs.sendFinished(c.serverFinished[:]); err != nil { 104 return err 105 } 106 if _, err := c.flush(); err != nil { 107 return err 108 } 109 c.clientFinishedIsFirst = false 110 if err := hs.readFinished(nil); err != nil { 111 return err 112 } 113 } else { 114 // The client didn't include a session ticket, or it wasn't 115 // valid so we do a full handshake. 116 if err := hs.pickCipherSuite(); err != nil { 117 return err 118 } 119 if err := hs.doFullHandshake(); err != nil { 120 return err 121 } 122 if err := hs.establishKeys(); err != nil { 123 return err 124 } 125 if err := hs.readFinished(c.clientFinished[:]); err != nil { 126 return err 127 } 128 c.clientFinishedIsFirst = true 129 c.buffering = true 130 if err := hs.sendSessionTicket(); err != nil { 131 return err 132 } 133 if err := hs.sendFinished(nil); err != nil { 134 return err 135 } 136 if _, err := c.flush(); err != nil { 137 return err 138 } 139 } 140 141 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) 142 atomic.StoreUint32(&c.handshakeStatus, 1) 143 144 return nil 145 } 146 147 // 读取ClientHello并选择协议版本。 148 // readClientHello reads a ClientHello message and selects the protocol version. 149 func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) { 150 // 读取ClientHello 151 msg, err := c.readHandshake() 152 if err != nil { 153 return nil, err 154 } 155 clientHello, ok := msg.(*clientHelloMsg) 156 if !ok { 157 _ = c.sendAlert(alertUnexpectedMessage) 158 return nil, unexpectedMessageError(clientHello, msg) 159 } 160 fmt.Println("===== 服务端读取到 ClientHello") 161 162 var configForClient *Config 163 originalConfig := c.config 164 if c.config.GetConfigForClient != nil { 165 chi := clientHelloInfo(ctx, c, clientHello) 166 if configForClient, err = c.config.GetConfigForClient(chi); err != nil { 167 _ = c.sendAlert(alertInternalError) 168 return nil, fmt.Errorf("gmtls: GetConfigForClient时发生错误: %s", err) 169 } else if configForClient != nil { 170 c.config = configForClient 171 } 172 } 173 // 为当前连接设置ticketKeys 174 c.ticketKeys = originalConfig.ticketKeys(configForClient) 175 // 获取ClientHello的协议版本信息,默认使用supportedVersions,没有设置supportedVersions的情况下使用vers 176 clientVersions := clientHello.supportedVersions 177 if len(clientHello.supportedVersions) == 0 { 178 clientVersions = supportedVersionsFromMax(clientHello.vers) 179 } 180 // 协商tls协议版本 181 c.vers, ok = c.config.mutualVersion(clientVersions) 182 if !ok { 183 _ = c.sendAlert(alertProtocolVersion) 184 return nil, fmt.Errorf("gmtls: client offered only unsupported versions: %x", clientVersions) 185 } 186 fmt.Println("===== 服务端选择本次tls连接使用的版本是:", ShowTLSVersion(int(c.vers))) 187 c.haveVers = true 188 c.in.version = c.vers 189 c.out.version = c.vers 190 191 return clientHello, nil 192 } 193 194 func (hs *serverHandshakeState) processClientHello() error { 195 c := hs.c 196 197 hs.hello = new(serverHelloMsg) 198 hs.hello.vers = c.vers 199 200 foundCompression := false 201 // We only support null compression, so check that the client offered it. 202 for _, compression := range hs.clientHello.compressionMethods { 203 if compression == compressionNone { 204 foundCompression = true 205 break 206 } 207 } 208 209 if !foundCompression { 210 _ = c.sendAlert(alertHandshakeFailure) 211 return errors.New("gmtls: client does not support uncompressed connections") 212 } 213 214 hs.hello.random = make([]byte, 32) 215 serverRandom := hs.hello.random 216 // Downgrade protection canaries. See RFC 8446, Section 4.1.3. 217 maxVers := c.config.maxSupportedVersion() 218 if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary { 219 if c.vers == VersionTLS12 { 220 copy(serverRandom[24:], downgradeCanaryTLS12) 221 } else { 222 copy(serverRandom[24:], downgradeCanaryTLS11) 223 } 224 serverRandom = serverRandom[:24] 225 } 226 _, err := io.ReadFull(c.config.rand(), serverRandom) 227 if err != nil { 228 _ = c.sendAlert(alertInternalError) 229 return fmt.Errorf("gmtls: 创建serverRandom失败: %s", err) 230 } 231 232 if len(hs.clientHello.secureRenegotiation) != 0 { 233 _ = c.sendAlert(alertHandshakeFailure) 234 return errors.New("gmtls: initial handshake had non-empty renegotiation extension") 235 } 236 237 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported 238 hs.hello.compressionMethod = compressionNone 239 if len(hs.clientHello.serverName) > 0 { 240 c.serverName = hs.clientHello.serverName 241 } 242 243 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 244 if err != nil { 245 _ = c.sendAlert(alertNoApplicationProtocol) 246 return err 247 } 248 hs.hello.alpnProtocol = selectedProto 249 c.clientProtocol = selectedProto 250 251 hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 252 if err != nil { 253 var alt alert 254 if err == errNoCertificates { 255 alt = alertUnrecognizedName 256 } else { 257 alt = alertInternalError 258 } 259 _ = c.sendAlert(alt) 260 return err 261 } 262 if hs.clientHello.scts { 263 hs.hello.scts = hs.cert.SignedCertificateTimestamps 264 } 265 266 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints) 267 268 if hs.ecdheOk { 269 // Although omitting the ec_point_formats extension is permitted, some 270 // old OpenSSL version will refuse to handshake if not present. 271 // 272 // Per RFC 4492, section 5.1.2, implementations MUST support the 273 // uncompressed point format. See golang.org/issue/31943. 274 hs.hello.supportedPoints = []uint8{pointFormatUncompressed} 275 } 276 277 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok { 278 switch priv.Public().(type) { 279 case *sm2.PublicKey, *ecdsa.PublicKey: 280 hs.ecSignOk = true 281 case ed25519.PublicKey: 282 hs.ecSignOk = true 283 case *rsa.PublicKey: 284 hs.rsaSignOk = true 285 default: 286 _ = c.sendAlert(alertInternalError) 287 return fmt.Errorf("gmtls: unsupported signing key type (%T)", priv.Public()) 288 } 289 } 290 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok { 291 switch priv.Public().(type) { 292 case *rsa.PublicKey: 293 hs.rsaDecryptOk = true 294 default: 295 _ = c.sendAlert(alertInternalError) 296 return fmt.Errorf("gmtls: unsupported decryption key type (%T)", priv.Public()) 297 } 298 } 299 300 return nil 301 } 302 303 // negotiateALPN picks a shared ALPN protocol that both sides support in server 304 // preference order. If ALPN is not configured or the peer doesn't support it, 305 // it returns "" and no error. 306 func negotiateALPN(serverProtos, clientProtos []string) (string, error) { 307 if len(serverProtos) == 0 || len(clientProtos) == 0 { 308 return "", nil 309 } 310 var http11fallback bool 311 for _, s := range serverProtos { 312 for _, c := range clientProtos { 313 if s == c { 314 return s, nil 315 } 316 if s == "h2" && c == "http/1.1" { 317 http11fallback = true 318 } 319 } 320 } 321 // As a special case, let http/1.1 clients connect to h2 servers as if they 322 // didn't support ALPN. We used not to enforce protocol overlap, so over 323 // time a number of HTTP servers were configured with only "h2", but 324 // expected to accept connections from "http/1.1" clients. See Issue 46310. 325 if http11fallback { 326 return "", nil 327 } 328 return "", fmt.Errorf("gmtls: client requested unsupported application protocols (%s)", clientProtos) 329 } 330 331 // supportsECDHE returns whether ECDHE key exchanges can be used with this 332 // pre-TLS 1.3 client. 333 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool { 334 supportsCurve := false 335 for _, curve := range supportedCurves { 336 if c.supportsCurve(curve) { 337 supportsCurve = true 338 break 339 } 340 } 341 342 supportsPointFormat := false 343 for _, pointFormat := range supportedPoints { 344 if pointFormat == pointFormatUncompressed { 345 supportsPointFormat = true 346 break 347 } 348 } 349 350 return supportsCurve && supportsPointFormat 351 } 352 353 func (hs *serverHandshakeState) pickCipherSuite() error { 354 c := hs.c 355 356 preferenceOrder := cipherSuitesPreferenceOrder 357 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 358 preferenceOrder = cipherSuitesPreferenceOrderNoAES 359 } 360 361 configCipherSuites := c.config.cipherSuites() 362 preferenceList := make([]uint16, 0, len(configCipherSuites)) 363 for _, suiteID := range preferenceOrder { 364 for _, id := range configCipherSuites { 365 if id == suiteID { 366 preferenceList = append(preferenceList, id) 367 break 368 } 369 } 370 } 371 372 hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk) 373 if hs.suite == nil { 374 _ = c.sendAlert(alertHandshakeFailure) 375 return errors.New("gmtls: no cipher suite supported by both client and server") 376 } 377 c.cipherSuite = hs.suite.id 378 379 for _, id := range hs.clientHello.cipherSuites { 380 if id == TLS_FALLBACK_SCSV { 381 // The client is doing a fallback connection. See RFC 7507. 382 if hs.clientHello.vers < c.config.maxSupportedVersion() { 383 _ = c.sendAlert(alertInappropriateFallback) 384 return errors.New("gmtls: client using inappropriate protocol fallback") 385 } 386 break 387 } 388 } 389 390 return nil 391 } 392 393 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool { 394 if c.flags&suiteECDHE != 0 { 395 if !hs.ecdheOk { 396 return false 397 } 398 if c.flags&suiteECSign != 0 { 399 if !hs.ecSignOk { 400 return false 401 } 402 } else if !hs.rsaSignOk { 403 return false 404 } 405 } else if !hs.rsaDecryptOk { 406 return false 407 } 408 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { 409 return false 410 } 411 return true 412 } 413 414 // checkForResumption reports whether we should perform resumption on this connection. 415 func (hs *serverHandshakeState) checkForResumption() bool { 416 c := hs.c 417 418 if c.config.SessionTicketsDisabled { 419 return false 420 } 421 422 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket) 423 if plaintext == nil { 424 return false 425 } 426 hs.sessionState = &sessionState{usedOldKey: usedOldKey} 427 ok := hs.sessionState.unmarshal(plaintext) 428 if !ok { 429 return false 430 } 431 432 createdAt := time.Unix(int64(hs.sessionState.createdAt), 0) 433 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 434 return false 435 } 436 437 // Never resume a session for a different TLS version. 438 if c.vers != hs.sessionState.vers { 439 return false 440 } 441 442 cipherSuiteOk := false 443 // Check that the client is still offering the ciphersuite in the session. 444 for _, id := range hs.clientHello.cipherSuites { 445 if id == hs.sessionState.cipherSuite { 446 cipherSuiteOk = true 447 break 448 } 449 } 450 if !cipherSuiteOk { 451 return false 452 } 453 454 // Check that we also support the ciphersuite from the session. 455 hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite}, 456 c.config.cipherSuites(), hs.cipherSuiteOk) 457 if hs.suite == nil { 458 return false 459 } 460 461 sessionHasClientCerts := len(hs.sessionState.certificates) != 0 462 needClientCerts := requiresClientCert(c.config.ClientAuth) 463 if needClientCerts && !sessionHasClientCerts { 464 return false 465 } 466 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 467 return false 468 } 469 470 return true 471 } 472 473 func (hs *serverHandshakeState) doResumeHandshake() error { 474 c := hs.c 475 476 hs.hello.cipherSuite = hs.suite.id 477 c.cipherSuite = hs.suite.id 478 // We echo the client's session ID in the ServerHello to let it know 479 // that we're doing a resumption. 480 hs.hello.sessionId = hs.clientHello.sessionId 481 hs.hello.ticketSupported = hs.sessionState.usedOldKey 482 hs.finishedHash = newFinishedHash(c.vers, hs.suite) 483 hs.finishedHash.discardHandshakeBuffer() 484 _, _ = hs.finishedHash.Write(hs.clientHello.marshal()) 485 _, _ = hs.finishedHash.Write(hs.hello.marshal()) 486 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 487 return err 488 } 489 490 if err := c.processCertsFromClient(Certificate{ 491 Certificate: hs.sessionState.certificates, 492 }); err != nil { 493 return err 494 } 495 496 if c.config.VerifyConnection != nil { 497 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 498 _ = c.sendAlert(alertBadCertificate) 499 return fmt.Errorf("gmtls: VerifyConnection时发生错误: %s", err) 500 } 501 } 502 503 hs.masterSecret = hs.sessionState.masterSecret 504 505 return nil 506 } 507 508 // 完整握手过程 tls1.2 509 func (hs *serverHandshakeState) doFullHandshake() error { 510 c := hs.c 511 512 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { 513 hs.hello.ocspStapling = true 514 } 515 516 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled 517 hs.hello.cipherSuite = hs.suite.id 518 519 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite) 520 if c.config.ClientAuth == NoClientCert { 521 // No need to keep a full record of the handshake if client 522 // certificates won't be used. 523 hs.finishedHash.discardHandshakeBuffer() 524 } 525 _, _ = hs.finishedHash.Write(hs.clientHello.marshal()) 526 _, _ = hs.finishedHash.Write(hs.hello.marshal()) 527 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 528 return err 529 } 530 531 certMsg := new(certificateMsg) 532 certMsg.certificates = hs.cert.Certificate 533 _, _ = hs.finishedHash.Write(certMsg.marshal()) 534 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 535 return err 536 } 537 538 if hs.hello.ocspStapling { 539 certStatus := new(certificateStatusMsg) 540 certStatus.response = hs.cert.OCSPStaple 541 _, _ = hs.finishedHash.Write(certStatus.marshal()) 542 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil { 543 return err 544 } 545 } 546 547 keyAgreement := hs.suite.ka(c.vers) 548 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello) 549 if err != nil { 550 _ = c.sendAlert(alertHandshakeFailure) 551 return fmt.Errorf("gmtls: generateServerKeyExchange时发生错误: %s", err) 552 } 553 if skx != nil { 554 _, _ = hs.finishedHash.Write(skx.marshal()) 555 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil { 556 return err 557 } 558 } 559 560 var certReq *certificateRequestMsg 561 if c.config.ClientAuth >= RequestClientCert { 562 // Request a client certificate 563 certReq = new(certificateRequestMsg) 564 certReq.certificateTypes = []byte{ 565 byte(certTypeRSASign), 566 byte(certTypeECDSASign), 567 } 568 if c.vers >= VersionTLS12 { 569 certReq.hasSignatureAlgorithm = true 570 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms 571 } 572 573 // An empty list of certificateAuthorities signals to 574 // the client that it may send any certificate in response 575 // to our request. When we know the CAs we trust, then 576 // we can send them down, so that the client can choose 577 // an appropriate certificate to give to us. 578 if c.config.ClientCAs != nil { 579 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 580 } 581 _, _ = hs.finishedHash.Write(certReq.marshal()) 582 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 583 return err 584 } 585 } 586 587 helloDone := new(serverHelloDoneMsg) 588 _, _ = hs.finishedHash.Write(helloDone.marshal()) 589 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil { 590 return err 591 } 592 593 if _, err := c.flush(); err != nil { 594 return err 595 } 596 597 var pub crypto.PublicKey // public key for client auth, if any 598 599 msg, err := c.readHandshake() 600 if err != nil { 601 return err 602 } 603 604 // If we requested a client certificate, then the client must send a 605 // certificate message, even if it's empty. 606 if c.config.ClientAuth >= RequestClientCert { 607 certMsg, ok := msg.(*certificateMsg) 608 if !ok { 609 _ = c.sendAlert(alertUnexpectedMessage) 610 return unexpectedMessageError(certMsg, msg) 611 } 612 _, _ = hs.finishedHash.Write(certMsg.marshal()) 613 614 if err := c.processCertsFromClient(Certificate{ 615 Certificate: certMsg.certificates, 616 }); err != nil { 617 return err 618 } 619 if len(certMsg.certificates) != 0 { 620 pub = c.peerCertificates[0].PublicKey 621 } 622 623 msg, err = c.readHandshake() 624 if err != nil { 625 return err 626 } 627 } 628 if c.config.VerifyConnection != nil { 629 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 630 _ = c.sendAlert(alertBadCertificate) 631 return err 632 } 633 } 634 635 // Get client key exchange 636 ckx, ok := msg.(*clientKeyExchangeMsg) 637 if !ok { 638 _ = c.sendAlert(alertUnexpectedMessage) 639 return unexpectedMessageError(ckx, msg) 640 } 641 _, _ = hs.finishedHash.Write(ckx.marshal()) 642 643 // 获取预主密钥, 分为RSA与ECDHE 644 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers) 645 if err != nil { 646 _ = c.sendAlert(alertHandshakeFailure) 647 return err 648 } 649 // 根据预主密钥,随机数C、S,使用PRF函数计算主密钥 650 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) 651 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil { 652 _ = c.sendAlert(alertInternalError) 653 return err 654 } 655 656 // If we received a client cert in response to our certificate request message, 657 // the client will send us a certificateVerifyMsg immediately after the 658 // clientKeyExchangeMsg. This message is a digest of all preceding 659 // handshake-layer messages that is signed using the private key corresponding 660 // to the client's certificate. This allows us to verify that the client is in 661 // possession of the private key of the certificate. 662 if len(c.peerCertificates) > 0 { 663 msg, err = c.readHandshake() 664 if err != nil { 665 return err 666 } 667 certVerify, ok := msg.(*certificateVerifyMsg) 668 if !ok { 669 _ = c.sendAlert(alertUnexpectedMessage) 670 return unexpectedMessageError(certVerify, msg) 671 } 672 673 var sigType uint8 674 var sigHash x509.Hash 675 if c.vers >= VersionTLS12 { 676 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) { 677 _ = c.sendAlert(alertIllegalParameter) 678 return errors.New("gmtls: client certificate used with invalid signature algorithm") 679 } 680 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 681 if err != nil { 682 return c.sendAlert(alertInternalError) 683 } 684 } else { 685 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub) 686 if err != nil { 687 _ = c.sendAlert(alertIllegalParameter) 688 return err 689 } 690 } 691 692 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret) 693 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil { 694 _ = c.sendAlert(alertDecryptError) 695 return fmt.Errorf("gmtls: invalid signature by the client certificate: %s", err) 696 } 697 698 _, _ = hs.finishedHash.Write(certVerify.marshal()) 699 } 700 701 hs.finishedHash.discardHandshakeBuffer() 702 703 return nil 704 } 705 706 // 派生会话密钥 tls1.2 707 func (hs *serverHandshakeState) establishKeys() error { 708 c := hs.c 709 // 根据主密钥、随机数C/S,使用PRF函数派生出6个会话密钥 710 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 711 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) 712 713 var clientCipher, serverCipher interface{} 714 var clientHash, serverHash hash.Hash 715 716 if hs.suite.aead == nil { 717 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) 718 clientHash = hs.suite.mac(clientMAC) 719 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) 720 serverHash = hs.suite.mac(serverMAC) 721 } else { 722 clientCipher = hs.suite.aead(clientKey, clientIV) 723 serverCipher = hs.suite.aead(serverKey, serverIV) 724 } 725 726 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) 727 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) 728 729 return nil 730 } 731 732 func (hs *serverHandshakeState) readFinished(out []byte) error { 733 c := hs.c 734 735 if err := c.readChangeCipherSpec(); err != nil { 736 return err 737 } 738 739 msg, err := c.readHandshake() 740 if err != nil { 741 return err 742 } 743 clientFinished, ok := msg.(*finishedMsg) 744 if !ok { 745 _ = c.sendAlert(alertUnexpectedMessage) 746 return unexpectedMessageError(clientFinished, msg) 747 } 748 749 verify := hs.finishedHash.clientSum(hs.masterSecret) 750 if len(verify) != len(clientFinished.verifyData) || 751 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 752 _ = c.sendAlert(alertHandshakeFailure) 753 return errors.New("gmtls: client's Finished message is incorrect") 754 } 755 756 _, _ = hs.finishedHash.Write(clientFinished.marshal()) 757 copy(out, verify) 758 return nil 759 } 760 761 func (hs *serverHandshakeState) sendSessionTicket() error { 762 // ticketSupported is set in a resumption handshake if the 763 // ticket from the client was encrypted with an old session 764 // ticket key and thus a refreshed ticket should be sent. 765 if !hs.hello.ticketSupported { 766 return nil 767 } 768 769 c := hs.c 770 m := new(newSessionTicketMsg) 771 772 createdAt := uint64(c.config.time().Unix()) 773 if hs.sessionState != nil { 774 // If this is re-wrapping an old key, then keep 775 // the original time it was created. 776 createdAt = hs.sessionState.createdAt 777 } 778 779 var certsFromClient [][]byte 780 for _, cert := range c.peerCertificates { 781 certsFromClient = append(certsFromClient, cert.Raw) 782 } 783 state := sessionState{ 784 vers: c.vers, 785 cipherSuite: hs.suite.id, 786 createdAt: createdAt, 787 masterSecret: hs.masterSecret, 788 certificates: certsFromClient, 789 } 790 var err error 791 m.ticket, err = c.encryptTicket(state.marshal()) 792 if err != nil { 793 return err 794 } 795 796 _, _ = hs.finishedHash.Write(m.marshal()) 797 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 798 return err 799 } 800 801 return nil 802 } 803 804 func (hs *serverHandshakeState) sendFinished(out []byte) error { 805 c := hs.c 806 807 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 808 return err 809 } 810 811 finished := new(finishedMsg) 812 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) 813 _, _ = hs.finishedHash.Write(finished.marshal()) 814 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 815 return err 816 } 817 818 copy(out, finished.verifyData) 819 820 return nil 821 } 822 823 // 检查客户端证书。 824 // processCertsFromClient takes a chain of client certificates either from a 825 // Certificates message or from a sessionState and verifies them. It returns 826 // the public key of the leaf certificate. 827 func (c *Conn) processCertsFromClient(certificate Certificate) error { 828 certificates := certificate.Certificate 829 certs := make([]*x509.Certificate, len(certificates)) 830 var err error 831 for i, asn1Data := range certificates { 832 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { 833 _ = c.sendAlert(alertBadCertificate) 834 return fmt.Errorf("gmtls: failed to parse client certificate: %s", err) 835 } 836 } 837 838 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) { 839 _ = c.sendAlert(alertBadCertificate) 840 return errors.New("gmtls: client didn't provide a certificate") 841 } 842 843 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { 844 opts := x509.VerifyOptions{ 845 Roots: c.config.ClientCAs, 846 CurrentTime: c.config.time(), 847 Intermediates: x509.NewCertPool(), 848 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 849 } 850 851 for _, cert := range certs[1:] { 852 opts.Intermediates.AddCert(cert) 853 } 854 // 从子证书开始验证签名并尝试构建信任链 855 chains, err := certs[0].Verify(opts) 856 if err != nil { 857 _ = c.sendAlert(alertBadCertificate) 858 return fmt.Errorf("gmtls: failed to verify client certificate: %s", err) 859 } 860 861 c.verifiedChains = chains 862 } 863 864 c.peerCertificates = certs 865 c.ocspResponse = certificate.OCSPStaple 866 c.scts = certificate.SignedCertificateTimestamps 867 868 if len(certs) > 0 { 869 // 补充sm2条件 870 switch certs[0].PublicKey.(type) { 871 case *sm2.PublicKey, *ecdsa.PublicKey, *ecdsa_ext.PublicKey, *rsa.PublicKey, ed25519.PublicKey: 872 default: 873 _ = c.sendAlert(alertUnsupportedCertificate) 874 return fmt.Errorf("gmtls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey) 875 } 876 } 877 878 if c.config.VerifyPeerCertificate != nil { 879 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { 880 _ = c.sendAlert(alertBadCertificate) 881 return fmt.Errorf("gmtls: VerifyPeerCertificate时发生错误: %s", err) 882 } 883 } 884 885 return nil 886 } 887 888 func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo { 889 supportedVersions := clientHello.supportedVersions 890 if len(clientHello.supportedVersions) == 0 { 891 supportedVersions = supportedVersionsFromMax(clientHello.vers) 892 } 893 894 return &ClientHelloInfo{ 895 CipherSuites: clientHello.cipherSuites, 896 ServerName: clientHello.serverName, 897 SupportedCurves: clientHello.supportedCurves, 898 SupportedPoints: clientHello.supportedPoints, 899 SignatureSchemes: clientHello.supportedSignatureAlgorithms, 900 SupportedProtos: clientHello.alpnProtocols, 901 SupportedVersions: supportedVersions, 902 Conn: c.conn, 903 config: c.config, 904 ctx: ctx, 905 } 906 }