1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package runner 6 7import ( 8 "bytes" 9 "crypto" 10 "crypto/ecdsa" 11 "crypto/elliptic" 12 "crypto/rsa" 13 "crypto/subtle" 14 "crypto/x509" 15 "errors" 16 "fmt" 17 "io" 18 "math/big" 19 "net" 20 "time" 21 22 "./ed25519" 23) 24 25type clientHandshakeState struct { 26 c *Conn 27 serverHello *serverHelloMsg 28 hello *clientHelloMsg 29 suite *cipherSuite 30 finishedHash finishedHash 31 keyShares map[CurveID]ecdhCurve 32 masterSecret []byte 33 session *ClientSessionState 34 finishedBytes []byte 35} 36 37func mapClientHelloVersion(vers uint16, isDTLS bool) uint16 { 38 if !isDTLS { 39 return vers 40 } 41 42 switch vers { 43 case VersionTLS12: 44 return VersionDTLS12 45 case VersionTLS10: 46 return VersionDTLS10 47 } 48 49 panic("Unknown ClientHello version.") 50} 51 52func (c *Conn) clientHandshake() error { 53 if c.config == nil { 54 c.config = defaultConfig() 55 } 56 57 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify { 58 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") 59 } 60 61 c.sendHandshakeSeq = 0 62 c.recvHandshakeSeq = 0 63 64 nextProtosLength := 0 65 for _, proto := range c.config.NextProtos { 66 if l := len(proto); l > 255 { 67 return errors.New("tls: invalid NextProtos value") 68 } else { 69 nextProtosLength += 1 + l 70 } 71 } 72 if nextProtosLength > 0xffff { 73 return errors.New("tls: NextProtos values too large") 74 } 75 76 minVersion := c.config.minVersion(c.isDTLS) 77 maxVersion := c.config.maxVersion(c.isDTLS) 78 hello := &clientHelloMsg{ 79 isDTLS: c.isDTLS, 80 compressionMethods: []uint8{compressionNone}, 81 random: make([]byte, 32), 82 ocspStapling: !c.config.Bugs.NoOCSPStapling, 83 sctListSupported: !c.config.Bugs.NoSignedCertificateTimestamps, 84 serverName: c.config.ServerName, 85 supportedCurves: c.config.curvePreferences(), 86 supportedPoints: []uint8{pointFormatUncompressed}, 87 nextProtoNeg: len(c.config.NextProtos) > 0, 88 secureRenegotiation: []byte{}, 89 alpnProtocols: c.config.NextProtos, 90 quicTransportParams: c.config.QUICTransportParams, 91 duplicateExtension: c.config.Bugs.DuplicateExtension, 92 channelIDSupported: c.config.ChannelID != nil, 93 tokenBindingParams: c.config.TokenBindingParams, 94 tokenBindingVersion: c.config.TokenBindingVersion, 95 npnAfterAlpn: c.config.Bugs.SwapNPNAndALPN, 96 extendedMasterSecret: maxVersion >= VersionTLS10, 97 srtpProtectionProfiles: c.config.SRTPProtectionProfiles, 98 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer, 99 customExtension: c.config.Bugs.CustomExtension, 100 pskBinderFirst: c.config.Bugs.PSKBinderFirst, 101 omitExtensions: c.config.Bugs.OmitExtensions, 102 emptyExtensions: c.config.Bugs.EmptyExtensions, 103 } 104 105 if maxVersion >= VersionTLS13 { 106 hello.vers = mapClientHelloVersion(VersionTLS12, c.isDTLS) 107 if !c.config.Bugs.OmitSupportedVersions { 108 hello.supportedVersions = c.config.supportedVersions(c.isDTLS) 109 } 110 hello.pskKEModes = []byte{pskDHEKEMode} 111 } else { 112 hello.vers = mapClientHelloVersion(maxVersion, c.isDTLS) 113 } 114 115 if c.config.Bugs.SendClientVersion != 0 { 116 hello.vers = c.config.Bugs.SendClientVersion 117 } 118 119 if len(c.config.Bugs.SendSupportedVersions) > 0 { 120 hello.supportedVersions = c.config.Bugs.SendSupportedVersions 121 } 122 123 disableEMS := c.config.Bugs.NoExtendedMasterSecret 124 if c.cipherSuite != nil { 125 disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation 126 } 127 128 if disableEMS { 129 hello.extendedMasterSecret = false 130 } 131 132 if c.config.Bugs.NoSupportedCurves { 133 hello.supportedCurves = nil 134 } 135 136 if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 { 137 hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes 138 } 139 140 if c.config.Bugs.SendCompressionMethods != nil { 141 hello.compressionMethods = c.config.Bugs.SendCompressionMethods 142 } 143 144 if c.config.Bugs.SendSupportedPointFormats != nil { 145 hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats 146 } 147 148 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo { 149 if c.config.Bugs.BadRenegotiationInfo { 150 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...) 151 hello.secureRenegotiation[0] ^= 0x80 152 } else { 153 hello.secureRenegotiation = c.clientVerify 154 } 155 } 156 157 if c.noRenegotiationInfo() { 158 hello.secureRenegotiation = nil 159 } 160 161 var keyShares map[CurveID]ecdhCurve 162 if maxVersion >= VersionTLS13 { 163 keyShares = make(map[CurveID]ecdhCurve) 164 hello.hasKeyShares = true 165 hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData 166 curvesToSend := c.config.defaultCurves() 167 for _, curveID := range hello.supportedCurves { 168 if !curvesToSend[curveID] { 169 continue 170 } 171 curve, ok := curveForCurveID(curveID) 172 if !ok { 173 continue 174 } 175 publicKey, err := curve.offer(c.config.rand()) 176 if err != nil { 177 return err 178 } 179 180 if c.config.Bugs.SendCurve != 0 { 181 curveID = c.config.Bugs.SendCurve 182 } 183 if c.config.Bugs.InvalidECDHPoint { 184 publicKey[0] ^= 0xff 185 } 186 187 hello.keyShares = append(hello.keyShares, keyShareEntry{ 188 group: curveID, 189 keyExchange: publicKey, 190 }) 191 keyShares[curveID] = curve 192 193 if c.config.Bugs.DuplicateKeyShares { 194 hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1]) 195 } 196 } 197 198 if c.config.Bugs.MissingKeyShare { 199 hello.hasKeyShares = false 200 } 201 } 202 203 possibleCipherSuites := c.config.cipherSuites() 204 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) 205 206NextCipherSuite: 207 for _, suiteId := range possibleCipherSuites { 208 for _, suite := range cipherSuites { 209 if suite.id != suiteId { 210 continue 211 } 212 // Don't advertise TLS 1.2-only cipher suites unless 213 // we're attempting TLS 1.2. 214 if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 { 215 continue 216 } 217 hello.cipherSuites = append(hello.cipherSuites, suiteId) 218 continue NextCipherSuite 219 } 220 } 221 222 if c.config.Bugs.AdvertiseAllConfiguredCiphers { 223 hello.cipherSuites = possibleCipherSuites 224 } 225 226 if c.config.Bugs.SendRenegotiationSCSV { 227 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV) 228 } 229 230 if c.config.Bugs.SendFallbackSCSV { 231 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV) 232 } 233 234 _, err := io.ReadFull(c.config.rand(), hello.random) 235 if err != nil { 236 c.sendAlert(alertInternalError) 237 return errors.New("tls: short read from Rand: " + err.Error()) 238 } 239 240 if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms { 241 hello.signatureAlgorithms = c.config.verifySignatureAlgorithms() 242 } 243 244 var session *ClientSessionState 245 var cacheKey string 246 sessionCache := c.config.ClientSessionCache 247 248 if sessionCache != nil { 249 hello.ticketSupported = !c.config.SessionTicketsDisabled 250 251 // Try to resume a previously negotiated TLS session, if 252 // available. 253 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 254 // TODO(nharper): Support storing more than one session 255 // ticket for TLS 1.3. 256 candidateSession, ok := sessionCache.Get(cacheKey) 257 if ok { 258 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil 259 260 // Check that the ciphersuite/version used for the 261 // previous session are still valid. 262 cipherSuiteOk := false 263 if candidateSession.vers <= VersionTLS12 { 264 for _, id := range hello.cipherSuites { 265 if id == candidateSession.cipherSuite { 266 cipherSuiteOk = true 267 break 268 } 269 } 270 } else { 271 // TLS 1.3 allows the cipher to change on 272 // resumption. 273 cipherSuiteOk = true 274 } 275 276 versOk := candidateSession.vers >= minVersion && 277 candidateSession.vers <= maxVersion 278 if ticketOk && versOk && cipherSuiteOk { 279 session = candidateSession 280 } 281 } 282 } 283 284 var pskCipherSuite *cipherSuite 285 if session != nil && c.config.time().Before(session.ticketExpiration) { 286 ticket := session.sessionTicket 287 if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 { 288 // Copy the ticket so FilterTicket may act in-place. 289 ticket = make([]byte, len(session.sessionTicket)) 290 copy(ticket, session.sessionTicket) 291 292 ticket, err = c.config.Bugs.FilterTicket(ticket) 293 if err != nil { 294 return err 295 } 296 } 297 298 if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets { 299 pskCipherSuite = cipherSuiteFromID(session.cipherSuite) 300 if pskCipherSuite == nil { 301 return errors.New("tls: client session cache has invalid cipher suite") 302 } 303 // TODO(nharper): Support sending more 304 // than one PSK identity. 305 ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond) 306 if c.config.Bugs.SendTicketAge != 0 { 307 ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond) 308 } 309 psk := pskIdentity{ 310 ticket: ticket, 311 obfuscatedTicketAge: session.ticketAgeAdd + ticketAge, 312 } 313 hello.pskIdentities = []pskIdentity{psk} 314 315 if c.config.Bugs.ExtraPSKIdentity { 316 hello.pskIdentities = append(hello.pskIdentities, psk) 317 } 318 } 319 320 if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets { 321 if ticket != nil { 322 hello.sessionTicket = ticket 323 // A random session ID is used to detect when the 324 // server accepted the ticket and is resuming a session 325 // (see RFC 5077). 326 sessionIdLen := 16 327 if c.config.Bugs.TicketSessionIDLength != 0 { 328 sessionIdLen = c.config.Bugs.TicketSessionIDLength 329 } 330 if c.config.Bugs.EmptyTicketSessionID { 331 sessionIdLen = 0 332 } 333 hello.sessionId = make([]byte, sessionIdLen) 334 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { 335 c.sendAlert(alertInternalError) 336 return errors.New("tls: short read from Rand: " + err.Error()) 337 } 338 } else { 339 hello.sessionId = session.sessionId 340 } 341 } 342 } 343 344 if c.config.Bugs.SendCipherSuites != nil { 345 hello.cipherSuites = c.config.Bugs.SendCipherSuites 346 } 347 348 var sendEarlyData bool 349 if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil { 350 hello.hasEarlyData = true 351 sendEarlyData = true 352 } 353 if c.config.Bugs.SendFakeEarlyDataLength > 0 { 354 hello.hasEarlyData = true 355 } 356 if c.config.Bugs.OmitEarlyDataExtension { 357 hello.hasEarlyData = false 358 } 359 if c.config.Bugs.SendClientHelloSessionID != nil { 360 hello.sessionId = c.config.Bugs.SendClientHelloSessionID 361 } 362 363 var helloBytes []byte 364 if c.config.Bugs.SendV2ClientHello { 365 // Test that the peer left-pads random. 366 hello.random[0] = 0 367 v2Hello := &v2ClientHelloMsg{ 368 vers: hello.vers, 369 cipherSuites: hello.cipherSuites, 370 // No session resumption for V2ClientHello. 371 sessionId: nil, 372 challenge: hello.random[1:], 373 } 374 helloBytes = v2Hello.marshal() 375 c.writeV2Record(helloBytes) 376 } else { 377 if len(hello.pskIdentities) > 0 { 378 version := session.wireVersion 379 // We may have a pre-1.3 session if SendBothTickets is 380 // set. Fill in an arbitrary TLS 1.3 version to compute 381 // the binder. 382 if session.vers < VersionTLS13 { 383 version = tls13Draft23Version 384 } 385 generatePSKBinders(version, hello, pskCipherSuite, session.masterSecret, []byte{}, []byte{}, c.config) 386 } 387 helloBytes = hello.marshal() 388 389 if c.config.Bugs.PartialClientFinishedWithClientHello { 390 // Include one byte of Finished. We can compute it 391 // without completing the handshake. This assumes we 392 // negotiate TLS 1.3 with no HelloRetryRequest or 393 // CertificateRequest. 394 toWrite := make([]byte, 0, len(helloBytes)+1) 395 toWrite = append(toWrite, helloBytes...) 396 toWrite = append(toWrite, typeFinished) 397 c.writeRecord(recordTypeHandshake, toWrite) 398 } else { 399 c.writeRecord(recordTypeHandshake, helloBytes) 400 } 401 } 402 c.flushHandshake() 403 404 if err := c.simulatePacketLoss(nil); err != nil { 405 return err 406 } 407 if c.config.Bugs.SendEarlyAlert { 408 c.sendAlert(alertHandshakeFailure) 409 } 410 if c.config.Bugs.SendFakeEarlyDataLength > 0 { 411 c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength) 412 } 413 414 // Derive early write keys and set Conn state to allow early writes. 415 if sendEarlyData { 416 finishedHash := newFinishedHash(session.wireVersion, c.isDTLS, pskCipherSuite) 417 finishedHash.addEntropy(session.masterSecret) 418 finishedHash.Write(helloBytes) 419 420 if !c.config.Bugs.SkipChangeCipherSpec { 421 c.wireVersion = session.wireVersion 422 c.vers = VersionTLS13 423 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 424 c.wireVersion = 0 425 c.vers = 0 426 } 427 428 earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel) 429 c.earlyExporterSecret = finishedHash.deriveSecret(earlyExporterLabel) 430 431 c.useOutTrafficSecret(session.wireVersion, pskCipherSuite, earlyTrafficSecret) 432 for _, earlyData := range c.config.Bugs.SendEarlyData { 433 if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil { 434 return err 435 } 436 } 437 } 438 439 msg, err := c.readHandshake() 440 if err != nil { 441 return err 442 } 443 444 if c.isDTLS { 445 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg) 446 if ok { 447 if helloVerifyRequest.vers != VersionDTLS10 { 448 // Per RFC 6347, the version field in 449 // HelloVerifyRequest SHOULD be always DTLS 450 // 1.0. Enforce this for testing purposes. 451 return errors.New("dtls: bad HelloVerifyRequest version") 452 } 453 454 hello.raw = nil 455 hello.cookie = helloVerifyRequest.cookie 456 helloBytes = hello.marshal() 457 c.writeRecord(recordTypeHandshake, helloBytes) 458 c.flushHandshake() 459 460 if err := c.simulatePacketLoss(nil); err != nil { 461 return err 462 } 463 msg, err = c.readHandshake() 464 if err != nil { 465 return err 466 } 467 } 468 } 469 470 var serverWireVersion uint16 471 switch m := msg.(type) { 472 case *helloRetryRequestMsg: 473 serverWireVersion = m.vers 474 case *serverHelloMsg: 475 serverWireVersion = m.vers 476 default: 477 c.sendAlert(alertUnexpectedMessage) 478 return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg) 479 } 480 481 serverVersion, ok := c.config.isSupportedVersion(serverWireVersion, c.isDTLS) 482 if !ok { 483 c.sendAlert(alertProtocolVersion) 484 return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers) 485 } 486 c.wireVersion = serverWireVersion 487 c.vers = serverVersion 488 c.haveVers = true 489 490 if c.vers >= VersionTLS13 { 491 // The first server message must be followed by a ChangeCipherSpec. 492 c.expectTLS13ChangeCipherSpec = true 493 } 494 495 helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg) 496 var secondHelloBytes []byte 497 if haveHelloRetryRequest { 498 // Explicitly read the ChangeCipherSpec now; it should 499 // be attached to the first flight, not the second flight. 500 if err := c.readTLS13ChangeCipherSpec(); err != nil { 501 return err 502 } 503 504 c.out.resetCipher() 505 if len(helloRetryRequest.cookie) > 0 { 506 hello.tls13Cookie = helloRetryRequest.cookie 507 } 508 509 if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 { 510 helloRetryRequest.hasSelectedGroup = true 511 helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve 512 } 513 if helloRetryRequest.hasSelectedGroup { 514 var hrrCurveFound bool 515 group := helloRetryRequest.selectedGroup 516 for _, curveID := range hello.supportedCurves { 517 if group == curveID { 518 hrrCurveFound = true 519 break 520 } 521 } 522 if !hrrCurveFound || keyShares[group] != nil { 523 c.sendAlert(alertHandshakeFailure) 524 return errors.New("tls: received invalid HelloRetryRequest") 525 } 526 curve, ok := curveForCurveID(group) 527 if !ok { 528 return errors.New("tls: Unable to get curve requested in HelloRetryRequest") 529 } 530 publicKey, err := curve.offer(c.config.rand()) 531 if err != nil { 532 return err 533 } 534 keyShares[group] = curve 535 hello.keyShares = []keyShareEntry{{ 536 group: group, 537 keyExchange: publicKey, 538 }} 539 } 540 541 if c.config.Bugs.SecondClientHelloMissingKeyShare { 542 hello.hasKeyShares = false 543 } 544 545 hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello 546 hello.raw = nil 547 548 if len(hello.pskIdentities) > 0 { 549 generatePSKBinders(c.wireVersion, hello, pskCipherSuite, session.masterSecret, helloBytes, helloRetryRequest.marshal(), c.config) 550 } 551 secondHelloBytes = hello.marshal() 552 553 if c.config.Bugs.InterleaveEarlyData { 554 c.sendFakeEarlyData(4) 555 c.writeRecord(recordTypeHandshake, secondHelloBytes[:16]) 556 c.sendFakeEarlyData(4) 557 c.writeRecord(recordTypeHandshake, secondHelloBytes[16:]) 558 } else { 559 c.writeRecord(recordTypeHandshake, secondHelloBytes) 560 } 561 c.flushHandshake() 562 563 if c.config.Bugs.SendEarlyDataOnSecondClientHello { 564 c.sendFakeEarlyData(4) 565 } 566 567 msg, err = c.readHandshake() 568 if err != nil { 569 return err 570 } 571 } 572 573 serverHello, ok := msg.(*serverHelloMsg) 574 if !ok { 575 c.sendAlert(alertUnexpectedMessage) 576 return unexpectedMessageError(serverHello, msg) 577 } 578 579 if serverWireVersion != serverHello.vers { 580 c.sendAlert(alertProtocolVersion) 581 return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers) 582 } 583 584 // Check for downgrade signals in the server random, per 585 // draft-ietf-tls-tls13-16, section 4.1.3. 586 if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 { 587 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) { 588 c.sendAlert(alertProtocolVersion) 589 return errors.New("tls: downgrade from TLS 1.3 detected") 590 } 591 } 592 if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 { 593 if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) { 594 c.sendAlert(alertProtocolVersion) 595 return errors.New("tls: downgrade from TLS 1.2 detected") 596 } 597 } 598 if c.config.Bugs.ExpectDraftTLS13DowngradeRandom && !bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13Draft) { 599 return errors.New("tls: server did not send draft TLS 1.3 anti-downgrade signal") 600 } 601 602 suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite) 603 if suite == nil { 604 c.sendAlert(alertHandshakeFailure) 605 return fmt.Errorf("tls: server selected an unsupported cipher suite") 606 } 607 608 if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group { 609 c.sendAlert(alertHandshakeFailure) 610 return errors.New("tls: ServerHello parameters did not match HelloRetryRequest") 611 } 612 613 if c.config.Bugs.ExpectOmitExtensions && !serverHello.omitExtensions { 614 return errors.New("tls: ServerHello did not omit extensions") 615 } 616 617 hs := &clientHandshakeState{ 618 c: c, 619 serverHello: serverHello, 620 hello: hello, 621 suite: suite, 622 finishedHash: newFinishedHash(c.wireVersion, c.isDTLS, suite), 623 keyShares: keyShares, 624 session: session, 625 } 626 627 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1) 628 if haveHelloRetryRequest { 629 err = hs.finishedHash.UpdateForHelloRetryRequest() 630 if err != nil { 631 return err 632 } 633 hs.writeServerHash(helloRetryRequest.marshal()) 634 hs.writeClientHash(secondHelloBytes) 635 } 636 hs.writeServerHash(hs.serverHello.marshal()) 637 638 if c.vers >= VersionTLS13 { 639 if err := hs.doTLS13Handshake(); err != nil { 640 return err 641 } 642 } else { 643 if c.config.Bugs.EarlyChangeCipherSpec > 0 { 644 hs.establishKeys() 645 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 646 } 647 648 if hs.serverHello.compressionMethod != compressionNone { 649 c.sendAlert(alertUnexpectedMessage) 650 return errors.New("tls: server selected unsupported compression format") 651 } 652 653 err = hs.processServerExtensions(&serverHello.extensions) 654 if err != nil { 655 return err 656 } 657 658 isResume, err := hs.processServerHello() 659 if err != nil { 660 return err 661 } 662 663 if isResume { 664 if c.config.Bugs.EarlyChangeCipherSpec == 0 { 665 if err := hs.establishKeys(); err != nil { 666 return err 667 } 668 } 669 if err := hs.readSessionTicket(); err != nil { 670 return err 671 } 672 if err := hs.readFinished(c.firstFinished[:]); err != nil { 673 return err 674 } 675 if err := hs.sendFinished(nil, isResume); err != nil { 676 return err 677 } 678 } else { 679 if err := hs.doFullHandshake(); err != nil { 680 return err 681 } 682 if err := hs.establishKeys(); err != nil { 683 return err 684 } 685 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil { 686 return err 687 } 688 // Most retransmits are triggered by a timeout, but the final 689 // leg of the handshake is retransmited upon re-receiving a 690 // Finished. 691 if err := c.simulatePacketLoss(func() { 692 c.sendHandshakeSeq-- 693 c.writeRecord(recordTypeHandshake, hs.finishedBytes) 694 c.flushHandshake() 695 }); err != nil { 696 return err 697 } 698 if err := hs.readSessionTicket(); err != nil { 699 return err 700 } 701 if err := hs.readFinished(nil); err != nil { 702 return err 703 } 704 } 705 706 if sessionCache != nil && hs.session != nil && session != hs.session { 707 if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 { 708 return errors.New("tls: new session used session IDs instead of tickets") 709 } 710 sessionCache.Put(cacheKey, hs.session) 711 } 712 713 c.didResume = isResume 714 c.exporterSecret = hs.masterSecret 715 } 716 717 c.handshakeComplete = true 718 c.cipherSuite = suite 719 copy(c.clientRandom[:], hs.hello.random) 720 copy(c.serverRandom[:], hs.serverHello.random) 721 722 return nil 723} 724 725func (hs *clientHandshakeState) doTLS13Handshake() error { 726 c := hs.c 727 728 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 729 return errors.New("tls: session IDs did not match.") 730 } 731 732 // Once the PRF hash is known, TLS 1.3 does not require a handshake 733 // buffer. 734 hs.finishedHash.discardHandshakeBuffer() 735 736 zeroSecret := hs.finishedHash.zeroSecret() 737 738 // Resolve PSK and compute the early secret. 739 // 740 // TODO(davidben): This will need to be handled slightly earlier once 741 // 0-RTT is implemented. 742 if hs.serverHello.hasPSKIdentity { 743 // We send at most one PSK identity. 744 if hs.session == nil || hs.serverHello.pskIdentity != 0 { 745 c.sendAlert(alertUnknownPSKIdentity) 746 return errors.New("tls: server sent unknown PSK identity") 747 } 748 sessionCipher := cipherSuiteFromID(hs.session.cipherSuite) 749 if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() { 750 c.sendAlert(alertHandshakeFailure) 751 return errors.New("tls: server resumed an invalid session for the cipher suite") 752 } 753 hs.finishedHash.addEntropy(hs.session.masterSecret) 754 c.didResume = true 755 } else { 756 hs.finishedHash.addEntropy(zeroSecret) 757 } 758 759 if !hs.serverHello.hasKeyShare { 760 c.sendAlert(alertUnsupportedExtension) 761 return errors.New("tls: server omitted KeyShare on resumption.") 762 } 763 764 // Resolve ECDHE and compute the handshake secret. 765 if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare { 766 curve, ok := hs.keyShares[hs.serverHello.keyShare.group] 767 if !ok { 768 c.sendAlert(alertHandshakeFailure) 769 return errors.New("tls: server selected an unsupported group") 770 } 771 c.curveID = hs.serverHello.keyShare.group 772 773 ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange) 774 if err != nil { 775 return err 776 } 777 hs.finishedHash.nextSecret() 778 hs.finishedHash.addEntropy(ecdheSecret) 779 } else { 780 hs.finishedHash.nextSecret() 781 hs.finishedHash.addEntropy(zeroSecret) 782 } 783 784 // Derive handshake traffic keys and switch read key to handshake 785 // traffic key. 786 clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel) 787 serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel) 788 if err := c.useInTrafficSecret(c.wireVersion, hs.suite, serverHandshakeTrafficSecret); err != nil { 789 return err 790 } 791 792 msg, err := c.readHandshake() 793 if err != nil { 794 return err 795 } 796 797 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 798 if !ok { 799 c.sendAlert(alertUnexpectedMessage) 800 return unexpectedMessageError(encryptedExtensions, msg) 801 } 802 hs.writeServerHash(encryptedExtensions.marshal()) 803 804 err = hs.processServerExtensions(&encryptedExtensions.extensions) 805 if err != nil { 806 return err 807 } 808 809 var chainToSend *Certificate 810 var certReq *certificateRequestMsg 811 if c.didResume { 812 // Copy over authentication from the session. 813 c.peerCertificates = hs.session.serverCertificates 814 c.sctList = hs.session.sctList 815 c.ocspResponse = hs.session.ocspResponse 816 } else { 817 msg, err := c.readHandshake() 818 if err != nil { 819 return err 820 } 821 822 var ok bool 823 certReq, ok = msg.(*certificateRequestMsg) 824 if ok { 825 if len(certReq.requestContext) != 0 { 826 return errors.New("tls: non-empty certificate request context sent in handshake") 827 } 828 829 if c.config.Bugs.ExpectNoCertificateAuthoritiesExtension && certReq.hasCAExtension { 830 return errors.New("tls: expected no certificate_authorities extension") 831 } 832 833 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences { 834 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms() 835 } 836 837 hs.writeServerHash(certReq.marshal()) 838 839 chainToSend, err = selectClientCertificate(c, certReq) 840 if err != nil { 841 return err 842 } 843 844 msg, err = c.readHandshake() 845 if err != nil { 846 return err 847 } 848 } 849 850 certMsg, ok := msg.(*certificateMsg) 851 if !ok { 852 c.sendAlert(alertUnexpectedMessage) 853 return unexpectedMessageError(certMsg, msg) 854 } 855 hs.writeServerHash(certMsg.marshal()) 856 857 // Check for unsolicited extensions. 858 for i, cert := range certMsg.certificates { 859 if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil { 860 c.sendAlert(alertUnsupportedExtension) 861 return errors.New("tls: unexpected OCSP response in the server certificate") 862 } 863 if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil { 864 c.sendAlert(alertUnsupportedExtension) 865 return errors.New("tls: unexpected SCT list in the server certificate") 866 } 867 if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) { 868 c.sendAlert(alertUnsupportedExtension) 869 return errors.New("tls: unexpected extensions in the server certificate") 870 } 871 } 872 873 if err := hs.verifyCertificates(certMsg); err != nil { 874 return err 875 } 876 leaf := c.peerCertificates[0] 877 c.ocspResponse = certMsg.certificates[0].ocspResponse 878 c.sctList = certMsg.certificates[0].sctList 879 880 msg, err = c.readHandshake() 881 if err != nil { 882 return err 883 } 884 certVerifyMsg, ok := msg.(*certificateVerifyMsg) 885 if !ok { 886 c.sendAlert(alertUnexpectedMessage) 887 return unexpectedMessageError(certVerifyMsg, msg) 888 } 889 890 c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm 891 input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13) 892 err = verifyMessage(c.vers, getCertificatePublicKey(leaf), c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature) 893 if err != nil { 894 return err 895 } 896 897 hs.writeServerHash(certVerifyMsg.marshal()) 898 } 899 900 msg, err = c.readHandshake() 901 if err != nil { 902 return err 903 } 904 serverFinished, ok := msg.(*finishedMsg) 905 if !ok { 906 c.sendAlert(alertUnexpectedMessage) 907 return unexpectedMessageError(serverFinished, msg) 908 } 909 910 verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret) 911 if len(verify) != len(serverFinished.verifyData) || 912 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { 913 c.sendAlert(alertHandshakeFailure) 914 return errors.New("tls: server's Finished message was incorrect") 915 } 916 917 hs.writeServerHash(serverFinished.marshal()) 918 919 // The various secrets do not incorporate the client's final leg, so 920 // derive them now before updating the handshake context. 921 hs.finishedHash.nextSecret() 922 hs.finishedHash.addEntropy(zeroSecret) 923 924 clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel) 925 serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel) 926 c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel) 927 928 // Switch to application data keys on read. In particular, any alerts 929 // from the client certificate are read over these keys. 930 if err := c.useInTrafficSecret(c.wireVersion, hs.suite, serverTrafficSecret); err != nil { 931 return err 932 } 933 934 // If we're expecting 0.5-RTT messages from the server, read them now. 935 var deferredTickets []*newSessionTicketMsg 936 if encryptedExtensions.extensions.hasEarlyData { 937 // BoringSSL will always send two tickets half-RTT when 938 // negotiating 0-RTT. 939 for i := 0; i < shimConfig.HalfRTTTickets; i++ { 940 msg, err := c.readHandshake() 941 if err != nil { 942 return fmt.Errorf("tls: error reading half-RTT ticket: %s", err) 943 } 944 newSessionTicket, ok := msg.(*newSessionTicketMsg) 945 if !ok { 946 return errors.New("tls: expected half-RTT ticket") 947 } 948 // Defer processing until the resumption secret is computed. 949 deferredTickets = append(deferredTickets, newSessionTicket) 950 } 951 for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData { 952 if err := c.readRecord(recordTypeApplicationData); err != nil { 953 return err 954 } 955 if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) { 956 return errors.New("ExpectHalfRTTData: did not get expected message") 957 } 958 c.in.freeBlock(c.input) 959 c.input = nil 960 } 961 } 962 963 // Send EndOfEarlyData and then switch write key to handshake 964 // traffic key. 965 if encryptedExtensions.extensions.hasEarlyData && c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData { 966 if c.config.Bugs.SendStrayEarlyHandshake { 967 helloRequest := new(helloRequestMsg) 968 c.writeRecord(recordTypeHandshake, helloRequest.marshal()) 969 } 970 endOfEarlyData := new(endOfEarlyDataMsg) 971 endOfEarlyData.nonEmpty = c.config.Bugs.NonEmptyEndOfEarlyData 972 c.writeRecord(recordTypeHandshake, endOfEarlyData.marshal()) 973 hs.writeClientHash(endOfEarlyData.marshal()) 974 } 975 976 if !c.config.Bugs.SkipChangeCipherSpec && !hs.hello.hasEarlyData { 977 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 978 } 979 980 for i := 0; i < c.config.Bugs.SendExtraChangeCipherSpec; i++ { 981 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 982 } 983 984 c.useOutTrafficSecret(c.wireVersion, hs.suite, clientHandshakeTrafficSecret) 985 986 if certReq != nil && !c.config.Bugs.SkipClientCertificate { 987 certMsg := &certificateMsg{ 988 hasRequestContext: true, 989 requestContext: certReq.requestContext, 990 } 991 if chainToSend != nil { 992 for _, certData := range chainToSend.Certificate { 993 certMsg.certificates = append(certMsg.certificates, certificateEntry{ 994 data: certData, 995 extraExtension: c.config.Bugs.SendExtensionOnCertificate, 996 }) 997 } 998 } 999 hs.writeClientHash(certMsg.marshal()) 1000 c.writeRecord(recordTypeHandshake, certMsg.marshal()) 1001 1002 if chainToSend != nil { 1003 certVerify := &certificateVerifyMsg{ 1004 hasSignatureAlgorithm: true, 1005 } 1006 1007 // Determine the hash to sign. 1008 privKey := chainToSend.PrivateKey 1009 1010 var err error 1011 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms) 1012 if err != nil { 1013 c.sendAlert(alertInternalError) 1014 return err 1015 } 1016 1017 input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13) 1018 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input) 1019 if err != nil { 1020 c.sendAlert(alertInternalError) 1021 return err 1022 } 1023 if c.config.Bugs.SendSignatureAlgorithm != 0 { 1024 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm 1025 } 1026 1027 if !c.config.Bugs.SkipCertificateVerify { 1028 hs.writeClientHash(certVerify.marshal()) 1029 c.writeRecord(recordTypeHandshake, certVerify.marshal()) 1030 } 1031 } 1032 } 1033 1034 if encryptedExtensions.extensions.channelIDRequested { 1035 channelIDHash := crypto.SHA256.New() 1036 channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13)) 1037 channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil)) 1038 if err != nil { 1039 return err 1040 } 1041 hs.writeClientHash(channelIDMsgBytes) 1042 c.writeRecord(recordTypeHandshake, channelIDMsgBytes) 1043 } 1044 1045 // Send a client Finished message. 1046 finished := new(finishedMsg) 1047 finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret) 1048 if c.config.Bugs.BadFinished { 1049 finished.verifyData[0]++ 1050 } 1051 hs.writeClientHash(finished.marshal()) 1052 if c.config.Bugs.PartialClientFinishedWithClientHello { 1053 // The first byte has already been sent. 1054 c.writeRecord(recordTypeHandshake, finished.marshal()[1:]) 1055 } else if c.config.Bugs.InterleaveEarlyData { 1056 finishedBytes := finished.marshal() 1057 c.sendFakeEarlyData(4) 1058 c.writeRecord(recordTypeHandshake, finishedBytes[:1]) 1059 c.sendFakeEarlyData(4) 1060 c.writeRecord(recordTypeHandshake, finishedBytes[1:]) 1061 } else { 1062 c.writeRecord(recordTypeHandshake, finished.marshal()) 1063 } 1064 if c.config.Bugs.SendExtraFinished { 1065 c.writeRecord(recordTypeHandshake, finished.marshal()) 1066 } 1067 c.flushHandshake() 1068 1069 // Switch to application data keys. 1070 c.useOutTrafficSecret(c.wireVersion, hs.suite, clientTrafficSecret) 1071 c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel) 1072 for _, ticket := range deferredTickets { 1073 if err := c.processTLS13NewSessionTicket(ticket, hs.suite); err != nil { 1074 return err 1075 } 1076 } 1077 1078 return nil 1079} 1080 1081func (hs *clientHandshakeState) doFullHandshake() error { 1082 c := hs.c 1083 1084 var leaf *x509.Certificate 1085 if hs.suite.flags&suitePSK == 0 { 1086 msg, err := c.readHandshake() 1087 if err != nil { 1088 return err 1089 } 1090 1091 certMsg, ok := msg.(*certificateMsg) 1092 if !ok { 1093 c.sendAlert(alertUnexpectedMessage) 1094 return unexpectedMessageError(certMsg, msg) 1095 } 1096 hs.writeServerHash(certMsg.marshal()) 1097 1098 if err := hs.verifyCertificates(certMsg); err != nil { 1099 return err 1100 } 1101 leaf = c.peerCertificates[0] 1102 } 1103 1104 if hs.serverHello.extensions.ocspStapling { 1105 msg, err := c.readHandshake() 1106 if err != nil { 1107 return err 1108 } 1109 cs, ok := msg.(*certificateStatusMsg) 1110 if !ok { 1111 c.sendAlert(alertUnexpectedMessage) 1112 return unexpectedMessageError(cs, msg) 1113 } 1114 hs.writeServerHash(cs.marshal()) 1115 1116 if cs.statusType == statusTypeOCSP { 1117 c.ocspResponse = cs.response 1118 } 1119 } 1120 1121 msg, err := c.readHandshake() 1122 if err != nil { 1123 return err 1124 } 1125 1126 keyAgreement := hs.suite.ka(c.vers) 1127 1128 skx, ok := msg.(*serverKeyExchangeMsg) 1129 if ok { 1130 hs.writeServerHash(skx.marshal()) 1131 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx) 1132 if err != nil { 1133 c.sendAlert(alertUnexpectedMessage) 1134 return err 1135 } 1136 if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok { 1137 c.curveID = ecdhe.curveID 1138 } 1139 1140 c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm() 1141 1142 msg, err = c.readHandshake() 1143 if err != nil { 1144 return err 1145 } 1146 } 1147 1148 var chainToSend *Certificate 1149 var certRequested bool 1150 certReq, ok := msg.(*certificateRequestMsg) 1151 if ok { 1152 certRequested = true 1153 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences { 1154 certReq.signatureAlgorithms = c.config.signSignatureAlgorithms() 1155 } 1156 1157 hs.writeServerHash(certReq.marshal()) 1158 1159 chainToSend, err = selectClientCertificate(c, certReq) 1160 if err != nil { 1161 return err 1162 } 1163 1164 msg, err = c.readHandshake() 1165 if err != nil { 1166 return err 1167 } 1168 } 1169 1170 shd, ok := msg.(*serverHelloDoneMsg) 1171 if !ok { 1172 c.sendAlert(alertUnexpectedMessage) 1173 return unexpectedMessageError(shd, msg) 1174 } 1175 hs.writeServerHash(shd.marshal()) 1176 1177 // If the server requested a certificate then we have to send a 1178 // Certificate message in TLS, even if it's empty because we don't have 1179 // a certificate to send. In SSL 3.0, skip the message and send a 1180 // no_certificate warning alert. 1181 if certRequested { 1182 if c.vers == VersionSSL30 && chainToSend == nil { 1183 c.sendAlert(alertNoCertificate) 1184 } else if !c.config.Bugs.SkipClientCertificate { 1185 certMsg := new(certificateMsg) 1186 if chainToSend != nil { 1187 for _, certData := range chainToSend.Certificate { 1188 certMsg.certificates = append(certMsg.certificates, certificateEntry{ 1189 data: certData, 1190 }) 1191 } 1192 } 1193 hs.writeClientHash(certMsg.marshal()) 1194 c.writeRecord(recordTypeHandshake, certMsg.marshal()) 1195 } 1196 } 1197 1198 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf) 1199 if err != nil { 1200 c.sendAlert(alertInternalError) 1201 return err 1202 } 1203 if ckx != nil { 1204 if c.config.Bugs.EarlyChangeCipherSpec < 2 { 1205 hs.writeClientHash(ckx.marshal()) 1206 } 1207 c.writeRecord(recordTypeHandshake, ckx.marshal()) 1208 } 1209 1210 if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 { 1211 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash) 1212 c.extendedMasterSecret = true 1213 } else { 1214 if c.config.Bugs.RequireExtendedMasterSecret { 1215 return errors.New("tls: extended master secret required but not supported by peer") 1216 } 1217 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) 1218 } 1219 1220 if chainToSend != nil { 1221 certVerify := &certificateVerifyMsg{ 1222 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1223 } 1224 1225 // Determine the hash to sign. 1226 privKey := c.config.Certificates[0].PrivateKey 1227 1228 if certVerify.hasSignatureAlgorithm { 1229 certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms) 1230 if err != nil { 1231 c.sendAlert(alertInternalError) 1232 return err 1233 } 1234 } 1235 1236 if c.vers > VersionSSL30 { 1237 certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer) 1238 if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 { 1239 certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm 1240 } 1241 } else { 1242 // SSL 3.0's client certificate construction is 1243 // incompatible with signatureAlgorithm. 1244 rsaKey, ok := privKey.(*rsa.PrivateKey) 1245 if !ok { 1246 err = errors.New("unsupported signature type for client certificate") 1247 } else { 1248 digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret) 1249 if c.config.Bugs.InvalidSignature { 1250 digest[0] ^= 0x80 1251 } 1252 certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest) 1253 } 1254 } 1255 if err != nil { 1256 c.sendAlert(alertInternalError) 1257 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error()) 1258 } 1259 1260 if !c.config.Bugs.SkipCertificateVerify { 1261 hs.writeClientHash(certVerify.marshal()) 1262 c.writeRecord(recordTypeHandshake, certVerify.marshal()) 1263 } 1264 } 1265 // flushHandshake will be called in sendFinished. 1266 1267 hs.finishedHash.discardHandshakeBuffer() 1268 1269 return nil 1270} 1271 1272func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error { 1273 c := hs.c 1274 1275 if len(certMsg.certificates) == 0 { 1276 c.sendAlert(alertIllegalParameter) 1277 return errors.New("tls: no certificates sent") 1278 } 1279 1280 certs := make([]*x509.Certificate, len(certMsg.certificates)) 1281 for i, certEntry := range certMsg.certificates { 1282 cert, err := x509.ParseCertificate(certEntry.data) 1283 if err != nil { 1284 c.sendAlert(alertBadCertificate) 1285 return errors.New("tls: failed to parse certificate from server: " + err.Error()) 1286 } 1287 certs[i] = cert 1288 } 1289 1290 if !c.config.InsecureSkipVerify { 1291 opts := x509.VerifyOptions{ 1292 Roots: c.config.RootCAs, 1293 CurrentTime: c.config.time(), 1294 DNSName: c.config.ServerName, 1295 Intermediates: x509.NewCertPool(), 1296 } 1297 1298 for i, cert := range certs { 1299 if i == 0 { 1300 continue 1301 } 1302 opts.Intermediates.AddCert(cert) 1303 } 1304 var err error 1305 c.verifiedChains, err = certs[0].Verify(opts) 1306 if err != nil { 1307 c.sendAlert(alertBadCertificate) 1308 return err 1309 } 1310 } 1311 1312 publicKey := getCertificatePublicKey(certs[0]) 1313 switch publicKey.(type) { 1314 case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: 1315 break 1316 default: 1317 c.sendAlert(alertUnsupportedCertificate) 1318 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", publicKey) 1319 } 1320 1321 c.peerCertificates = certs 1322 return nil 1323} 1324 1325func (hs *clientHandshakeState) establishKeys() error { 1326 c := hs.c 1327 1328 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 1329 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers)) 1330 var clientCipher, serverCipher interface{} 1331 var clientHash, serverHash macFunction 1332 if hs.suite.cipher != nil { 1333 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) 1334 clientHash = hs.suite.mac(c.vers, clientMAC) 1335 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) 1336 serverHash = hs.suite.mac(c.vers, serverMAC) 1337 } else { 1338 clientCipher = hs.suite.aead(c.vers, clientKey, clientIV) 1339 serverCipher = hs.suite.aead(c.vers, serverKey, serverIV) 1340 } 1341 1342 c.in.prepareCipherSpec(c.wireVersion, serverCipher, serverHash) 1343 c.out.prepareCipherSpec(c.wireVersion, clientCipher, clientHash) 1344 return nil 1345} 1346 1347func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error { 1348 c := hs.c 1349 1350 if c.vers < VersionTLS13 { 1351 if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil { 1352 return errors.New("tls: renegotiation extension missing") 1353 } 1354 1355 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() { 1356 var expectedRenegInfo []byte 1357 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...) 1358 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...) 1359 if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) { 1360 c.sendAlert(alertHandshakeFailure) 1361 return fmt.Errorf("tls: renegotiation mismatch") 1362 } 1363 } 1364 } else if serverExtensions.secureRenegotiation != nil { 1365 return errors.New("tls: renegotiation info sent in TLS 1.3") 1366 } 1367 1368 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil { 1369 if serverExtensions.customExtension != *expected { 1370 return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension) 1371 } 1372 } 1373 1374 clientDidNPN := hs.hello.nextProtoNeg 1375 clientDidALPN := len(hs.hello.alpnProtocols) > 0 1376 serverHasNPN := serverExtensions.nextProtoNeg 1377 serverHasALPN := len(serverExtensions.alpnProtocol) > 0 1378 1379 if !clientDidNPN && serverHasNPN { 1380 c.sendAlert(alertHandshakeFailure) 1381 return errors.New("server advertised unrequested NPN extension") 1382 } 1383 1384 if !clientDidALPN && serverHasALPN { 1385 c.sendAlert(alertHandshakeFailure) 1386 return errors.New("server advertised unrequested ALPN extension") 1387 } 1388 1389 if serverHasNPN && serverHasALPN { 1390 c.sendAlert(alertHandshakeFailure) 1391 return errors.New("server advertised both NPN and ALPN extensions") 1392 } 1393 1394 if serverHasALPN { 1395 c.clientProtocol = serverExtensions.alpnProtocol 1396 c.clientProtocolFallback = false 1397 c.usedALPN = true 1398 } 1399 1400 if serverHasNPN && c.vers >= VersionTLS13 { 1401 c.sendAlert(alertHandshakeFailure) 1402 return errors.New("server advertised NPN over TLS 1.3") 1403 } 1404 1405 if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested { 1406 c.sendAlert(alertHandshakeFailure) 1407 return errors.New("server advertised unrequested Channel ID extension") 1408 } 1409 1410 if len(serverExtensions.tokenBindingParams) == 1 { 1411 found := false 1412 for _, p := range c.config.TokenBindingParams { 1413 if p == serverExtensions.tokenBindingParams[0] { 1414 c.tokenBindingParam = p 1415 found = true 1416 break 1417 } 1418 } 1419 if !found { 1420 return errors.New("tls: server advertised unsupported Token Binding key param") 1421 } 1422 if serverExtensions.tokenBindingVersion > c.config.TokenBindingVersion { 1423 return errors.New("tls: server's Token Binding version is too new") 1424 } 1425 if c.vers < VersionTLS13 { 1426 if !serverExtensions.extendedMasterSecret || serverExtensions.secureRenegotiation == nil { 1427 return errors.New("server sent Token Binding without EMS or RI") 1428 } 1429 } 1430 c.tokenBindingNegotiated = true 1431 } 1432 1433 if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 { 1434 return errors.New("tls: server advertised extended master secret over TLS 1.3") 1435 } 1436 1437 if serverExtensions.ticketSupported && c.vers >= VersionTLS13 { 1438 return errors.New("tls: server advertised ticket extension over TLS 1.3") 1439 } 1440 1441 if serverExtensions.ocspStapling && c.vers >= VersionTLS13 { 1442 return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3") 1443 } 1444 1445 if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling { 1446 return errors.New("tls: server advertised unrequested OCSP extension") 1447 } 1448 1449 if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 { 1450 return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3") 1451 } 1452 1453 if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps { 1454 return errors.New("tls: server advertised unrequested SCTs") 1455 } 1456 1457 if serverExtensions.srtpProtectionProfile != 0 { 1458 if serverExtensions.srtpMasterKeyIdentifier != "" { 1459 return errors.New("tls: server selected SRTP MKI value") 1460 } 1461 1462 found := false 1463 for _, p := range c.config.SRTPProtectionProfiles { 1464 if p == serverExtensions.srtpProtectionProfile { 1465 found = true 1466 break 1467 } 1468 } 1469 if !found { 1470 return errors.New("tls: server advertised unsupported SRTP profile") 1471 } 1472 1473 c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile 1474 } 1475 1476 if c.vers >= VersionTLS13 && c.didResume { 1477 if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData { 1478 c.sendAlert(alertHandshakeFailure) 1479 return errors.New("tls: server did not accept early data when expected") 1480 } 1481 1482 if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData { 1483 c.sendAlert(alertHandshakeFailure) 1484 return errors.New("tls: server accepted early data when not expected") 1485 } 1486 } 1487 1488 if len(serverExtensions.quicTransportParams) > 0 { 1489 if c.vers < VersionTLS13 { 1490 c.sendAlert(alertHandshakeFailure) 1491 return errors.New("tls: server sent QUIC transport params for TLS version less than 1.3") 1492 } 1493 c.quicTransportParams = serverExtensions.quicTransportParams 1494 } 1495 return nil 1496} 1497 1498func (hs *clientHandshakeState) serverResumedSession() bool { 1499 // If the server responded with the same sessionId then it means the 1500 // sessionTicket is being used to resume a TLS session. 1501 // 1502 // Note that, if hs.hello.sessionId is a non-nil empty array, this will 1503 // accept an empty session ID from the server as resumption. See 1504 // EmptyTicketSessionID. 1505 return hs.session != nil && hs.hello.sessionId != nil && 1506 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) 1507} 1508 1509func (hs *clientHandshakeState) processServerHello() (bool, error) { 1510 c := hs.c 1511 1512 if hs.serverResumedSession() { 1513 // For test purposes, assert that the server never accepts the 1514 // resumption offer on renegotiation. 1515 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego { 1516 return false, errors.New("tls: server resumed session on renegotiation") 1517 } 1518 1519 if hs.serverHello.extensions.sctList != nil { 1520 return false, errors.New("tls: server sent SCT extension on session resumption") 1521 } 1522 1523 if hs.serverHello.extensions.ocspStapling { 1524 return false, errors.New("tls: server sent OCSP extension on session resumption") 1525 } 1526 1527 // Restore masterSecret and peerCerts from previous state 1528 hs.masterSecret = hs.session.masterSecret 1529 c.peerCertificates = hs.session.serverCertificates 1530 c.extendedMasterSecret = hs.session.extendedMasterSecret 1531 c.sctList = hs.session.sctList 1532 c.ocspResponse = hs.session.ocspResponse 1533 hs.finishedHash.discardHandshakeBuffer() 1534 return true, nil 1535 } 1536 1537 if hs.serverHello.extensions.sctList != nil { 1538 c.sctList = hs.serverHello.extensions.sctList 1539 } 1540 1541 return false, nil 1542} 1543 1544func (hs *clientHandshakeState) readFinished(out []byte) error { 1545 c := hs.c 1546 1547 c.readRecord(recordTypeChangeCipherSpec) 1548 if err := c.in.error(); err != nil { 1549 return err 1550 } 1551 1552 msg, err := c.readHandshake() 1553 if err != nil { 1554 return err 1555 } 1556 serverFinished, ok := msg.(*finishedMsg) 1557 if !ok { 1558 c.sendAlert(alertUnexpectedMessage) 1559 return unexpectedMessageError(serverFinished, msg) 1560 } 1561 1562 if c.config.Bugs.EarlyChangeCipherSpec == 0 { 1563 verify := hs.finishedHash.serverSum(hs.masterSecret) 1564 if len(verify) != len(serverFinished.verifyData) || 1565 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { 1566 c.sendAlert(alertHandshakeFailure) 1567 return errors.New("tls: server's Finished message was incorrect") 1568 } 1569 } 1570 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...) 1571 copy(out, serverFinished.verifyData) 1572 hs.writeServerHash(serverFinished.marshal()) 1573 return nil 1574} 1575 1576func (hs *clientHandshakeState) readSessionTicket() error { 1577 c := hs.c 1578 1579 // Create a session with no server identifier. Either a 1580 // session ID or session ticket will be attached. 1581 session := &ClientSessionState{ 1582 vers: c.vers, 1583 wireVersion: c.wireVersion, 1584 cipherSuite: hs.suite.id, 1585 masterSecret: hs.masterSecret, 1586 handshakeHash: hs.finishedHash.Sum(), 1587 serverCertificates: c.peerCertificates, 1588 sctList: c.sctList, 1589 ocspResponse: c.ocspResponse, 1590 ticketExpiration: c.config.time().Add(time.Duration(7 * 24 * time.Hour)), 1591 } 1592 1593 if !hs.serverHello.extensions.ticketSupported { 1594 if c.config.Bugs.ExpectNewTicket { 1595 return errors.New("tls: expected new ticket") 1596 } 1597 if hs.session == nil && len(hs.serverHello.sessionId) > 0 { 1598 session.sessionId = hs.serverHello.sessionId 1599 hs.session = session 1600 } 1601 return nil 1602 } 1603 1604 if c.vers == VersionSSL30 { 1605 return errors.New("tls: negotiated session tickets in SSL 3.0") 1606 } 1607 1608 msg, err := c.readHandshake() 1609 if err != nil { 1610 return err 1611 } 1612 sessionTicketMsg, ok := msg.(*newSessionTicketMsg) 1613 if !ok { 1614 c.sendAlert(alertUnexpectedMessage) 1615 return unexpectedMessageError(sessionTicketMsg, msg) 1616 } 1617 1618 session.sessionTicket = sessionTicketMsg.ticket 1619 hs.session = session 1620 1621 hs.writeServerHash(sessionTicketMsg.marshal()) 1622 1623 return nil 1624} 1625 1626func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error { 1627 c := hs.c 1628 1629 var postCCSMsgs [][]byte 1630 seqno := hs.c.sendHandshakeSeq 1631 if hs.serverHello.extensions.nextProtoNeg { 1632 nextProto := new(nextProtoMsg) 1633 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos) 1634 nextProto.proto = proto 1635 c.clientProtocol = proto 1636 c.clientProtocolFallback = fallback 1637 1638 nextProtoBytes := nextProto.marshal() 1639 hs.writeHash(nextProtoBytes, seqno) 1640 seqno++ 1641 postCCSMsgs = append(postCCSMsgs, nextProtoBytes) 1642 } 1643 1644 if hs.serverHello.extensions.channelIDRequested { 1645 var resumeHash []byte 1646 if isResume { 1647 resumeHash = hs.session.handshakeHash 1648 } 1649 channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash)) 1650 if err != nil { 1651 return err 1652 } 1653 hs.writeHash(channelIDMsgBytes, seqno) 1654 seqno++ 1655 postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes) 1656 } 1657 1658 finished := new(finishedMsg) 1659 if c.config.Bugs.EarlyChangeCipherSpec == 2 { 1660 finished.verifyData = hs.finishedHash.clientSum(nil) 1661 } else { 1662 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) 1663 } 1664 copy(out, finished.verifyData) 1665 if c.config.Bugs.BadFinished { 1666 finished.verifyData[0]++ 1667 } 1668 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...) 1669 hs.finishedBytes = finished.marshal() 1670 hs.writeHash(hs.finishedBytes, seqno) 1671 postCCSMsgs = append(postCCSMsgs, hs.finishedBytes) 1672 1673 if c.config.Bugs.FragmentAcrossChangeCipherSpec { 1674 c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5]) 1675 postCCSMsgs[0] = postCCSMsgs[0][5:] 1676 } else if c.config.Bugs.SendUnencryptedFinished { 1677 c.writeRecord(recordTypeHandshake, postCCSMsgs[0]) 1678 postCCSMsgs = postCCSMsgs[1:] 1679 } 1680 1681 if !c.config.Bugs.SkipChangeCipherSpec && 1682 c.config.Bugs.EarlyChangeCipherSpec == 0 { 1683 ccs := []byte{1} 1684 if c.config.Bugs.BadChangeCipherSpec != nil { 1685 ccs = c.config.Bugs.BadChangeCipherSpec 1686 } 1687 c.writeRecord(recordTypeChangeCipherSpec, ccs) 1688 } 1689 1690 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil { 1691 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec) 1692 } 1693 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 { 1694 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec) 1695 return errors.New("tls: simulating post-CCS alert") 1696 } 1697 1698 if !c.config.Bugs.SkipFinished { 1699 for _, msg := range postCCSMsgs { 1700 c.writeRecord(recordTypeHandshake, msg) 1701 } 1702 1703 if c.config.Bugs.SendExtraFinished { 1704 c.writeRecord(recordTypeHandshake, finished.marshal()) 1705 } 1706 } 1707 1708 if !isResume || !c.config.Bugs.PackAppDataWithHandshake { 1709 c.flushHandshake() 1710 } 1711 return nil 1712} 1713 1714func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) { 1715 c := hs.c 1716 channelIDMsg := new(channelIDMsg) 1717 if c.config.ChannelID.Curve != elliptic.P256() { 1718 return nil, fmt.Errorf("tls: Channel ID is not on P-256.") 1719 } 1720 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash) 1721 if err != nil { 1722 return nil, err 1723 } 1724 channelID := make([]byte, 128) 1725 writeIntPadded(channelID[0:32], c.config.ChannelID.X) 1726 writeIntPadded(channelID[32:64], c.config.ChannelID.Y) 1727 writeIntPadded(channelID[64:96], r) 1728 writeIntPadded(channelID[96:128], s) 1729 if c.config.Bugs.InvalidChannelIDSignature { 1730 channelID[64] ^= 1 1731 } 1732 channelIDMsg.channelID = channelID 1733 1734 c.channelID = &c.config.ChannelID.PublicKey 1735 1736 return channelIDMsg.marshal(), nil 1737} 1738 1739func (hs *clientHandshakeState) writeClientHash(msg []byte) { 1740 // writeClientHash is called before writeRecord. 1741 hs.writeHash(msg, hs.c.sendHandshakeSeq) 1742} 1743 1744func (hs *clientHandshakeState) writeServerHash(msg []byte) { 1745 // writeServerHash is called after readHandshake. 1746 hs.writeHash(msg, hs.c.recvHandshakeSeq-1) 1747} 1748 1749func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) { 1750 if hs.c.isDTLS { 1751 // This is somewhat hacky. DTLS hashes a slightly different format. 1752 // First, the TLS header. 1753 hs.finishedHash.Write(msg[:4]) 1754 // Then the sequence number and reassembled fragment offset (always 0). 1755 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0}) 1756 // Then the reassembled fragment (always equal to the message length). 1757 hs.finishedHash.Write(msg[1:4]) 1758 // And then the message body. 1759 hs.finishedHash.Write(msg[4:]) 1760 } else { 1761 hs.finishedHash.Write(msg) 1762 } 1763} 1764 1765// selectClientCertificate selects a certificate for use with the given 1766// certificate, or none if none match. It may return a particular certificate or 1767// nil on success, or an error on internal error. 1768func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) { 1769 if len(c.config.Certificates) == 0 { 1770 return nil, nil 1771 } 1772 1773 // The test is assumed to have configured the certificate it meant to 1774 // send. 1775 if len(c.config.Certificates) > 1 { 1776 return nil, errors.New("tls: multiple certificates configured") 1777 } 1778 1779 return &c.config.Certificates[0], nil 1780} 1781 1782// clientSessionCacheKey returns a key used to cache sessionTickets that could 1783// be used to resume previously negotiated TLS sessions with a server. 1784func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { 1785 if len(config.ServerName) > 0 { 1786 return config.ServerName 1787 } 1788 return serverAddr.String() 1789} 1790 1791// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol 1792// given list of possible protocols and a list of the preference order. The 1793// first list must not be empty. It returns the resulting protocol and flag 1794// indicating if the fallback case was reached. 1795func mutualProtocol(protos, preferenceProtos []string) (string, bool) { 1796 for _, s := range preferenceProtos { 1797 for _, c := range protos { 1798 if s == c { 1799 return s, false 1800 } 1801 } 1802 } 1803 1804 return protos[0], true 1805} 1806 1807// writeIntPadded writes x into b, padded up with leading zeros as 1808// needed. 1809func writeIntPadded(b []byte, x *big.Int) { 1810 for i := range b { 1811 b[i] = 0 1812 } 1813 xb := x.Bytes() 1814 copy(b[len(b)-len(xb):], xb) 1815} 1816 1817func generatePSKBinders(version uint16, hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, firstClientHello, helloRetryRequest []byte, config *Config) { 1818 if config.Bugs.SendNoPSKBinder { 1819 return 1820 } 1821 1822 binderLen := pskCipherSuite.hash().Size() 1823 if config.Bugs.SendShortPSKBinder { 1824 binderLen-- 1825 } 1826 1827 numBinders := 1 1828 if config.Bugs.SendExtraPSKBinder { 1829 numBinders++ 1830 } 1831 1832 // Fill hello.pskBinders with appropriate length arrays of zeros so the 1833 // length prefixes are correct when computing the binder over the truncated 1834 // ClientHello message. 1835 hello.pskBinders = make([][]byte, numBinders) 1836 for i := range hello.pskBinders { 1837 hello.pskBinders[i] = make([]byte, binderLen) 1838 } 1839 1840 helloBytes := hello.marshal() 1841 binderSize := len(hello.pskBinders)*(binderLen+1) + 2 1842 truncatedHello := helloBytes[:len(helloBytes)-binderSize] 1843 binder := computePSKBinder(psk, version, resumptionPSKBinderLabel, pskCipherSuite, firstClientHello, helloRetryRequest, truncatedHello) 1844 if config.Bugs.SendShortPSKBinder { 1845 binder = binder[:binderLen] 1846 } 1847 if config.Bugs.SendInvalidPSKBinder { 1848 binder[0] ^= 1 1849 } 1850 1851 for i := range hello.pskBinders { 1852 hello.pskBinders[i] = binder 1853 } 1854 1855 hello.raw = nil 1856} 1857