github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/crypto/tls/13.go (about)

     1  package tls
     2  
     3  import (
     4  	"bytes"
     5  	"crypto"
     6  	"crypto/ecdsa"
     7  	"crypto/elliptic"
     8  	"crypto/hmac"
     9  	"crypto/rsa"
    10  	"crypto/subtle"
    11  	"encoding/hex"
    12  	"errors"
    13  	"fmt"
    14  	"hash"
    15  	"io"
    16  	"log"
    17  	"os"
    18  	"runtime"
    19  	"runtime/debug"
    20  	"strings"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"golang_org/x/crypto/curve25519"
    25  )
    26  
    27  // numSessionTickets is the number of different session tickets the
    28  // server sends to a TLS 1.3 client, who will use each only once.
    29  const numSessionTickets = 2
    30  
    31  type secretLabel int
    32  
    33  const (
    34  	secretResumptionPskBinder secretLabel = iota
    35  	secretEarlyClient
    36  	secretHandshakeClient
    37  	secretHandshakeServer
    38  	secretApplicationClient
    39  	secretApplicationServer
    40  	secretResumption
    41  )
    42  
    43  type keySchedule13 struct {
    44  	suite          *cipherSuite
    45  	transcriptHash hash.Hash // uses the cipher suite hash algo
    46  	secret         []byte    // Current secret as used for Derive-Secret
    47  	handshakeCtx   []byte    // cached handshake context, invalidated on updates.
    48  	clientRandom   []byte    // Used for keylogging, nil if keylogging is disabled.
    49  	config         *Config   // Used for KeyLogWriter callback, nil if keylogging is disabled.
    50  }
    51  
    52  func newKeySchedule13(suite *cipherSuite, config *Config, clientRandom []byte) *keySchedule13 {
    53  	if config.KeyLogWriter == nil {
    54  		clientRandom = nil
    55  		config = nil
    56  	}
    57  	return &keySchedule13{
    58  		suite:          suite,
    59  		transcriptHash: hashForSuite(suite).New(),
    60  		clientRandom:   clientRandom,
    61  		config:         config,
    62  	}
    63  }
    64  
    65  // setSecret sets the early/handshake/master secret based on the given secret
    66  // (IKM). The salt is based on previous secrets (nil for the early secret).
    67  func (ks *keySchedule13) setSecret(secret []byte) {
    68  	hash := hashForSuite(ks.suite)
    69  	salt := ks.secret
    70  	ks.secret = hkdfExtract(hash, secret, salt)
    71  }
    72  
    73  // write appends the data to the transcript hash context.
    74  func (ks *keySchedule13) write(data []byte) {
    75  	ks.handshakeCtx = nil
    76  	ks.transcriptHash.Write(data)
    77  }
    78  
    79  func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label, keylogType string) {
    80  	switch secretLabel {
    81  	case secretResumptionPskBinder:
    82  		label = "resumption psk binder key"
    83  	case secretEarlyClient:
    84  		label = "client early traffic secret"
    85  		keylogType = "CLIENT_EARLY_TRAFFIC_SECRET"
    86  	case secretHandshakeClient:
    87  		label = "client handshake traffic secret"
    88  		keylogType = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
    89  	case secretHandshakeServer:
    90  		label = "server handshake traffic secret"
    91  		keylogType = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
    92  	case secretApplicationClient:
    93  		label = "client application traffic secret"
    94  		keylogType = "CLIENT_TRAFFIC_SECRET_0"
    95  	case secretApplicationServer:
    96  		label = "server application traffic secret"
    97  		keylogType = "SERVER_TRAFFIC_SECRET_0"
    98  	case secretResumption:
    99  		label = "resumption master secret"
   100  	}
   101  	return
   102  }
   103  
   104  // deriveSecret returns the secret derived from the handshake context and label.
   105  func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte {
   106  	label, keylogType := ks.getLabel(secretLabel)
   107  	if ks.handshakeCtx == nil {
   108  		ks.handshakeCtx = ks.transcriptHash.Sum(nil)
   109  	}
   110  	hash := hashForSuite(ks.suite)
   111  	secret := hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size())
   112  	if keylogType != "" && ks.config != nil {
   113  		ks.config.writeKeyLog(keylogType, ks.clientRandom, secret)
   114  	}
   115  	return secret
   116  }
   117  
   118  func (ks *keySchedule13) prepareCipher(secretLabel secretLabel) (interface{}, []byte) {
   119  	trafficSecret := ks.deriveSecret(secretLabel)
   120  	hash := hashForSuite(ks.suite)
   121  	key := hkdfExpandLabel(hash, trafficSecret, nil, "key", ks.suite.keyLen)
   122  	iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", 12)
   123  	return ks.suite.aead(key, iv), trafficSecret
   124  }
   125  
   126  func (hs *serverHandshakeState) doTLS13Handshake() error {
   127  	config := hs.c.config
   128  	c := hs.c
   129  
   130  	hs.c.cipherSuite, hs.hello13.cipherSuite = hs.suite.id, hs.suite.id
   131  	hs.c.clientHello = hs.clientHello.marshal()
   132  
   133  	// When picking the group for the handshake, priority is given to groups
   134  	// that the client provided a keyShare for, so to avoid a round-trip.
   135  	// After that the order of CurvePreferences is respected.
   136  	var ks keyShare
   137  CurvePreferenceLoop:
   138  	for _, curveID := range config.curvePreferences() {
   139  		for _, keyShare := range hs.clientHello.keyShares {
   140  			if curveID == keyShare.group {
   141  				ks = keyShare
   142  				break CurvePreferenceLoop
   143  			}
   144  		}
   145  	}
   146  	if ks.group == 0 {
   147  		c.sendAlert(alertInternalError)
   148  		return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
   149  	}
   150  
   151  	if committer, ok := c.conn.(Committer); ok {
   152  		if err := committer.Commit(); err != nil {
   153  			return err
   154  		}
   155  	}
   156  
   157  	privateKey, serverKS, err := config.generateKeyShare(ks.group)
   158  	if err != nil {
   159  		c.sendAlert(alertInternalError)
   160  		return err
   161  	}
   162  	hs.hello13.keyShare = serverKS
   163  
   164  	hash := hashForSuite(hs.suite)
   165  	hashSize := hash.Size()
   166  	hs.keySchedule = newKeySchedule13(hs.suite, config, hs.clientHello.random)
   167  
   168  	// Check for PSK and update key schedule with new early secret key
   169  	isResumed, pskAlert := hs.checkPSK()
   170  	switch {
   171  	case pskAlert != alertSuccess:
   172  		c.sendAlert(pskAlert)
   173  		return errors.New("tls: invalid client PSK")
   174  	case !isResumed:
   175  		// apply an empty PSK if not resumed.
   176  		hs.keySchedule.setSecret(nil)
   177  	case isResumed:
   178  		c.didResume = true
   179  	}
   180  
   181  	hs.keySchedule.write(hs.clientHello.marshal())
   182  
   183  	earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient)
   184  
   185  	ecdheSecret := deriveECDHESecret(ks, privateKey)
   186  	if ecdheSecret == nil {
   187  		c.sendAlert(alertIllegalParameter)
   188  		return errors.New("tls: bad ECDHE client share")
   189  	}
   190  
   191  	hs.keySchedule.write(hs.hello13.marshal())
   192  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello13.marshal()); err != nil {
   193  		return err
   194  	}
   195  
   196  	hs.keySchedule.setSecret(ecdheSecret)
   197  	clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
   198  	hs.hsClientCipher = clientCipher
   199  	serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
   200  	c.out.setCipher(c.vers, serverCipher)
   201  
   202  	serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize)
   203  	hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize)
   204  
   205  	hs.keySchedule.write(hs.hello13Enc.marshal())
   206  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
   207  		return err
   208  	}
   209  
   210  	if !c.didResume {
   211  		if err := hs.sendCertificate13(); err != nil {
   212  			return err
   213  		}
   214  	}
   215  
   216  	verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
   217  	serverFinished := &finishedMsg{
   218  		verifyData: verifyData,
   219  	}
   220  	hs.keySchedule.write(serverFinished.marshal())
   221  	if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
   222  		return err
   223  	}
   224  
   225  	hs.keySchedule.setSecret(nil) // derive master secret
   226  	hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
   227  	serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
   228  	c.out.setCipher(c.vers, serverCipher)
   229  
   230  	if c.hand.Len() > 0 {
   231  		return c.sendAlert(alertUnexpectedMessage)
   232  	}
   233  	if hs.hello13Enc.earlyData {
   234  		c.in.setCipher(c.vers, earlyClientCipher)
   235  		c.phase = readingEarlyData
   236  	} else if hs.clientHello.earlyData {
   237  		c.in.setCipher(c.vers, hs.hsClientCipher)
   238  		c.phase = discardingEarlyData
   239  	} else {
   240  		c.in.setCipher(c.vers, hs.hsClientCipher)
   241  		c.phase = waitingClientFinished
   242  	}
   243  
   244  	return nil
   245  }
   246  
   247  // readClientFinished13 is called when, on the second flight of the client,
   248  // a handshake message is received. This might be immediately or after the
   249  // early data. Once done it sends the session tickets. Under c.in lock.
   250  func (hs *serverHandshakeState) readClientFinished13() error {
   251  	c := hs.c
   252  
   253  	c.phase = readingClientFinished
   254  	msg, err := c.readHandshake()
   255  	if err != nil {
   256  		return err
   257  	}
   258  
   259  	clientFinished, ok := msg.(*finishedMsg)
   260  	if !ok {
   261  		c.sendAlert(alertUnexpectedMessage)
   262  		return unexpectedMessageError(clientFinished, msg)
   263  	}
   264  
   265  	hash := hashForSuite(hs.suite)
   266  	expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey)
   267  	if len(expectedVerifyData) != len(clientFinished.verifyData) ||
   268  		subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
   269  		c.sendAlert(alertDecryptError)
   270  		return errors.New("tls: client's Finished message is incorrect")
   271  	}
   272  	hs.keySchedule.write(clientFinished.marshal())
   273  
   274  	c.hs = nil // Discard the server handshake state
   275  	if c.hand.Len() > 0 {
   276  		return c.sendAlert(alertUnexpectedMessage)
   277  	}
   278  	c.in.setCipher(c.vers, hs.appClientCipher)
   279  	c.in.traceErr, c.out.traceErr = nil, nil
   280  	c.phase = handshakeConfirmed
   281  	atomic.StoreInt32(&c.handshakeConfirmed, 1)
   282  
   283  	// Any read operation after handshakeRunning and before handshakeConfirmed
   284  	// will be holding this lock, which we release as soon as the confirmation
   285  	// happens, even if the Read call might do more work.
   286  	c.confirmMutex.Unlock()
   287  
   288  	return hs.sendSessionTicket13() // TODO: do in a goroutine
   289  }
   290  
   291  func (hs *serverHandshakeState) sendCertificate13() error {
   292  	c := hs.c
   293  
   294  	certEntries := []certificateEntry{}
   295  	for _, cert := range hs.cert.Certificate {
   296  		certEntries = append(certEntries, certificateEntry{data: cert})
   297  	}
   298  	if len(certEntries) > 0 && hs.clientHello.ocspStapling {
   299  		certEntries[0].ocspStaple = hs.cert.OCSPStaple
   300  	}
   301  	if len(certEntries) > 0 && hs.clientHello.scts {
   302  		certEntries[0].sctList = hs.cert.SignedCertificateTimestamps
   303  	}
   304  	certMsg := &certificateMsg13{certificates: certEntries}
   305  
   306  	hs.keySchedule.write(certMsg.marshal())
   307  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   308  		return err
   309  	}
   310  
   311  	sigScheme, err := hs.selectTLS13SignatureScheme()
   312  	if err != nil {
   313  		c.sendAlert(alertInternalError)
   314  		return err
   315  	}
   316  
   317  	sigHash := hashForSignatureScheme(sigScheme)
   318  	opts := crypto.SignerOpts(sigHash)
   319  	if signatureSchemeIsPSS(sigScheme) {
   320  		opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   321  	}
   322  
   323  	toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
   324  	signature, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
   325  	if err != nil {
   326  		c.sendAlert(alertInternalError)
   327  		return err
   328  	}
   329  
   330  	verifyMsg := &certificateVerifyMsg{
   331  		hasSignatureAndHash: true,
   332  		signatureAlgorithm:  sigScheme,
   333  		signature:           signature,
   334  	}
   335  	hs.keySchedule.write(verifyMsg.marshal())
   336  	if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
   337  		return err
   338  	}
   339  
   340  	return nil
   341  }
   342  
   343  func (c *Conn) handleEndOfEarlyData() {
   344  	if c.phase != readingEarlyData || c.vers < VersionTLS13 {
   345  		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   346  		return
   347  	}
   348  	c.phase = waitingClientFinished
   349  	if c.hand.Len() > 0 {
   350  		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   351  		return
   352  	}
   353  	c.in.setCipher(c.vers, c.hs.hsClientCipher)
   354  }
   355  
   356  // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
   357  // based on the certificate type and client supported schemes. If no overlap is found,
   358  // a fallback is selected.
   359  //
   360  // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
   361  func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
   362  	var supportedSchemes []SignatureScheme
   363  	signer, ok := hs.cert.PrivateKey.(crypto.Signer)
   364  	if !ok {
   365  		return 0, errors.New("tls: certificate private key does not implement crypto.Signer")
   366  	}
   367  	pk := signer.Public()
   368  	if _, ok := pk.(*rsa.PublicKey); ok {
   369  		sigScheme = PSSWithSHA256
   370  		supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
   371  	} else if pk, ok := pk.(*ecdsa.PublicKey); ok {
   372  		switch pk.Curve {
   373  		case elliptic.P256():
   374  			sigScheme = ECDSAWithP256AndSHA256
   375  			supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
   376  		case elliptic.P384():
   377  			sigScheme = ECDSAWithP384AndSHA384
   378  			supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
   379  		case elliptic.P521():
   380  			sigScheme = ECDSAWithP521AndSHA512
   381  			supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
   382  		default:
   383  			return 0, errors.New("tls: unknown ECDSA certificate curve")
   384  		}
   385  	} else {
   386  		return 0, errors.New("tls: unknown certificate key type")
   387  	}
   388  
   389  	for _, ss := range supportedSchemes {
   390  		for _, cs := range hs.clientHello.supportedSignatureAlgorithms {
   391  			if ss == cs {
   392  				return ss, nil
   393  			}
   394  		}
   395  	}
   396  
   397  	return sigScheme, nil
   398  }
   399  
   400  func signatureSchemeIsPSS(s SignatureScheme) bool {
   401  	return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
   402  }
   403  
   404  // hashForSignatureScheme returns the Hash used by a SignatureScheme which is
   405  // supported by selectTLS13SignatureScheme.
   406  func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
   407  	switch ss {
   408  	case PSSWithSHA256, ECDSAWithP256AndSHA256:
   409  		return crypto.SHA256
   410  	case PSSWithSHA384, ECDSAWithP384AndSHA384:
   411  		return crypto.SHA384
   412  	case PSSWithSHA512, ECDSAWithP521AndSHA512:
   413  		return crypto.SHA512
   414  	default:
   415  		panic("unsupported SignatureScheme passed to hashForSignatureScheme")
   416  	}
   417  }
   418  
   419  func hashForSuite(suite *cipherSuite) crypto.Hash {
   420  	if suite.flags&suiteSHA384 != 0 {
   421  		return crypto.SHA384
   422  	}
   423  	return crypto.SHA256
   424  }
   425  
   426  func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
   427  	message := bytes.Repeat([]byte{32}, 64)
   428  	message = append(message, context...)
   429  	message = append(message, 0)
   430  	message = append(message, data...)
   431  	h := hash.New()
   432  	h.Write(message)
   433  	return h.Sum(nil)
   434  }
   435  
   436  func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
   437  	if curveID == X25519 {
   438  		var scalar, public [32]byte
   439  		if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
   440  			return nil, keyShare{}, err
   441  		}
   442  
   443  		curve25519.ScalarBaseMult(&public, &scalar)
   444  		return scalar[:], keyShare{group: curveID, data: public[:]}, nil
   445  	}
   446  
   447  	curve, ok := curveForCurveID(curveID)
   448  	if !ok {
   449  		return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
   450  	}
   451  
   452  	privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
   453  	if err != nil {
   454  		return nil, keyShare{}, err
   455  	}
   456  	ecdhePublic := elliptic.Marshal(curve, x, y)
   457  
   458  	return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
   459  }
   460  
   461  func deriveECDHESecret(ks keyShare, secretKey []byte) []byte {
   462  	if ks.group == X25519 {
   463  		if len(ks.data) != 32 {
   464  			return nil
   465  		}
   466  
   467  		var theirPublic, sharedKey, scalar [32]byte
   468  		copy(theirPublic[:], ks.data)
   469  		copy(scalar[:], secretKey)
   470  		curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
   471  		return sharedKey[:]
   472  	}
   473  
   474  	curve, ok := curveForCurveID(ks.group)
   475  	if !ok {
   476  		return nil
   477  	}
   478  	x, y := elliptic.Unmarshal(curve, ks.data)
   479  	if x == nil {
   480  		return nil
   481  	}
   482  	x, _ = curve.ScalarMult(x, y, secretKey)
   483  	xBytes := x.Bytes()
   484  	curveSize := (curve.Params().BitSize + 8 - 1) >> 3
   485  	if len(xBytes) == curveSize {
   486  		return xBytes
   487  	}
   488  	buf := make([]byte, curveSize)
   489  	copy(buf[len(buf)-len(xBytes):], xBytes)
   490  	return buf
   491  }
   492  
   493  func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
   494  	hkdfLabel := make([]byte, 4+len("TLS 1.3, ")+len(label)+len(hashValue))
   495  	hkdfLabel[0] = byte(L >> 8)
   496  	hkdfLabel[1] = byte(L)
   497  	hkdfLabel[2] = byte(len("TLS 1.3, ") + len(label))
   498  	copy(hkdfLabel[3:], "TLS 1.3, ")
   499  	z := hkdfLabel[3+len("TLS 1.3, "):]
   500  	copy(z, label)
   501  	z = z[len(label):]
   502  	z[0] = byte(len(hashValue))
   503  	copy(z[1:], hashValue)
   504  
   505  	return hkdfExpand(hash, secret, hkdfLabel, L)
   506  }
   507  
   508  func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte {
   509  	h := hmac.New(f.New, key)
   510  	h.Write(hash.Sum(nil))
   511  	return h.Sum(nil)
   512  }
   513  
   514  // Maximum allowed mismatch between the stated age of a ticket
   515  // and the server-observed one. See
   516  // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2.
   517  const ticketAgeSkewAllowance = 10 * time.Second
   518  
   519  // checkPSK tries to resume using a PSK, returning true (and updating the
   520  // early secret in the key schedule) if the PSK was used and false otherwise.
   521  func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) {
   522  	if hs.c.config.SessionTicketsDisabled {
   523  		return false, alertSuccess
   524  	}
   525  
   526  	foundDHE := false
   527  	for _, mode := range hs.clientHello.pskKeyExchangeModes {
   528  		if mode == pskDHEKeyExchange {
   529  			foundDHE = true
   530  			break
   531  		}
   532  	}
   533  	if !foundDHE {
   534  		return false, alertSuccess
   535  	}
   536  
   537  	hash := hashForSuite(hs.suite)
   538  	hashSize := hash.Size()
   539  	for i := range hs.clientHello.psks {
   540  		sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...)
   541  		if hs.c.config.SessionTicketSealer != nil {
   542  			var ok bool
   543  			sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket)
   544  			if !ok {
   545  				continue
   546  			}
   547  		} else {
   548  			sessionTicket, _ = hs.c.decryptTicket(sessionTicket)
   549  			if sessionTicket == nil {
   550  				continue
   551  			}
   552  		}
   553  		s := &sessionState13{}
   554  		if s.unmarshal(sessionTicket) != alertSuccess {
   555  			continue
   556  		}
   557  		if s.vers != hs.c.vers {
   558  			continue
   559  		}
   560  		clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond
   561  		serverAge := time.Since(time.Unix(int64(s.createdAt), 0))
   562  		if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
   563  			// XXX: NSS is off spec and sends obfuscated_ticket_age as seconds
   564  			clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second
   565  			if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
   566  				continue
   567  			}
   568  		}
   569  
   570  		// This enforces the stricter 0-RTT requirements on all ticket uses.
   571  		// The benefit of using PSK+ECDHE without 0-RTT are small enough that
   572  		// we can give them up in the edge case of changed suite or ALPN or SNI.
   573  		if s.suite != hs.suite.id {
   574  			continue
   575  		}
   576  		if s.alpnProtocol != hs.c.clientProtocol {
   577  			continue
   578  		}
   579  		if s.SNI != hs.c.serverName {
   580  			continue
   581  		}
   582  
   583  		hs.keySchedule.setSecret(s.resumptionSecret)
   584  		binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder)
   585  		binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize)
   586  		chHash := hash.New()
   587  		chHash.Write(hs.clientHello.rawTruncated)
   588  		expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey)
   589  
   590  		if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 {
   591  			return false, alertDecryptError
   592  		}
   593  
   594  		if i == 0 && hs.clientHello.earlyData {
   595  			// This is a ticket intended to be used for 0-RTT
   596  			if s.maxEarlyDataLen == 0 {
   597  				// But we had not tagged it as such.
   598  				return false, alertIllegalParameter
   599  			}
   600  			if hs.c.config.Accept0RTTData {
   601  				hs.c.binder = expectedBinder
   602  				hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen)
   603  				hs.hello13Enc.earlyData = true
   604  			}
   605  		}
   606  		hs.hello13.psk = true
   607  		hs.hello13.pskIdentity = uint16(i)
   608  		return true, alertSuccess
   609  	}
   610  
   611  	return false, alertSuccess
   612  }
   613  
   614  func (hs *serverHandshakeState) sendSessionTicket13() error {
   615  	c := hs.c
   616  	if c.config.SessionTicketsDisabled {
   617  		return nil
   618  	}
   619  
   620  	foundDHE := false
   621  	for _, mode := range hs.clientHello.pskKeyExchangeModes {
   622  		if mode == pskDHEKeyExchange {
   623  			foundDHE = true
   624  			break
   625  		}
   626  	}
   627  	if !foundDHE {
   628  		return nil
   629  	}
   630  
   631  	resumptionSecret := hs.keySchedule.deriveSecret(secretResumption)
   632  
   633  	ageAddBuf := make([]byte, 4)
   634  	sessionState := &sessionState13{
   635  		vers:             c.vers,
   636  		suite:            hs.suite.id,
   637  		createdAt:        uint64(time.Now().Unix()),
   638  		resumptionSecret: resumptionSecret,
   639  		alpnProtocol:     c.clientProtocol,
   640  		SNI:              c.serverName,
   641  		maxEarlyDataLen:  c.config.Max0RTTDataSize,
   642  	}
   643  
   644  	for i := 0; i < numSessionTickets; i++ {
   645  		if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil {
   646  			c.sendAlert(alertInternalError)
   647  			return err
   648  		}
   649  		sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 |
   650  			uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3])
   651  		ticket := sessionState.marshal()
   652  		var err error
   653  		if c.config.SessionTicketSealer != nil {
   654  			cs := c.ConnectionState()
   655  			ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket)
   656  		} else {
   657  			ticket, err = c.encryptTicket(ticket)
   658  		}
   659  		if err != nil {
   660  			c.sendAlert(alertInternalError)
   661  			return err
   662  		}
   663  		if ticket == nil {
   664  			continue
   665  		}
   666  		ticketMsg := &newSessionTicketMsg13{
   667  			lifetime:           24 * 3600, // TODO(filippo)
   668  			maxEarlyDataLength: c.config.Max0RTTDataSize,
   669  			withEarlyDataInfo:  c.config.Max0RTTDataSize > 0,
   670  			ageAdd:             sessionState.ageAdd,
   671  			ticket:             ticket,
   672  		}
   673  		if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil {
   674  			return err
   675  		}
   676  	}
   677  
   678  	return nil
   679  }
   680  
   681  func (hs *serverHandshakeState) traceErr(err error) {
   682  	if err == nil {
   683  		return
   684  	}
   685  	if os.Getenv("TLSDEBUG") == "error" {
   686  		if hs != nil && hs.clientHello != nil {
   687  			os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal()))
   688  		} else if err == io.EOF {
   689  			return // don't stack trace on EOF before CH
   690  		}
   691  		fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack())
   692  	}
   693  	if os.Getenv("TLSDEBUG") == "short" {
   694  		var pcs [4]uintptr
   695  		frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])])
   696  		for {
   697  			frame, more := frames.Next()
   698  			if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" &&
   699  				frame.Function != "crypto/tls.(*Conn).sendAlertLocked" &&
   700  				frame.Function != "crypto/tls.(*Conn).sendAlert" {
   701  				file := frame.File[strings.LastIndex(frame.File, "/")+1:]
   702  				log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err)
   703  				return
   704  			}
   705  			if !more {
   706  				break
   707  			}
   708  		}
   709  	}
   710  }