2016-11-06 17:01:12 +00:00
|
|
|
package tls
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto"
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/subtle"
|
2016-11-07 06:48:40 +00:00
|
|
|
"encoding/hex"
|
2016-11-06 17:01:12 +00:00
|
|
|
"errors"
|
2016-11-07 06:48:40 +00:00
|
|
|
"fmt"
|
2016-11-23 03:23:34 +00:00
|
|
|
"hash"
|
2016-11-06 17:01:12 +00:00
|
|
|
"io"
|
2017-01-24 18:56:43 +00:00
|
|
|
"log"
|
2016-11-07 06:48:40 +00:00
|
|
|
"os"
|
2017-01-24 18:56:43 +00:00
|
|
|
"runtime"
|
2016-11-07 06:48:40 +00:00
|
|
|
"runtime/debug"
|
2017-01-24 18:56:43 +00:00
|
|
|
"strings"
|
2016-12-05 18:38:08 +00:00
|
|
|
"sync/atomic"
|
2016-11-21 22:25:27 +00:00
|
|
|
"time"
|
2016-11-06 17:01:12 +00:00
|
|
|
|
|
|
|
"golang_org/x/crypto/curve25519"
|
|
|
|
)
|
|
|
|
|
2017-01-30 18:03:46 +00:00
|
|
|
// numSessionTickets is the number of different session tickets the
|
2017-06-01 22:09:33 +01:00
|
|
|
// server sends to a TLS 1.3 client, who will use each only once.
|
2017-01-30 18:03:46 +00:00
|
|
|
const numSessionTickets = 2
|
|
|
|
|
2017-09-18 15:55:55 +01:00
|
|
|
type secretLabel int
|
|
|
|
|
|
|
|
const (
|
|
|
|
secretResumptionPskBinder secretLabel = iota
|
|
|
|
secretEarlyClient
|
|
|
|
secretHandshakeClient
|
|
|
|
secretHandshakeServer
|
|
|
|
secretApplicationClient
|
|
|
|
secretApplicationServer
|
|
|
|
secretResumption
|
|
|
|
)
|
|
|
|
|
|
|
|
type keySchedule13 struct {
|
|
|
|
suite *cipherSuite
|
|
|
|
transcriptHash hash.Hash // uses the cipher suite hash algo
|
|
|
|
secret []byte // Current secret as used for Derive-Secret
|
|
|
|
handshakeCtx []byte // cached handshake context, invalidated on updates.
|
|
|
|
}
|
|
|
|
|
|
|
|
func newKeySchedule13(suite *cipherSuite) *keySchedule13 {
|
|
|
|
return &keySchedule13{
|
|
|
|
suite: suite,
|
|
|
|
transcriptHash: hashForSuite(suite).New(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// setSecret sets the early/handshake/master secret based on the given secret
|
|
|
|
// (IKM). The salt is based on previous secrets (nil for the early secret).
|
|
|
|
func (ks *keySchedule13) setSecret(secret []byte) {
|
|
|
|
hash := hashForSuite(ks.suite)
|
|
|
|
salt := ks.secret
|
|
|
|
ks.secret = hkdfExtract(hash, secret, salt)
|
|
|
|
}
|
|
|
|
|
|
|
|
// write appends the data to the transcript hash context.
|
|
|
|
func (ks *keySchedule13) write(data []byte) {
|
|
|
|
ks.handshakeCtx = nil
|
|
|
|
ks.transcriptHash.Write(data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label string) {
|
|
|
|
switch secretLabel {
|
|
|
|
case secretResumptionPskBinder:
|
|
|
|
label = "resumption psk binder key"
|
|
|
|
case secretEarlyClient:
|
|
|
|
label = "client early traffic secret"
|
|
|
|
case secretHandshakeClient:
|
|
|
|
label = "client handshake traffic secret"
|
|
|
|
case secretHandshakeServer:
|
|
|
|
label = "server handshake traffic secret"
|
|
|
|
case secretApplicationClient:
|
|
|
|
label = "client application traffic secret"
|
|
|
|
case secretApplicationServer:
|
|
|
|
label = "server application traffic secret"
|
|
|
|
case secretResumption:
|
|
|
|
label = "resumption master secret"
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// deriveSecret returns the secret derived from the handshake context and label.
|
|
|
|
func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte {
|
|
|
|
label := ks.getLabel(secretLabel)
|
|
|
|
if ks.handshakeCtx == nil {
|
|
|
|
ks.handshakeCtx = ks.transcriptHash.Sum(nil)
|
|
|
|
}
|
|
|
|
hash := hashForSuite(ks.suite)
|
|
|
|
return hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ks *keySchedule13) prepareCipher(secretLabel secretLabel) (interface{}, []byte) {
|
|
|
|
trafficSecret := ks.deriveSecret(secretLabel)
|
|
|
|
hash := hashForSuite(ks.suite)
|
|
|
|
key := hkdfExpandLabel(hash, trafficSecret, nil, "key", ks.suite.keyLen)
|
|
|
|
iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", 12)
|
|
|
|
return ks.suite.aead(key, iv), trafficSecret
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
func (hs *serverHandshakeState) doTLS13Handshake() error {
|
|
|
|
config := hs.c.config
|
|
|
|
c := hs.c
|
|
|
|
|
|
|
|
hs.c.cipherSuite, hs.hello13.cipherSuite = hs.suite.id, hs.suite.id
|
2016-11-05 00:07:36 +00:00
|
|
|
hs.c.clientHello = hs.clientHello.marshal()
|
2016-11-06 17:01:12 +00:00
|
|
|
|
|
|
|
// When picking the group for the handshake, priority is given to groups
|
|
|
|
// that the client provided a keyShare for, so to avoid a round-trip.
|
|
|
|
// After that the order of CurvePreferences is respected.
|
|
|
|
var ks keyShare
|
2016-12-05 17:15:16 +00:00
|
|
|
CurvePreferenceLoop:
|
2016-11-06 17:01:12 +00:00
|
|
|
for _, curveID := range config.curvePreferences() {
|
|
|
|
for _, keyShare := range hs.clientHello.keyShares {
|
|
|
|
if curveID == keyShare.group {
|
|
|
|
ks = keyShare
|
2016-12-05 17:15:16 +00:00
|
|
|
break CurvePreferenceLoop
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if ks.group == 0 {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
|
|
|
|
}
|
|
|
|
|
2017-02-07 16:47:02 +00:00
|
|
|
if committer, ok := c.conn.(Committer); ok {
|
|
|
|
if err := committer.Commit(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
privateKey, serverKS, err := config.generateKeyShare(ks.group)
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
hs.hello13.keyShare = serverKS
|
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
hash := hashForSuite(hs.suite)
|
2016-11-06 17:01:12 +00:00
|
|
|
hashSize := hash.Size()
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule = newKeySchedule13(hs.suite)
|
2016-11-06 17:01:12 +00:00
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
// Check for PSK and update key schedule with new early secret key
|
|
|
|
isResumed, pskAlert := hs.checkPSK()
|
2017-01-16 12:23:17 +00:00
|
|
|
switch {
|
|
|
|
case pskAlert != alertSuccess:
|
|
|
|
c.sendAlert(pskAlert)
|
|
|
|
return errors.New("tls: invalid client PSK")
|
2017-09-18 16:01:36 +01:00
|
|
|
case !isResumed:
|
|
|
|
// apply an empty PSK if not resumed.
|
|
|
|
hs.keySchedule.setSecret(nil)
|
|
|
|
case isResumed:
|
2017-01-16 12:23:17 +00:00
|
|
|
c.didResume = true
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(hs.clientHello.marshal())
|
2016-11-25 21:46:50 +00:00
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient)
|
2016-11-25 21:46:50 +00:00
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
ecdheSecret := deriveECDHESecret(ks, privateKey)
|
|
|
|
if ecdheSecret == nil {
|
|
|
|
c.sendAlert(alertIllegalParameter)
|
|
|
|
return errors.New("tls: bad ECDHE client share")
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(hs.hello13.marshal())
|
2016-11-06 17:01:12 +00:00
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, hs.hello13.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.setSecret(ecdheSecret)
|
|
|
|
clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
|
2016-11-25 21:46:50 +00:00
|
|
|
hs.hsClientCipher = clientCipher
|
2017-09-18 16:01:36 +01:00
|
|
|
serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
|
2016-11-06 17:01:12 +00:00
|
|
|
c.out.setCipher(c.vers, serverCipher)
|
|
|
|
|
2016-11-25 21:46:50 +00:00
|
|
|
serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize)
|
|
|
|
hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize)
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(hs.hello13Enc.marshal())
|
2016-11-06 17:01:12 +00:00
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-01-16 12:23:17 +00:00
|
|
|
if !c.didResume {
|
2016-11-21 22:25:27 +00:00
|
|
|
if err := hs.sendCertificate13(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
|
2016-11-06 17:01:12 +00:00
|
|
|
serverFinished := &finishedMsg{
|
|
|
|
verifyData: verifyData,
|
|
|
|
}
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(serverFinished.marshal())
|
2016-11-06 17:01:12 +00:00
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.setSecret(nil) // derive master secret
|
|
|
|
hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
|
|
|
|
serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
|
2016-11-21 22:25:27 +00:00
|
|
|
c.out.setCipher(c.vers, serverCipher)
|
|
|
|
|
2017-01-18 17:13:07 +00:00
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
return c.sendAlert(alertUnexpectedMessage)
|
|
|
|
}
|
2016-11-25 21:46:50 +00:00
|
|
|
if hs.hello13Enc.earlyData {
|
|
|
|
c.in.setCipher(c.vers, earlyClientCipher)
|
|
|
|
c.phase = readingEarlyData
|
|
|
|
} else if hs.clientHello.earlyData {
|
|
|
|
c.in.setCipher(c.vers, hs.hsClientCipher)
|
|
|
|
c.phase = discardingEarlyData
|
|
|
|
} else {
|
|
|
|
c.in.setCipher(c.vers, hs.hsClientCipher)
|
|
|
|
c.phase = waitingClientFinished
|
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// readClientFinished13 is called when, on the second flight of the client,
|
|
|
|
// a handshake message is received. This might be immediately or after the
|
|
|
|
// early data. Once done it sends the session tickets. Under c.in lock.
|
|
|
|
func (hs *serverHandshakeState) readClientFinished13() error {
|
|
|
|
c := hs.c
|
2016-11-06 17:01:12 +00:00
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
c.phase = readingClientFinished
|
2016-11-06 17:01:12 +00:00
|
|
|
msg, err := c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
clientFinished, ok := msg.(*finishedMsg)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(clientFinished, msg)
|
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
hash := hashForSuite(hs.suite)
|
2017-09-18 16:01:36 +01:00
|
|
|
expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey)
|
2016-11-06 17:01:12 +00:00
|
|
|
if len(expectedVerifyData) != len(clientFinished.verifyData) ||
|
|
|
|
subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
|
2017-01-16 12:23:17 +00:00
|
|
|
c.sendAlert(alertDecryptError)
|
2016-11-06 17:01:12 +00:00
|
|
|
return errors.New("tls: client's Finished message is incorrect")
|
|
|
|
}
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(clientFinished.marshal())
|
2016-11-06 17:01:12 +00:00
|
|
|
|
2016-11-25 21:46:50 +00:00
|
|
|
c.hs = nil // Discard the server handshake state
|
2017-01-18 17:13:07 +00:00
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
return c.sendAlert(alertUnexpectedMessage)
|
|
|
|
}
|
2016-11-25 21:46:50 +00:00
|
|
|
c.in.setCipher(c.vers, hs.appClientCipher)
|
|
|
|
c.in.traceErr, c.out.traceErr = nil, nil
|
2016-12-05 22:11:46 +00:00
|
|
|
c.phase = handshakeConfirmed
|
|
|
|
atomic.StoreInt32(&c.handshakeConfirmed, 1)
|
|
|
|
|
|
|
|
// Any read operation after handshakeRunning and before handshakeConfirmed
|
|
|
|
// will be holding this lock, which we release as soon as the confirmation
|
|
|
|
// happens, even if the Read call might do more work.
|
|
|
|
c.confirmMutex.Unlock()
|
2016-11-23 03:23:34 +00:00
|
|
|
|
2017-02-22 21:56:04 +00:00
|
|
|
return hs.sendSessionTicket13() // TODO: do in a goroutine
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (hs *serverHandshakeState) sendCertificate13() error {
|
|
|
|
c := hs.c
|
|
|
|
|
2017-02-03 19:36:10 +00:00
|
|
|
certEntries := []certificateEntry{}
|
|
|
|
for _, cert := range hs.cert.Certificate {
|
|
|
|
certEntries = append(certEntries, certificateEntry{data: cert})
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
2017-02-03 19:36:10 +00:00
|
|
|
if len(certEntries) > 0 && hs.clientHello.ocspStapling {
|
|
|
|
certEntries[0].ocspStaple = hs.cert.OCSPStaple
|
|
|
|
}
|
|
|
|
if len(certEntries) > 0 && hs.clientHello.scts {
|
|
|
|
certEntries[0].sctList = hs.cert.SignedCertificateTimestamps
|
|
|
|
}
|
|
|
|
certMsg := &certificateMsg13{certificates: certEntries}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(certMsg.marshal())
|
2016-11-21 22:25:27 +00:00
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sigScheme, err := hs.selectTLS13SignatureScheme()
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sigHash := hashForSignatureScheme(sigScheme)
|
|
|
|
opts := crypto.SignerOpts(sigHash)
|
|
|
|
if signatureSchemeIsPSS(sigScheme) {
|
|
|
|
opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
|
2016-11-21 22:25:27 +00:00
|
|
|
signature, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
verifyMsg := &certificateVerifyMsg{
|
|
|
|
hasSignatureAndHash: true,
|
|
|
|
signatureAndHash: sigSchemeToSigAndHash(sigScheme),
|
|
|
|
signature: signature,
|
|
|
|
}
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.write(verifyMsg.marshal())
|
2016-11-21 22:25:27 +00:00
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-06 17:01:12 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-11-25 21:46:50 +00:00
|
|
|
func (c *Conn) handleEndOfEarlyData() {
|
|
|
|
if c.phase != readingEarlyData || c.vers < VersionTLS13 {
|
|
|
|
c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.phase = waitingClientFinished
|
2017-01-18 17:13:07 +00:00
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
|
|
|
|
return
|
|
|
|
}
|
2016-11-25 21:46:50 +00:00
|
|
|
c.in.setCipher(c.vers, c.hs.hsClientCipher)
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
// selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
|
|
|
|
// based on the certificate type and client supported schemes. If no overlap is found,
|
|
|
|
// a fallback is selected.
|
|
|
|
//
|
|
|
|
// See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
|
|
|
|
func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
|
|
|
|
var supportedSchemes []SignatureScheme
|
|
|
|
signer, ok := hs.cert.PrivateKey.(crypto.Signer)
|
|
|
|
if !ok {
|
|
|
|
return 0, errors.New("tls: certificate private key does not implement crypto.Signer")
|
|
|
|
}
|
|
|
|
pk := signer.Public()
|
|
|
|
if _, ok := pk.(*rsa.PublicKey); ok {
|
|
|
|
sigScheme = PSSWithSHA256
|
|
|
|
supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
|
|
|
|
} else if pk, ok := pk.(*ecdsa.PublicKey); ok {
|
|
|
|
switch pk.Curve {
|
|
|
|
case elliptic.P256():
|
|
|
|
sigScheme = ECDSAWithP256AndSHA256
|
|
|
|
supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
|
|
|
|
case elliptic.P384():
|
|
|
|
sigScheme = ECDSAWithP384AndSHA384
|
|
|
|
supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
|
|
|
|
case elliptic.P521():
|
|
|
|
sigScheme = ECDSAWithP521AndSHA512
|
|
|
|
supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
|
|
|
|
default:
|
|
|
|
return 0, errors.New("tls: unknown ECDSA certificate curve")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return 0, errors.New("tls: unknown certificate key type")
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ss := range supportedSchemes {
|
|
|
|
for _, cs := range hs.clientHello.signatureAndHashes {
|
|
|
|
if ss == sigAndHashToSigScheme(cs) {
|
|
|
|
return ss, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sigScheme, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func sigSchemeToSigAndHash(s SignatureScheme) (sah signatureAndHash) {
|
|
|
|
sah.hash = byte(s >> 8)
|
|
|
|
sah.signature = byte(s)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func sigAndHashToSigScheme(sah signatureAndHash) SignatureScheme {
|
|
|
|
return SignatureScheme(sah.hash)<<8 | SignatureScheme(sah.signature)
|
|
|
|
}
|
|
|
|
|
|
|
|
func signatureSchemeIsPSS(s SignatureScheme) bool {
|
|
|
|
return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
|
|
|
|
}
|
|
|
|
|
|
|
|
// hashForSignatureScheme returns the Hash used by a SignatureScheme which is
|
|
|
|
// supported by selectTLS13SignatureScheme.
|
|
|
|
func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
|
|
|
|
switch ss {
|
|
|
|
case PSSWithSHA256, ECDSAWithP256AndSHA256:
|
|
|
|
return crypto.SHA256
|
|
|
|
case PSSWithSHA384, ECDSAWithP384AndSHA384:
|
|
|
|
return crypto.SHA384
|
|
|
|
case PSSWithSHA512, ECDSAWithP521AndSHA512:
|
|
|
|
return crypto.SHA512
|
|
|
|
default:
|
|
|
|
panic("unsupported SignatureScheme passed to hashForSignatureScheme")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
func hashForSuite(suite *cipherSuite) crypto.Hash {
|
|
|
|
if suite.flags&suiteSHA384 != 0 {
|
|
|
|
return crypto.SHA384
|
|
|
|
}
|
|
|
|
return crypto.SHA256
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
|
|
|
|
message := bytes.Repeat([]byte{32}, 64)
|
|
|
|
message = append(message, context...)
|
|
|
|
message = append(message, 0)
|
|
|
|
message = append(message, data...)
|
|
|
|
h := hash.New()
|
|
|
|
h.Write(message)
|
|
|
|
return h.Sum(nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
|
|
|
|
if curveID == X25519 {
|
|
|
|
var scalar, public [32]byte
|
|
|
|
if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
curve25519.ScalarBaseMult(&public, &scalar)
|
|
|
|
return scalar[:], keyShare{group: curveID, data: public[:]}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
curve, ok := curveForCurveID(curveID)
|
|
|
|
if !ok {
|
|
|
|
return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
|
|
|
|
}
|
|
|
|
|
|
|
|
privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
|
|
|
|
if err != nil {
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
ecdhePublic := elliptic.Marshal(curve, x, y)
|
|
|
|
|
|
|
|
return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
|
|
|
|
}
|
|
|
|
|
2017-06-06 19:37:09 +01:00
|
|
|
func deriveECDHESecret(ks keyShare, secretKey []byte) []byte {
|
2016-11-06 17:01:12 +00:00
|
|
|
if ks.group == X25519 {
|
|
|
|
if len(ks.data) != 32 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var theirPublic, sharedKey, scalar [32]byte
|
|
|
|
copy(theirPublic[:], ks.data)
|
2017-06-06 19:37:09 +01:00
|
|
|
copy(scalar[:], secretKey)
|
2016-11-06 17:01:12 +00:00
|
|
|
curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
|
|
|
|
return sharedKey[:]
|
|
|
|
}
|
|
|
|
|
|
|
|
curve, ok := curveForCurveID(ks.group)
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
x, y := elliptic.Unmarshal(curve, ks.data)
|
|
|
|
if x == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2017-06-06 19:37:09 +01:00
|
|
|
x, _ = curve.ScalarMult(x, y, secretKey)
|
2016-11-06 17:01:12 +00:00
|
|
|
xBytes := x.Bytes()
|
|
|
|
curveSize := (curve.Params().BitSize + 8 - 1) >> 3
|
|
|
|
if len(xBytes) == curveSize {
|
|
|
|
return xBytes
|
|
|
|
}
|
|
|
|
buf := make([]byte, curveSize)
|
|
|
|
copy(buf[len(buf)-len(xBytes):], xBytes)
|
|
|
|
return buf
|
|
|
|
}
|
|
|
|
|
|
|
|
func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
|
|
|
|
hkdfLabel := make([]byte, 4+len("TLS 1.3, ")+len(label)+len(hashValue))
|
|
|
|
hkdfLabel[0] = byte(L >> 8)
|
|
|
|
hkdfLabel[1] = byte(L)
|
|
|
|
hkdfLabel[2] = byte(len("TLS 1.3, ") + len(label))
|
|
|
|
copy(hkdfLabel[3:], "TLS 1.3, ")
|
|
|
|
z := hkdfLabel[3+len("TLS 1.3, "):]
|
|
|
|
copy(z, label)
|
|
|
|
z = z[len(label):]
|
|
|
|
z[0] = byte(len(hashValue))
|
|
|
|
copy(z[1:], hashValue)
|
|
|
|
|
|
|
|
return hkdfExpand(hash, secret, hkdfLabel, L)
|
|
|
|
}
|
2016-11-07 06:48:40 +00:00
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte {
|
|
|
|
h := hmac.New(f.New, key)
|
|
|
|
h.Write(hash.Sum(nil))
|
|
|
|
return h.Sum(nil)
|
|
|
|
}
|
|
|
|
|
2016-11-21 22:25:27 +00:00
|
|
|
// Maximum allowed mismatch between the stated age of a ticket
|
|
|
|
// and the server-observed one. See
|
|
|
|
// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2.
|
|
|
|
const ticketAgeSkewAllowance = 10 * time.Second
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
// checkPSK tries to resume using a PSK, returning true (and updating the
|
|
|
|
// early secret in the key schedule) if the PSK was used and false otherwise.
|
|
|
|
func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) {
|
2016-11-21 22:25:27 +00:00
|
|
|
if hs.c.config.SessionTicketsDisabled {
|
2017-09-18 16:01:36 +01:00
|
|
|
return false, alertSuccess
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
foundDHE := false
|
|
|
|
for _, mode := range hs.clientHello.pskKeyExchangeModes {
|
|
|
|
if mode == pskDHEKeyExchange {
|
|
|
|
foundDHE = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !foundDHE {
|
2017-09-18 16:01:36 +01:00
|
|
|
return false, alertSuccess
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
hash := hashForSuite(hs.suite)
|
2016-11-21 22:25:27 +00:00
|
|
|
hashSize := hash.Size()
|
|
|
|
for i := range hs.clientHello.psks {
|
|
|
|
sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...)
|
2017-02-22 21:56:04 +00:00
|
|
|
if hs.c.config.SessionTicketSealer != nil {
|
|
|
|
var ok bool
|
|
|
|
sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
sessionTicket, _ = hs.c.decryptTicket(sessionTicket)
|
|
|
|
if sessionTicket == nil {
|
|
|
|
continue
|
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
s := &sessionState13{}
|
2017-02-22 21:56:04 +00:00
|
|
|
if s.unmarshal(sessionTicket) != alertSuccess {
|
2016-11-21 22:25:27 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
if s.vers != hs.c.vers {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond
|
|
|
|
serverAge := time.Since(time.Unix(int64(s.createdAt), 0))
|
|
|
|
if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
|
2016-12-05 22:41:00 +00:00
|
|
|
// XXX: NSS is off spec and sends obfuscated_ticket_age as seconds
|
|
|
|
clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second
|
|
|
|
if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
|
|
|
|
continue
|
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
2016-11-25 21:46:50 +00:00
|
|
|
|
|
|
|
// This enforces the stricter 0-RTT requirements on all ticket uses.
|
|
|
|
// The benefit of using PSK+ECDHE without 0-RTT are small enough that
|
2016-11-30 00:11:10 +00:00
|
|
|
// we can give them up in the edge case of changed suite or ALPN or SNI.
|
2016-11-25 21:46:50 +00:00
|
|
|
if s.suite != hs.suite.id {
|
|
|
|
continue
|
|
|
|
}
|
2016-11-30 00:11:10 +00:00
|
|
|
if s.alpnProtocol != hs.c.clientProtocol {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if s.SNI != hs.c.serverName {
|
2016-11-21 22:25:27 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
hs.keySchedule.setSecret(s.resumptionSecret)
|
|
|
|
binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder)
|
2016-11-21 22:25:27 +00:00
|
|
|
binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize)
|
|
|
|
chHash := hash.New()
|
|
|
|
chHash.Write(hs.clientHello.rawTruncated)
|
2016-11-23 03:23:34 +00:00
|
|
|
expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey)
|
2016-11-21 22:25:27 +00:00
|
|
|
|
2017-01-16 12:23:17 +00:00
|
|
|
if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 {
|
2017-09-18 16:01:36 +01:00
|
|
|
return false, alertDecryptError
|
2017-01-16 12:23:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if i == 0 && hs.clientHello.earlyData {
|
|
|
|
// This is a ticket intended to be used for 0-RTT
|
|
|
|
if s.maxEarlyDataLen == 0 {
|
|
|
|
// But we had not tagged it as such.
|
2017-09-18 16:01:36 +01:00
|
|
|
return false, alertIllegalParameter
|
2017-01-16 12:23:17 +00:00
|
|
|
}
|
|
|
|
if hs.c.config.Accept0RTTData {
|
2017-02-09 20:50:39 +00:00
|
|
|
hs.c.binder = expectedBinder
|
2017-01-16 12:23:17 +00:00
|
|
|
hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen)
|
|
|
|
hs.hello13Enc.earlyData = true
|
2016-11-30 00:11:10 +00:00
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
2017-01-16 12:23:17 +00:00
|
|
|
hs.hello13.psk = true
|
|
|
|
hs.hello13.pskIdentity = uint16(i)
|
2017-09-18 16:01:36 +01:00
|
|
|
return true, alertSuccess
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
return false, alertSuccess
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
2016-11-23 03:23:34 +00:00
|
|
|
func (hs *serverHandshakeState) sendSessionTicket13() error {
|
2016-11-21 22:25:27 +00:00
|
|
|
c := hs.c
|
|
|
|
if c.config.SessionTicketsDisabled {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
foundDHE := false
|
|
|
|
for _, mode := range hs.clientHello.pskKeyExchangeModes {
|
|
|
|
if mode == pskDHEKeyExchange {
|
|
|
|
foundDHE = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !foundDHE {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:01:36 +01:00
|
|
|
resumptionSecret := hs.keySchedule.deriveSecret(secretResumption)
|
2016-11-21 22:25:27 +00:00
|
|
|
|
|
|
|
ageAddBuf := make([]byte, 4)
|
|
|
|
sessionState := &sessionState13{
|
2017-04-09 17:31:24 +01:00
|
|
|
vers: c.vers,
|
|
|
|
suite: hs.suite.id,
|
2016-11-21 22:25:27 +00:00
|
|
|
createdAt: uint64(time.Now().Unix()),
|
|
|
|
resumptionSecret: resumptionSecret,
|
2016-11-30 00:11:10 +00:00
|
|
|
alpnProtocol: c.clientProtocol,
|
|
|
|
SNI: c.serverName,
|
|
|
|
maxEarlyDataLen: c.config.Max0RTTDataSize,
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
2017-01-30 18:03:46 +00:00
|
|
|
for i := 0; i < numSessionTickets; i++ {
|
2017-04-09 17:31:24 +01:00
|
|
|
if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 |
|
|
|
|
uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3])
|
2017-02-22 21:56:04 +00:00
|
|
|
ticket := sessionState.marshal()
|
|
|
|
var err error
|
|
|
|
if c.config.SessionTicketSealer != nil {
|
|
|
|
cs := c.ConnectionState()
|
|
|
|
ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket)
|
|
|
|
} else {
|
|
|
|
ticket, err = c.encryptTicket(ticket)
|
|
|
|
}
|
2017-01-30 18:03:46 +00:00
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
2017-02-22 21:56:04 +00:00
|
|
|
if ticket == nil {
|
|
|
|
continue
|
|
|
|
}
|
2017-01-30 18:03:46 +00:00
|
|
|
ticketMsg := &newSessionTicketMsg13{
|
|
|
|
lifetime: 24 * 3600, // TODO(filippo)
|
|
|
|
maxEarlyDataLength: c.config.Max0RTTDataSize,
|
|
|
|
withEarlyDataInfo: c.config.Max0RTTDataSize > 0,
|
|
|
|
ageAdd: sessionState.ageAdd,
|
|
|
|
ticket: ticket,
|
|
|
|
}
|
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-11-07 06:48:40 +00:00
|
|
|
func (hs *serverHandshakeState) traceErr(err error) {
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if os.Getenv("TLSDEBUG") == "error" {
|
|
|
|
if hs != nil && hs.clientHello != nil {
|
|
|
|
os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal()))
|
|
|
|
} else if err == io.EOF {
|
|
|
|
return // don't stack trace on EOF before CH
|
|
|
|
}
|
|
|
|
fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack())
|
|
|
|
}
|
2017-01-24 18:56:43 +00:00
|
|
|
if os.Getenv("TLSDEBUG") == "short" {
|
|
|
|
var pcs [4]uintptr
|
|
|
|
frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])])
|
|
|
|
for {
|
|
|
|
frame, more := frames.Next()
|
|
|
|
if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" &&
|
|
|
|
frame.Function != "crypto/tls.(*Conn).sendAlertLocked" &&
|
|
|
|
frame.Function != "crypto/tls.(*Conn).sendAlert" {
|
|
|
|
file := frame.File[strings.LastIndex(frame.File, "/")+1:]
|
|
|
|
log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !more {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-11-07 06:48:40 +00:00
|
|
|
}
|