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.
20 // serverHandshakeState contains details of a server handshake in progress.
21 // It's discarded once the handshake has completed.
22 type serverHandshakeState struct {
24 clientHello *clientHelloMsg
31 sessionState *sessionState
32 finishedHash finishedHash
37 // serverHandshake performs a TLS handshake as a server.
38 func (c *Conn) serverHandshake() error {
39 // If this is the first server handshake, we generate a random key to
40 // encrypt the tickets with.
41 c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
43 clientHello, err := c.readClientHello()
48 if c.vers == VersionTLS13 {
49 hs := serverHandshakeStateTLS13{
51 clientHello: clientHello,
56 hs := serverHandshakeState{
58 clientHello: clientHello,
63 func (hs *serverHandshakeState) handshake() error {
66 if err := hs.processClientHello(); err != nil {
70 // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
72 if hs.checkForResumption() {
73 // The client has included a session ticket and so we do an abbreviated handshake.
74 if err := hs.doResumeHandshake(); err != nil {
77 if err := hs.establishKeys(); err != nil {
80 // ticketSupported is set in a resumption handshake if the
81 // ticket from the client was encrypted with an old session
82 // ticket key and thus a refreshed ticket should be sent.
83 if hs.hello.ticketSupported {
84 if err := hs.sendSessionTicket(); err != nil {
88 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
91 if _, err := c.flush(); err != nil {
94 c.clientFinishedIsFirst = false
95 if err := hs.readFinished(nil); err != nil {
100 // The client didn't include a session ticket, or it wasn't
101 // valid so we do a full handshake.
102 if err := hs.pickCipherSuite(); err != nil {
105 if err := hs.doFullHandshake(); err != nil {
108 if err := hs.establishKeys(); err != nil {
111 if err := hs.readFinished(c.clientFinished[:]); err != nil {
114 c.clientFinishedIsFirst = true
116 if err := hs.sendSessionTicket(); err != nil {
119 if err := hs.sendFinished(nil); err != nil {
122 if _, err := c.flush(); err != nil {
127 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
128 atomic.StoreUint32(&c.handshakeStatus, 1)
133 // readClientHello reads a ClientHello message and selects the protocol version.
134 func (c *Conn) readClientHello() (*clientHelloMsg, error) {
135 msg, err := c.readHandshake()
139 clientHello, ok := msg.(*clientHelloMsg)
141 c.sendAlert(alertUnexpectedMessage)
142 return nil, unexpectedMessageError(clientHello, msg)
145 if c.config.GetConfigForClient != nil {
146 chi := clientHelloInfo(c, clientHello)
147 if newConfig, err := c.config.GetConfigForClient(chi); err != nil {
148 c.sendAlert(alertInternalError)
150 } else if newConfig != nil {
151 newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
156 clientVersions := clientHello.supportedVersions
157 if len(clientHello.supportedVersions) == 0 {
158 clientVersions = supportedVersionsFromMax(clientHello.vers)
160 c.vers, ok = c.config.mutualVersion(false, clientVersions)
162 c.sendAlert(alertProtocolVersion)
163 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
166 c.in.version = c.vers
167 c.out.version = c.vers
169 return clientHello, nil
172 func (hs *serverHandshakeState) processClientHello() error {
175 hs.hello = new(serverHelloMsg)
176 hs.hello.vers = c.vers
178 supportedCurve := false
179 preferredCurves := c.config.curvePreferences()
181 for _, curve := range hs.clientHello.supportedCurves {
182 for _, supported := range preferredCurves {
183 if supported == curve {
184 supportedCurve = true
190 supportedPointFormat := false
191 for _, pointFormat := range hs.clientHello.supportedPoints {
192 if pointFormat == pointFormatUncompressed {
193 supportedPointFormat = true
197 hs.ecdhOk = supportedCurve && supportedPointFormat
199 foundCompression := false
200 // We only support null compression, so check that the client offered it.
201 for _, compression := range hs.clientHello.compressionMethods {
202 if compression == compressionNone {
203 foundCompression = true
208 if !foundCompression {
209 c.sendAlert(alertHandshakeFailure)
210 return errors.New("tls: client does not support uncompressed connections")
213 hs.hello.random = make([]byte, 32)
214 serverRandom := hs.hello.random
215 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
216 maxVers := c.config.maxSupportedVersion(false)
217 if maxVers >= VersionTLS12 && c.vers < maxVers {
218 if c.vers == VersionTLS12 {
219 copy(serverRandom[24:], downgradeCanaryTLS12)
221 copy(serverRandom[24:], downgradeCanaryTLS11)
223 serverRandom = serverRandom[:24]
225 _, err := io.ReadFull(c.config.rand(), serverRandom)
227 c.sendAlert(alertInternalError)
231 if len(hs.clientHello.secureRenegotiation) != 0 {
232 c.sendAlert(alertHandshakeFailure)
233 return errors.New("tls: initial handshake had non-empty renegotiation extension")
236 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
237 hs.hello.compressionMethod = compressionNone
238 if len(hs.clientHello.serverName) > 0 {
239 c.serverName = hs.clientHello.serverName
242 if len(hs.clientHello.alpnProtocols) > 0 {
243 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
244 hs.hello.alpnProtocol = selectedProto
245 c.clientProtocol = selectedProto
248 // Although sending an empty NPN extension is reasonable, Firefox has
249 // had a bug around this. Best to send nothing at all if
250 // c.config.NextProtos is empty. See
251 // https://golang.org/issue/5445.
252 if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 {
253 hs.hello.nextProtoNeg = true
254 hs.hello.nextProtos = c.config.NextProtos
258 hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
260 c.sendAlert(alertInternalError)
263 if hs.clientHello.scts {
264 hs.hello.scts = hs.cert.SignedCertificateTimestamps
267 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
268 switch priv.Public().(type) {
269 case *ecdsa.PublicKey:
271 case ed25519.PublicKey:
276 c.sendAlert(alertInternalError)
277 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
280 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
281 switch priv.Public().(type) {
283 hs.rsaDecryptOk = true
285 c.sendAlert(alertInternalError)
286 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
293 func (hs *serverHandshakeState) pickCipherSuite() error {
296 var preferenceList, supportedList []uint16
297 if c.config.PreferServerCipherSuites {
298 preferenceList = c.config.cipherSuites()
299 supportedList = hs.clientHello.cipherSuites
301 preferenceList = hs.clientHello.cipherSuites
302 supportedList = c.config.cipherSuites()
305 for _, id := range preferenceList {
306 if hs.setCipherSuite(id, supportedList, c.vers) {
312 c.sendAlert(alertHandshakeFailure)
313 return errors.New("tls: no cipher suite supported by both client and server")
316 for _, id := range hs.clientHello.cipherSuites {
317 if id == TLS_FALLBACK_SCSV {
318 // The client is doing a fallback connection. See RFC 7507.
319 if hs.clientHello.vers < c.config.maxSupportedVersion(false) {
320 c.sendAlert(alertInappropriateFallback)
321 return errors.New("tls: client using inappropriate protocol fallback")
330 // checkForResumption reports whether we should perform resumption on this connection.
331 func (hs *serverHandshakeState) checkForResumption() bool {
334 if c.config.SessionTicketsDisabled {
338 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
339 if plaintext == nil {
342 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
343 ok := hs.sessionState.unmarshal(plaintext)
348 // Never resume a session for a different TLS version.
349 if c.vers != hs.sessionState.vers {
353 cipherSuiteOk := false
354 // Check that the client is still offering the ciphersuite in the session.
355 for _, id := range hs.clientHello.cipherSuites {
356 if id == hs.sessionState.cipherSuite {
365 // Check that we also support the ciphersuite from the session.
366 if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
370 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
371 needClientCerts := requiresClientCert(c.config.ClientAuth)
372 if needClientCerts && !sessionHasClientCerts {
375 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
382 func (hs *serverHandshakeState) doResumeHandshake() error {
385 hs.hello.cipherSuite = hs.suite.id
386 // We echo the client's session ID in the ServerHello to let it know
387 // that we're doing a resumption.
388 hs.hello.sessionId = hs.clientHello.sessionId
389 hs.hello.ticketSupported = hs.sessionState.usedOldKey
390 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
391 hs.finishedHash.discardHandshakeBuffer()
392 hs.finishedHash.Write(hs.clientHello.marshal())
393 hs.finishedHash.Write(hs.hello.marshal())
394 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
398 if err := c.processCertsFromClient(Certificate{
399 Certificate: hs.sessionState.certificates,
404 hs.masterSecret = hs.sessionState.masterSecret
409 func (hs *serverHandshakeState) doFullHandshake() error {
412 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
413 hs.hello.ocspStapling = true
416 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
417 hs.hello.cipherSuite = hs.suite.id
419 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
420 if c.config.ClientAuth == NoClientCert {
421 // No need to keep a full record of the handshake if client
422 // certificates won't be used.
423 hs.finishedHash.discardHandshakeBuffer()
425 hs.finishedHash.Write(hs.clientHello.marshal())
426 hs.finishedHash.Write(hs.hello.marshal())
427 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
431 certMsg := new(certificateMsg)
432 certMsg.certificates = hs.cert.Certificate
433 hs.finishedHash.Write(certMsg.marshal())
434 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
438 if hs.hello.ocspStapling {
439 certStatus := new(certificateStatusMsg)
440 certStatus.response = hs.cert.OCSPStaple
441 hs.finishedHash.Write(certStatus.marshal())
442 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
447 keyAgreement := hs.suite.ka(c.vers)
448 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
450 c.sendAlert(alertHandshakeFailure)
454 hs.finishedHash.Write(skx.marshal())
455 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
460 if c.config.ClientAuth >= RequestClientCert {
461 // Request a client certificate
462 certReq := new(certificateRequestMsg)
463 certReq.certificateTypes = []byte{
464 byte(certTypeRSASign),
465 byte(certTypeECDSASign),
467 if c.vers >= VersionTLS12 {
468 certReq.hasSignatureAlgorithm = true
469 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
472 // An empty list of certificateAuthorities signals to
473 // the client that it may send any certificate in response
474 // to our request. When we know the CAs we trust, then
475 // we can send them down, so that the client can choose
476 // an appropriate certificate to give to us.
477 if c.config.ClientCAs != nil {
478 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
480 hs.finishedHash.Write(certReq.marshal())
481 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
486 helloDone := new(serverHelloDoneMsg)
487 hs.finishedHash.Write(helloDone.marshal())
488 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
492 if _, err := c.flush(); err != nil {
496 var pub crypto.PublicKey // public key for client auth, if any
498 msg, err := c.readHandshake()
503 // If we requested a client certificate, then the client must send a
504 // certificate message, even if it's empty.
505 if c.config.ClientAuth >= RequestClientCert {
506 certMsg, ok := msg.(*certificateMsg)
508 c.sendAlert(alertUnexpectedMessage)
509 return unexpectedMessageError(certMsg, msg)
511 hs.finishedHash.Write(certMsg.marshal())
513 if err := c.processCertsFromClient(Certificate{
514 Certificate: certMsg.certificates,
518 if len(certMsg.certificates) != 0 {
519 pub = c.peerCertificates[0].PublicKey
522 msg, err = c.readHandshake()
528 // Get client key exchange
529 ckx, ok := msg.(*clientKeyExchangeMsg)
531 c.sendAlert(alertUnexpectedMessage)
532 return unexpectedMessageError(ckx, msg)
534 hs.finishedHash.Write(ckx.marshal())
536 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
538 c.sendAlert(alertHandshakeFailure)
541 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
542 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
543 c.sendAlert(alertInternalError)
547 // If we received a client cert in response to our certificate request message,
548 // the client will send us a certificateVerifyMsg immediately after the
549 // clientKeyExchangeMsg. This message is a digest of all preceding
550 // handshake-layer messages that is signed using the private key corresponding
551 // to the client's certificate. This allows us to verify that the client is in
552 // possession of the private key of the certificate.
553 if len(c.peerCertificates) > 0 {
554 msg, err = c.readHandshake()
558 certVerify, ok := msg.(*certificateVerifyMsg)
560 c.sendAlert(alertUnexpectedMessage)
561 return unexpectedMessageError(certVerify, msg)
564 // Determine the signature type.
565 _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms(), c.vers)
567 c.sendAlert(alertIllegalParameter)
571 signed, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
573 err = verifyHandshakeSignature(sigType, pub, hashFunc, signed, certVerify.signature)
576 c.sendAlert(alertBadCertificate)
577 return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
580 hs.finishedHash.Write(certVerify.marshal())
583 hs.finishedHash.discardHandshakeBuffer()
588 func (hs *serverHandshakeState) establishKeys() error {
591 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
592 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
594 var clientCipher, serverCipher interface{}
595 var clientHash, serverHash macFunction
597 if hs.suite.aead == nil {
598 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
599 clientHash = hs.suite.mac(c.vers, clientMAC)
600 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
601 serverHash = hs.suite.mac(c.vers, serverMAC)
603 clientCipher = hs.suite.aead(clientKey, clientIV)
604 serverCipher = hs.suite.aead(serverKey, serverIV)
607 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
608 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
613 func (hs *serverHandshakeState) readFinished(out []byte) error {
616 if err := c.readChangeCipherSpec(); err != nil {
620 if hs.hello.nextProtoNeg {
621 msg, err := c.readHandshake()
625 nextProto, ok := msg.(*nextProtoMsg)
627 c.sendAlert(alertUnexpectedMessage)
628 return unexpectedMessageError(nextProto, msg)
630 hs.finishedHash.Write(nextProto.marshal())
631 c.clientProtocol = nextProto.proto
634 msg, err := c.readHandshake()
638 clientFinished, ok := msg.(*finishedMsg)
640 c.sendAlert(alertUnexpectedMessage)
641 return unexpectedMessageError(clientFinished, msg)
644 verify := hs.finishedHash.clientSum(hs.masterSecret)
645 if len(verify) != len(clientFinished.verifyData) ||
646 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
647 c.sendAlert(alertHandshakeFailure)
648 return errors.New("tls: client's Finished message is incorrect")
651 hs.finishedHash.Write(clientFinished.marshal())
656 func (hs *serverHandshakeState) sendSessionTicket() error {
657 if !hs.hello.ticketSupported {
662 m := new(newSessionTicketMsg)
664 var certsFromClient [][]byte
665 for _, cert := range c.peerCertificates {
666 certsFromClient = append(certsFromClient, cert.Raw)
668 state := sessionState{
670 cipherSuite: hs.suite.id,
671 masterSecret: hs.masterSecret,
672 certificates: certsFromClient,
675 m.ticket, err = c.encryptTicket(state.marshal())
680 hs.finishedHash.Write(m.marshal())
681 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
688 func (hs *serverHandshakeState) sendFinished(out []byte) error {
691 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
695 finished := new(finishedMsg)
696 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
697 hs.finishedHash.Write(finished.marshal())
698 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
702 c.cipherSuite = hs.suite.id
703 copy(out, finished.verifyData)
708 // processCertsFromClient takes a chain of client certificates either from a
709 // Certificates message or from a sessionState and verifies them. It returns
710 // the public key of the leaf certificate.
711 func (c *Conn) processCertsFromClient(certificate Certificate) error {
712 certificates := certificate.Certificate
713 certs := make([]*x509.Certificate, len(certificates))
715 for i, asn1Data := range certificates {
716 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
717 c.sendAlert(alertBadCertificate)
718 return errors.New("tls: failed to parse client certificate: " + err.Error())
722 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
723 c.sendAlert(alertBadCertificate)
724 return errors.New("tls: client didn't provide a certificate")
727 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
728 opts := x509.VerifyOptions{
729 IsBoring: isBoringCertificate,
731 Roots: c.config.ClientCAs,
732 CurrentTime: c.config.time(),
733 Intermediates: x509.NewCertPool(),
734 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
737 for _, cert := range certs[1:] {
738 opts.Intermediates.AddCert(cert)
741 chains, err := certs[0].Verify(opts)
743 c.sendAlert(alertBadCertificate)
744 return errors.New("tls: failed to verify client's certificate: " + err.Error())
747 c.verifiedChains = chains
750 if c.config.VerifyPeerCertificate != nil {
751 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
752 c.sendAlert(alertBadCertificate)
761 switch certs[0].PublicKey.(type) {
762 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
764 c.sendAlert(alertUnsupportedCertificate)
765 return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
768 c.peerCertificates = certs
769 c.ocspResponse = certificate.OCSPStaple
770 c.scts = certificate.SignedCertificateTimestamps
774 // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
775 // suite if that cipher suite is acceptable to use.
776 // It returns a bool indicating if the suite was set.
777 func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
778 for _, supported := range supportedCipherSuites {
782 candidate := cipherSuiteByID(id)
783 if candidate == nil {
786 // Don't select a ciphersuite which we can't
787 // support for this client.
788 if candidate.flags&suiteECDHE != 0 {
792 if candidate.flags&suiteECSign != 0 {
796 } else if !hs.rsaSignOk {
799 } else if !hs.rsaDecryptOk {
802 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
811 func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
812 supportedVersions := clientHello.supportedVersions
813 if len(clientHello.supportedVersions) == 0 {
814 supportedVersions = supportedVersionsFromMax(clientHello.vers)
817 return &ClientHelloInfo{
818 CipherSuites: clientHello.cipherSuites,
819 ServerName: clientHello.serverName,
820 SupportedCurves: clientHello.supportedCurves,
821 SupportedPoints: clientHello.supportedPoints,
822 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
823 SupportedProtos: clientHello.alpnProtocols,
824 SupportedVersions: supportedVersions,