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/ecdsa" 10 "crypto/elliptic" 11 "crypto/rsa" 12 "crypto/subtle" 13 "crypto/x509" 14 "encoding/asn1" 15 "errors" 16 "fmt" 17 "io" 18 "math/big" 19 "net" 20 "strconv" 21) 22 23type clientHandshakeState struct { 24 c *Conn 25 serverHello *serverHelloMsg 26 hello *clientHelloMsg 27 suite *cipherSuite 28 finishedHash finishedHash 29 masterSecret []byte 30 session *ClientSessionState 31 finishedBytes []byte 32} 33 34func (c *Conn) clientHandshake() error { 35 if c.config == nil { 36 c.config = defaultConfig() 37 } 38 39 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify { 40 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") 41 } 42 43 c.sendHandshakeSeq = 0 44 c.recvHandshakeSeq = 0 45 46 nextProtosLength := 0 47 for _, proto := range c.config.NextProtos { 48 if l := len(proto); l > 255 { 49 return errors.New("tls: invalid NextProtos value") 50 } else { 51 nextProtosLength += 1 + l 52 } 53 } 54 if nextProtosLength > 0xffff { 55 return errors.New("tls: NextProtos values too large") 56 } 57 58 hello := &clientHelloMsg{ 59 isDTLS: c.isDTLS, 60 vers: c.config.maxVersion(), 61 compressionMethods: []uint8{compressionNone}, 62 random: make([]byte, 32), 63 ocspStapling: true, 64 sctListSupported: true, 65 serverName: c.config.ServerName, 66 supportedCurves: c.config.curvePreferences(), 67 supportedPoints: []uint8{pointFormatUncompressed}, 68 nextProtoNeg: len(c.config.NextProtos) > 0, 69 secureRenegotiation: []byte{}, 70 alpnProtocols: c.config.NextProtos, 71 duplicateExtension: c.config.Bugs.DuplicateExtension, 72 channelIDSupported: c.config.ChannelID != nil, 73 npnLast: c.config.Bugs.SwapNPNAndALPN, 74 extendedMasterSecret: c.config.maxVersion() >= VersionTLS10, 75 srtpProtectionProfiles: c.config.SRTPProtectionProfiles, 76 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer, 77 customExtension: c.config.Bugs.CustomExtension, 78 } 79 80 if c.config.Bugs.SendClientVersion != 0 { 81 hello.vers = c.config.Bugs.SendClientVersion 82 } 83 84 if c.config.Bugs.NoExtendedMasterSecret { 85 hello.extendedMasterSecret = false 86 } 87 88 if c.config.Bugs.NoSupportedCurves { 89 hello.supportedCurves = nil 90 } 91 92 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo { 93 if c.config.Bugs.BadRenegotiationInfo { 94 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...) 95 hello.secureRenegotiation[0] ^= 0x80 96 } else { 97 hello.secureRenegotiation = c.clientVerify 98 } 99 } 100 101 if c.noRenegotiationInfo() { 102 hello.secureRenegotiation = nil 103 } 104 105 possibleCipherSuites := c.config.cipherSuites() 106 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) 107 108NextCipherSuite: 109 for _, suiteId := range possibleCipherSuites { 110 for _, suite := range cipherSuites { 111 if suite.id != suiteId { 112 continue 113 } 114 // Don't advertise TLS 1.2-only cipher suites unless 115 // we're attempting TLS 1.2. 116 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { 117 continue 118 } 119 // Don't advertise non-DTLS cipher suites on DTLS. 120 if c.isDTLS && suite.flags&suiteNoDTLS != 0 && !c.config.Bugs.EnableAllCiphersInDTLS { 121 continue 122 } 123 hello.cipherSuites = append(hello.cipherSuites, suiteId) 124 continue NextCipherSuite 125 } 126 } 127 128 if c.config.Bugs.SendRenegotiationSCSV { 129 hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV) 130 } 131 132 if c.config.Bugs.SendFallbackSCSV { 133 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV) 134 } 135 136 _, err := io.ReadFull(c.config.rand(), hello.random) 137 if err != nil { 138 c.sendAlert(alertInternalError) 139 return errors.New("tls: short read from Rand: " + err.Error()) 140 } 141 142 if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAndHashes { 143 hello.signatureAndHashes = c.config.signatureAndHashesForClient() 144 } 145 146 var session *ClientSessionState 147 var cacheKey string 148 sessionCache := c.config.ClientSessionCache 149 150 if sessionCache != nil { 151 hello.ticketSupported = !c.config.SessionTicketsDisabled 152 153 // Try to resume a previously negotiated TLS session, if 154 // available. 155 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 156 candidateSession, ok := sessionCache.Get(cacheKey) 157 if ok { 158 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil 159 160 // Check that the ciphersuite/version used for the 161 // previous session are still valid. 162 cipherSuiteOk := false 163 for _, id := range hello.cipherSuites { 164 if id == candidateSession.cipherSuite { 165 cipherSuiteOk = true 166 break 167 } 168 } 169 170 versOk := candidateSession.vers >= c.config.minVersion() && 171 candidateSession.vers <= c.config.maxVersion() 172 if ticketOk && versOk && cipherSuiteOk { 173 session = candidateSession 174 } 175 } 176 } 177 178 if session != nil { 179 if session.sessionTicket != nil { 180 hello.sessionTicket = session.sessionTicket 181 if c.config.Bugs.CorruptTicket { 182 hello.sessionTicket = make([]byte, len(session.sessionTicket)) 183 copy(hello.sessionTicket, session.sessionTicket) 184 if len(hello.sessionTicket) > 0 { 185 offset := 40 186 if offset > len(hello.sessionTicket) { 187 offset = len(hello.sessionTicket) - 1 188 } 189 hello.sessionTicket[offset] ^= 0x40 190 } 191 } 192 // A random session ID is used to detect when the 193 // server accepted the ticket and is resuming a session 194 // (see RFC 5077). 195 sessionIdLen := 16 196 if c.config.Bugs.OversizedSessionId { 197 sessionIdLen = 33 198 } 199 hello.sessionId = make([]byte, sessionIdLen) 200 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { 201 c.sendAlert(alertInternalError) 202 return errors.New("tls: short read from Rand: " + err.Error()) 203 } 204 } else { 205 hello.sessionId = session.sessionId 206 } 207 } 208 209 var helloBytes []byte 210 if c.config.Bugs.SendV2ClientHello { 211 // Test that the peer left-pads random. 212 hello.random[0] = 0 213 v2Hello := &v2ClientHelloMsg{ 214 vers: hello.vers, 215 cipherSuites: hello.cipherSuites, 216 // No session resumption for V2ClientHello. 217 sessionId: nil, 218 challenge: hello.random[1:], 219 } 220 helloBytes = v2Hello.marshal() 221 c.writeV2Record(helloBytes) 222 } else { 223 helloBytes = hello.marshal() 224 c.writeRecord(recordTypeHandshake, helloBytes) 225 } 226 c.dtlsFlushHandshake() 227 228 if err := c.simulatePacketLoss(nil); err != nil { 229 return err 230 } 231 msg, err := c.readHandshake() 232 if err != nil { 233 return err 234 } 235 236 if c.isDTLS { 237 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg) 238 if ok { 239 if helloVerifyRequest.vers != VersionTLS10 { 240 // Per RFC 6347, the version field in 241 // HelloVerifyRequest SHOULD be always DTLS 242 // 1.0. Enforce this for testing purposes. 243 return errors.New("dtls: bad HelloVerifyRequest version") 244 } 245 246 hello.raw = nil 247 hello.cookie = helloVerifyRequest.cookie 248 helloBytes = hello.marshal() 249 c.writeRecord(recordTypeHandshake, helloBytes) 250 c.dtlsFlushHandshake() 251 252 if err := c.simulatePacketLoss(nil); err != nil { 253 return err 254 } 255 msg, err = c.readHandshake() 256 if err != nil { 257 return err 258 } 259 } 260 } 261 262 serverHello, ok := msg.(*serverHelloMsg) 263 if !ok { 264 c.sendAlert(alertUnexpectedMessage) 265 return unexpectedMessageError(serverHello, msg) 266 } 267 268 c.vers, ok = c.config.mutualVersion(serverHello.vers) 269 if !ok { 270 c.sendAlert(alertProtocolVersion) 271 return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers) 272 } 273 c.haveVers = true 274 275 suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite) 276 if suite == nil { 277 c.sendAlert(alertHandshakeFailure) 278 return fmt.Errorf("tls: server selected an unsupported cipher suite") 279 } 280 281 if c.config.Bugs.RequireRenegotiationInfo && serverHello.secureRenegotiation == nil { 282 return errors.New("tls: renegotiation extension missing") 283 } 284 285 if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() { 286 var expectedRenegInfo []byte 287 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...) 288 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...) 289 if !bytes.Equal(serverHello.secureRenegotiation, expectedRenegInfo) { 290 c.sendAlert(alertHandshakeFailure) 291 return fmt.Errorf("tls: renegotiation mismatch") 292 } 293 } 294 295 if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil { 296 if serverHello.customExtension != *expected { 297 return fmt.Errorf("tls: bad custom extension contents %q", serverHello.customExtension) 298 } 299 } 300 301 hs := &clientHandshakeState{ 302 c: c, 303 serverHello: serverHello, 304 hello: hello, 305 suite: suite, 306 finishedHash: newFinishedHash(c.vers, suite), 307 session: session, 308 } 309 310 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1) 311 hs.writeServerHash(hs.serverHello.marshal()) 312 313 if c.config.Bugs.EarlyChangeCipherSpec > 0 { 314 hs.establishKeys() 315 c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 316 } 317 318 isResume, err := hs.processServerHello() 319 if err != nil { 320 return err 321 } 322 323 if isResume { 324 if c.config.Bugs.EarlyChangeCipherSpec == 0 { 325 if err := hs.establishKeys(); err != nil { 326 return err 327 } 328 } 329 if err := hs.readSessionTicket(); err != nil { 330 return err 331 } 332 if err := hs.readFinished(c.firstFinished[:]); err != nil { 333 return err 334 } 335 if err := hs.sendFinished(nil, isResume); err != nil { 336 return err 337 } 338 } else { 339 if err := hs.doFullHandshake(); err != nil { 340 return err 341 } 342 if err := hs.establishKeys(); err != nil { 343 return err 344 } 345 if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil { 346 return err 347 } 348 // Most retransmits are triggered by a timeout, but the final 349 // leg of the handshake is retransmited upon re-receiving a 350 // Finished. 351 if err := c.simulatePacketLoss(func() { 352 c.writeRecord(recordTypeHandshake, hs.finishedBytes) 353 c.dtlsFlushHandshake() 354 }); err != nil { 355 return err 356 } 357 if err := hs.readSessionTicket(); err != nil { 358 return err 359 } 360 if err := hs.readFinished(nil); err != nil { 361 return err 362 } 363 } 364 365 if sessionCache != nil && hs.session != nil && session != hs.session { 366 sessionCache.Put(cacheKey, hs.session) 367 } 368 369 c.didResume = isResume 370 c.handshakeComplete = true 371 c.cipherSuite = suite 372 copy(c.clientRandom[:], hs.hello.random) 373 copy(c.serverRandom[:], hs.serverHello.random) 374 copy(c.masterSecret[:], hs.masterSecret) 375 376 return nil 377} 378 379func (hs *clientHandshakeState) doFullHandshake() error { 380 c := hs.c 381 382 var leaf *x509.Certificate 383 if hs.suite.flags&suitePSK == 0 { 384 msg, err := c.readHandshake() 385 if err != nil { 386 return err 387 } 388 389 certMsg, ok := msg.(*certificateMsg) 390 if !ok || len(certMsg.certificates) == 0 { 391 c.sendAlert(alertUnexpectedMessage) 392 return unexpectedMessageError(certMsg, msg) 393 } 394 hs.writeServerHash(certMsg.marshal()) 395 396 certs := make([]*x509.Certificate, len(certMsg.certificates)) 397 for i, asn1Data := range certMsg.certificates { 398 cert, err := x509.ParseCertificate(asn1Data) 399 if err != nil { 400 c.sendAlert(alertBadCertificate) 401 return errors.New("tls: failed to parse certificate from server: " + err.Error()) 402 } 403 certs[i] = cert 404 } 405 leaf = certs[0] 406 407 if !c.config.InsecureSkipVerify { 408 opts := x509.VerifyOptions{ 409 Roots: c.config.RootCAs, 410 CurrentTime: c.config.time(), 411 DNSName: c.config.ServerName, 412 Intermediates: x509.NewCertPool(), 413 } 414 415 for i, cert := range certs { 416 if i == 0 { 417 continue 418 } 419 opts.Intermediates.AddCert(cert) 420 } 421 c.verifiedChains, err = leaf.Verify(opts) 422 if err != nil { 423 c.sendAlert(alertBadCertificate) 424 return err 425 } 426 } 427 428 switch leaf.PublicKey.(type) { 429 case *rsa.PublicKey, *ecdsa.PublicKey: 430 break 431 default: 432 c.sendAlert(alertUnsupportedCertificate) 433 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leaf.PublicKey) 434 } 435 436 c.peerCertificates = certs 437 } 438 439 if hs.serverHello.ocspStapling { 440 msg, err := c.readHandshake() 441 if err != nil { 442 return err 443 } 444 cs, ok := msg.(*certificateStatusMsg) 445 if !ok { 446 c.sendAlert(alertUnexpectedMessage) 447 return unexpectedMessageError(cs, msg) 448 } 449 hs.writeServerHash(cs.marshal()) 450 451 if cs.statusType == statusTypeOCSP { 452 c.ocspResponse = cs.response 453 } 454 } 455 456 msg, err := c.readHandshake() 457 if err != nil { 458 return err 459 } 460 461 keyAgreement := hs.suite.ka(c.vers) 462 463 skx, ok := msg.(*serverKeyExchangeMsg) 464 if ok { 465 hs.writeServerHash(skx.marshal()) 466 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx) 467 if err != nil { 468 c.sendAlert(alertUnexpectedMessage) 469 return err 470 } 471 472 msg, err = c.readHandshake() 473 if err != nil { 474 return err 475 } 476 } 477 478 var chainToSend *Certificate 479 var certRequested bool 480 certReq, ok := msg.(*certificateRequestMsg) 481 if ok { 482 certRequested = true 483 484 // RFC 4346 on the certificateAuthorities field: 485 // A list of the distinguished names of acceptable certificate 486 // authorities. These distinguished names may specify a desired 487 // distinguished name for a root CA or for a subordinate CA; 488 // thus, this message can be used to describe both known roots 489 // and a desired authorization space. If the 490 // certificate_authorities list is empty then the client MAY 491 // send any certificate of the appropriate 492 // ClientCertificateType, unless there is some external 493 // arrangement to the contrary. 494 495 hs.writeServerHash(certReq.marshal()) 496 497 var rsaAvail, ecdsaAvail bool 498 for _, certType := range certReq.certificateTypes { 499 switch certType { 500 case CertTypeRSASign: 501 rsaAvail = true 502 case CertTypeECDSASign: 503 ecdsaAvail = true 504 } 505 } 506 507 // We need to search our list of client certs for one 508 // where SignatureAlgorithm is RSA and the Issuer is in 509 // certReq.certificateAuthorities 510 findCert: 511 for i, chain := range c.config.Certificates { 512 if !rsaAvail && !ecdsaAvail { 513 continue 514 } 515 516 for j, cert := range chain.Certificate { 517 x509Cert := chain.Leaf 518 // parse the certificate if this isn't the leaf 519 // node, or if chain.Leaf was nil 520 if j != 0 || x509Cert == nil { 521 if x509Cert, err = x509.ParseCertificate(cert); err != nil { 522 c.sendAlert(alertInternalError) 523 return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error()) 524 } 525 } 526 527 switch { 528 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA: 529 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA: 530 default: 531 continue findCert 532 } 533 534 if len(certReq.certificateAuthorities) == 0 { 535 // they gave us an empty list, so just take the 536 // first RSA cert from c.config.Certificates 537 chainToSend = &chain 538 break findCert 539 } 540 541 for _, ca := range certReq.certificateAuthorities { 542 if bytes.Equal(x509Cert.RawIssuer, ca) { 543 chainToSend = &chain 544 break findCert 545 } 546 } 547 } 548 } 549 550 msg, err = c.readHandshake() 551 if err != nil { 552 return err 553 } 554 } 555 556 shd, ok := msg.(*serverHelloDoneMsg) 557 if !ok { 558 c.sendAlert(alertUnexpectedMessage) 559 return unexpectedMessageError(shd, msg) 560 } 561 hs.writeServerHash(shd.marshal()) 562 563 // If the server requested a certificate then we have to send a 564 // Certificate message, even if it's empty because we don't have a 565 // certificate to send. 566 if certRequested { 567 certMsg := new(certificateMsg) 568 if chainToSend != nil { 569 certMsg.certificates = chainToSend.Certificate 570 } 571 hs.writeClientHash(certMsg.marshal()) 572 c.writeRecord(recordTypeHandshake, certMsg.marshal()) 573 } 574 575 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf) 576 if err != nil { 577 c.sendAlert(alertInternalError) 578 return err 579 } 580 if ckx != nil { 581 if c.config.Bugs.EarlyChangeCipherSpec < 2 { 582 hs.writeClientHash(ckx.marshal()) 583 } 584 c.writeRecord(recordTypeHandshake, ckx.marshal()) 585 } 586 587 if hs.serverHello.extendedMasterSecret && c.vers >= VersionTLS10 { 588 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash) 589 c.extendedMasterSecret = true 590 } else { 591 if c.config.Bugs.RequireExtendedMasterSecret { 592 return errors.New("tls: extended master secret required but not supported by peer") 593 } 594 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) 595 } 596 597 if chainToSend != nil { 598 var signed []byte 599 certVerify := &certificateVerifyMsg{ 600 hasSignatureAndHash: c.vers >= VersionTLS12, 601 } 602 603 // Determine the hash to sign. 604 var signatureType uint8 605 switch c.config.Certificates[0].PrivateKey.(type) { 606 case *ecdsa.PrivateKey: 607 signatureType = signatureECDSA 608 case *rsa.PrivateKey: 609 signatureType = signatureRSA 610 default: 611 c.sendAlert(alertInternalError) 612 return errors.New("unknown private key type") 613 } 614 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences { 615 certReq.signatureAndHashes = c.config.signatureAndHashesForClient() 616 } 617 certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, c.config.signatureAndHashesForClient(), signatureType) 618 if err != nil { 619 c.sendAlert(alertInternalError) 620 return err 621 } 622 digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret) 623 if err != nil { 624 c.sendAlert(alertInternalError) 625 return err 626 } 627 if c.config.Bugs.InvalidCertVerifySignature { 628 digest[0] ^= 0x80 629 } 630 631 switch key := c.config.Certificates[0].PrivateKey.(type) { 632 case *ecdsa.PrivateKey: 633 var r, s *big.Int 634 r, s, err = ecdsa.Sign(c.config.rand(), key, digest) 635 if err == nil { 636 signed, err = asn1.Marshal(ecdsaSignature{r, s}) 637 } 638 case *rsa.PrivateKey: 639 signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest) 640 default: 641 err = errors.New("unknown private key type") 642 } 643 if err != nil { 644 c.sendAlert(alertInternalError) 645 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error()) 646 } 647 certVerify.signature = signed 648 649 hs.writeClientHash(certVerify.marshal()) 650 c.writeRecord(recordTypeHandshake, certVerify.marshal()) 651 } 652 c.dtlsFlushHandshake() 653 654 hs.finishedHash.discardHandshakeBuffer() 655 656 return nil 657} 658 659func (hs *clientHandshakeState) establishKeys() error { 660 c := hs.c 661 662 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 663 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) 664 var clientCipher, serverCipher interface{} 665 var clientHash, serverHash macFunction 666 if hs.suite.cipher != nil { 667 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) 668 clientHash = hs.suite.mac(c.vers, clientMAC) 669 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) 670 serverHash = hs.suite.mac(c.vers, serverMAC) 671 } else { 672 clientCipher = hs.suite.aead(clientKey, clientIV) 673 serverCipher = hs.suite.aead(serverKey, serverIV) 674 } 675 676 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) 677 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) 678 return nil 679} 680 681func (hs *clientHandshakeState) serverResumedSession() bool { 682 // If the server responded with the same sessionId then it means the 683 // sessionTicket is being used to resume a TLS session. 684 return hs.session != nil && hs.hello.sessionId != nil && 685 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) 686} 687 688func (hs *clientHandshakeState) processServerHello() (bool, error) { 689 c := hs.c 690 691 if hs.serverHello.compressionMethod != compressionNone { 692 c.sendAlert(alertUnexpectedMessage) 693 return false, errors.New("tls: server selected unsupported compression format") 694 } 695 696 clientDidNPN := hs.hello.nextProtoNeg 697 clientDidALPN := len(hs.hello.alpnProtocols) > 0 698 serverHasNPN := hs.serverHello.nextProtoNeg 699 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0 700 701 if !clientDidNPN && serverHasNPN { 702 c.sendAlert(alertHandshakeFailure) 703 return false, errors.New("server advertised unrequested NPN extension") 704 } 705 706 if !clientDidALPN && serverHasALPN { 707 c.sendAlert(alertHandshakeFailure) 708 return false, errors.New("server advertised unrequested ALPN extension") 709 } 710 711 if serverHasNPN && serverHasALPN { 712 c.sendAlert(alertHandshakeFailure) 713 return false, errors.New("server advertised both NPN and ALPN extensions") 714 } 715 716 if serverHasALPN { 717 c.clientProtocol = hs.serverHello.alpnProtocol 718 c.clientProtocolFallback = false 719 c.usedALPN = true 720 } 721 722 if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested { 723 c.sendAlert(alertHandshakeFailure) 724 return false, errors.New("server advertised unrequested Channel ID extension") 725 } 726 727 if hs.serverHello.srtpProtectionProfile != 0 { 728 if hs.serverHello.srtpMasterKeyIdentifier != "" { 729 return false, errors.New("tls: server selected SRTP MKI value") 730 } 731 732 found := false 733 for _, p := range c.config.SRTPProtectionProfiles { 734 if p == hs.serverHello.srtpProtectionProfile { 735 found = true 736 break 737 } 738 } 739 if !found { 740 return false, errors.New("tls: server advertised unsupported SRTP profile") 741 } 742 743 c.srtpProtectionProfile = hs.serverHello.srtpProtectionProfile 744 } 745 746 if hs.serverResumedSession() { 747 // For test purposes, assert that the server never accepts the 748 // resumption offer on renegotiation. 749 if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego { 750 return false, errors.New("tls: server resumed session on renegotiation") 751 } 752 753 if hs.serverHello.sctList != nil { 754 return false, errors.New("tls: server sent SCT extension on session resumption") 755 } 756 757 if hs.serverHello.ocspStapling { 758 return false, errors.New("tls: server sent OCSP extension on session resumption") 759 } 760 761 // Restore masterSecret and peerCerts from previous state 762 hs.masterSecret = hs.session.masterSecret 763 c.peerCertificates = hs.session.serverCertificates 764 c.extendedMasterSecret = hs.session.extendedMasterSecret 765 c.sctList = hs.session.sctList 766 c.ocspResponse = hs.session.ocspResponse 767 hs.finishedHash.discardHandshakeBuffer() 768 return true, nil 769 } 770 771 if hs.serverHello.sctList != nil { 772 c.sctList = hs.serverHello.sctList 773 } 774 775 return false, nil 776} 777 778func (hs *clientHandshakeState) readFinished(out []byte) error { 779 c := hs.c 780 781 c.readRecord(recordTypeChangeCipherSpec) 782 if err := c.in.error(); err != nil { 783 return err 784 } 785 786 msg, err := c.readHandshake() 787 if err != nil { 788 return err 789 } 790 serverFinished, ok := msg.(*finishedMsg) 791 if !ok { 792 c.sendAlert(alertUnexpectedMessage) 793 return unexpectedMessageError(serverFinished, msg) 794 } 795 796 if c.config.Bugs.EarlyChangeCipherSpec == 0 { 797 verify := hs.finishedHash.serverSum(hs.masterSecret) 798 if len(verify) != len(serverFinished.verifyData) || 799 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { 800 c.sendAlert(alertHandshakeFailure) 801 return errors.New("tls: server's Finished message was incorrect") 802 } 803 } 804 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...) 805 copy(out, serverFinished.verifyData) 806 hs.writeServerHash(serverFinished.marshal()) 807 return nil 808} 809 810func (hs *clientHandshakeState) readSessionTicket() error { 811 c := hs.c 812 813 // Create a session with no server identifier. Either a 814 // session ID or session ticket will be attached. 815 session := &ClientSessionState{ 816 vers: c.vers, 817 cipherSuite: hs.suite.id, 818 masterSecret: hs.masterSecret, 819 handshakeHash: hs.finishedHash.server.Sum(nil), 820 serverCertificates: c.peerCertificates, 821 sctList: c.sctList, 822 ocspResponse: c.ocspResponse, 823 } 824 825 if !hs.serverHello.ticketSupported { 826 if c.config.Bugs.ExpectNewTicket { 827 return errors.New("tls: expected new ticket") 828 } 829 if hs.session == nil && len(hs.serverHello.sessionId) > 0 { 830 session.sessionId = hs.serverHello.sessionId 831 hs.session = session 832 } 833 return nil 834 } 835 836 if c.vers == VersionSSL30 { 837 return errors.New("tls: negotiated session tickets in SSL 3.0") 838 } 839 840 msg, err := c.readHandshake() 841 if err != nil { 842 return err 843 } 844 sessionTicketMsg, ok := msg.(*newSessionTicketMsg) 845 if !ok { 846 c.sendAlert(alertUnexpectedMessage) 847 return unexpectedMessageError(sessionTicketMsg, msg) 848 } 849 850 session.sessionTicket = sessionTicketMsg.ticket 851 hs.session = session 852 853 hs.writeServerHash(sessionTicketMsg.marshal()) 854 855 return nil 856} 857 858func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error { 859 c := hs.c 860 861 var postCCSBytes []byte 862 seqno := hs.c.sendHandshakeSeq 863 if hs.serverHello.nextProtoNeg { 864 nextProto := new(nextProtoMsg) 865 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) 866 nextProto.proto = proto 867 c.clientProtocol = proto 868 c.clientProtocolFallback = fallback 869 870 nextProtoBytes := nextProto.marshal() 871 hs.writeHash(nextProtoBytes, seqno) 872 seqno++ 873 postCCSBytes = append(postCCSBytes, nextProtoBytes...) 874 } 875 876 if hs.serverHello.channelIDRequested { 877 encryptedExtensions := new(encryptedExtensionsMsg) 878 if c.config.ChannelID.Curve != elliptic.P256() { 879 return fmt.Errorf("tls: Channel ID is not on P-256.") 880 } 881 var resumeHash []byte 882 if isResume { 883 resumeHash = hs.session.handshakeHash 884 } 885 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash)) 886 if err != nil { 887 return err 888 } 889 channelID := make([]byte, 128) 890 writeIntPadded(channelID[0:32], c.config.ChannelID.X) 891 writeIntPadded(channelID[32:64], c.config.ChannelID.Y) 892 writeIntPadded(channelID[64:96], r) 893 writeIntPadded(channelID[96:128], s) 894 encryptedExtensions.channelID = channelID 895 896 c.channelID = &c.config.ChannelID.PublicKey 897 898 encryptedExtensionsBytes := encryptedExtensions.marshal() 899 hs.writeHash(encryptedExtensionsBytes, seqno) 900 seqno++ 901 postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...) 902 } 903 904 finished := new(finishedMsg) 905 if c.config.Bugs.EarlyChangeCipherSpec == 2 { 906 finished.verifyData = hs.finishedHash.clientSum(nil) 907 } else { 908 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) 909 } 910 copy(out, finished.verifyData) 911 if c.config.Bugs.BadFinished { 912 finished.verifyData[0]++ 913 } 914 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...) 915 hs.finishedBytes = finished.marshal() 916 hs.writeHash(hs.finishedBytes, seqno) 917 postCCSBytes = append(postCCSBytes, hs.finishedBytes...) 918 919 if c.config.Bugs.FragmentAcrossChangeCipherSpec { 920 c.writeRecord(recordTypeHandshake, postCCSBytes[:5]) 921 postCCSBytes = postCCSBytes[5:] 922 } 923 c.dtlsFlushHandshake() 924 925 if !c.config.Bugs.SkipChangeCipherSpec && 926 c.config.Bugs.EarlyChangeCipherSpec == 0 { 927 ccs := []byte{1} 928 if c.config.Bugs.BadChangeCipherSpec != nil { 929 ccs = c.config.Bugs.BadChangeCipherSpec 930 } 931 c.writeRecord(recordTypeChangeCipherSpec, ccs) 932 } 933 934 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil { 935 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec) 936 } 937 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 { 938 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec) 939 return errors.New("tls: simulating post-CCS alert") 940 } 941 942 if !c.config.Bugs.SkipFinished { 943 c.writeRecord(recordTypeHandshake, postCCSBytes) 944 c.dtlsFlushHandshake() 945 } 946 return nil 947} 948 949func (hs *clientHandshakeState) writeClientHash(msg []byte) { 950 // writeClientHash is called before writeRecord. 951 hs.writeHash(msg, hs.c.sendHandshakeSeq) 952} 953 954func (hs *clientHandshakeState) writeServerHash(msg []byte) { 955 // writeServerHash is called after readHandshake. 956 hs.writeHash(msg, hs.c.recvHandshakeSeq-1) 957} 958 959func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) { 960 if hs.c.isDTLS { 961 // This is somewhat hacky. DTLS hashes a slightly different format. 962 // First, the TLS header. 963 hs.finishedHash.Write(msg[:4]) 964 // Then the sequence number and reassembled fragment offset (always 0). 965 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0}) 966 // Then the reassembled fragment (always equal to the message length). 967 hs.finishedHash.Write(msg[1:4]) 968 // And then the message body. 969 hs.finishedHash.Write(msg[4:]) 970 } else { 971 hs.finishedHash.Write(msg) 972 } 973} 974 975// clientSessionCacheKey returns a key used to cache sessionTickets that could 976// be used to resume previously negotiated TLS sessions with a server. 977func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { 978 if len(config.ServerName) > 0 { 979 return config.ServerName 980 } 981 return serverAddr.String() 982} 983 984// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol 985// given list of possible protocols and a list of the preference order. The 986// first list must not be empty. It returns the resulting protocol and flag 987// indicating if the fallback case was reached. 988func mutualProtocol(protos, preferenceProtos []string) (string, bool) { 989 for _, s := range preferenceProtos { 990 for _, c := range protos { 991 if s == c { 992 return s, false 993 } 994 } 995 } 996 997 return protos[0], true 998} 999 1000// writeIntPadded writes x into b, padded up with leading zeros as 1001// needed. 1002func writeIntPadded(b []byte, x *big.Int) { 1003 for i := range b { 1004 b[i] = 0 1005 } 1006 xb := x.Bytes() 1007 copy(b[len(b)-len(xb):], xb) 1008} 1009