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
|
|
|
|
2018-10-05 22:43:00 +01:00
|
|
|
sidh "github_com/cloudflare/sidh/sidh"
|
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
|
2018-10-05 15:06:44 +01:00
|
|
|
|
|
|
|
const (
|
2018-10-05 22:43:00 +01:00
|
|
|
x25519SharedSecretSz = 32
|
|
|
|
|
|
|
|
P503PubKeySz = 378
|
|
|
|
P503PrvKeySz = 32
|
|
|
|
P503SharedSecretSz = 126
|
2018-12-05 14:20:21 +00:00
|
|
|
SIDHp503Curve25519PubKeySz = x25519SharedSecretSz + P503PubKeySz
|
|
|
|
SIDHp503Curve25519PrvKeySz = x25519SharedSecretSz + P503PrvKeySz
|
|
|
|
SIDHp503Curve25519SharedKeySz = x25519SharedSecretSz + P503SharedSecretSz
|
2018-10-05 15:06:44 +01:00
|
|
|
)
|
2017-09-18 15:55:55 +01:00
|
|
|
|
|
|
|
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.
|
2017-09-18 16:50:43 +01:00
|
|
|
clientRandom []byte // Used for keylogging, nil if keylogging is disabled.
|
|
|
|
config *Config // Used for KeyLogWriter callback, nil if keylogging is disabled.
|
2017-09-18 15:55:55 +01:00
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
// Interface implemented by key exchange strategies
|
|
|
|
type kex interface {
|
2018-10-05 22:43:00 +01:00
|
|
|
// c - context of current TLS handshake, groupId - ID of an algorithm
|
|
|
|
// (curve/field) being chosen for key agreement. Methods implmenting an
|
|
|
|
// interface always assume that provided groupId is correct.
|
|
|
|
//
|
|
|
|
// In case of success, function returns secret key and ephemeral key. Otherwise
|
|
|
|
// error is set.
|
|
|
|
generate(c *Conn, groupId CurveID) ([]byte, keyShare, error)
|
2019-02-25 17:25:16 +00:00
|
|
|
// keyAgreementClient declares an API for implementing shared secret agreement on
|
|
|
|
// the client side. `c` is a context of current TLS handshake, `ks` is a public key
|
|
|
|
// received from the server, ``privateKey`` client private key.
|
|
|
|
// Function returns shared secret in case of success or non nil error otherwise.
|
|
|
|
keyAgreementClient(c *Conn, ks keyShare, privateKey []byte) ([]byte, error)
|
|
|
|
// keyAgreementServer declares an API for implementing shared secret agreement on
|
|
|
|
// the server side. `c` context of current TLS handshake, `ks` is a public key
|
|
|
|
// received from the client side of the connection, ``privateKey`` is a private key
|
|
|
|
// of a server.
|
|
|
|
// Function returns secret shared between parties and public value to exchange
|
|
|
|
// between parties. In case of failure `error` must be set.
|
|
|
|
keyAgreementServer(c *Conn, ks keyShare) ([]byte, keyShare, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// defaultServerKEX is an abstract class defining default, common behaviour on
|
|
|
|
// a server side.
|
|
|
|
type defaultServerKEX struct{}
|
|
|
|
|
|
|
|
// defaultServerKEX is an abstract class defining default implementation of
|
|
|
|
// server side key agreement. It generates ephemeral key and uses it together
|
|
|
|
// with client public part in order to calculate shared secret.
|
|
|
|
func (defaultServerKEX) keyAgreementServer(c *Conn, clientKS keyShare) ([]byte, keyShare, error) {
|
|
|
|
privateKey, publicKey, err := c.generateKeyShare(clientKS.group)
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use same key agreement implementation as on the client side
|
|
|
|
ss, err := c.keyAgreementClient(clientKS, privateKey)
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertIllegalParameter)
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
return ss, publicKey, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Key Exchange strategies per curve type
|
2019-02-25 17:25:16 +00:00
|
|
|
type kexNIST struct{ defaultServerKEX } // Used by NIST curves; P-256, P-384, P-512
|
|
|
|
type kexX25519 struct{ defaultServerKEX } // Used by X25519
|
|
|
|
type kexSIDHp503 struct{ defaultServerKEX } // Used by SIDH/P503
|
2018-12-05 14:20:21 +00:00
|
|
|
type kexHybridSIDHp503X25519 struct {
|
2019-02-25 17:25:16 +00:00
|
|
|
defaultServerKEX
|
2018-12-05 14:20:21 +00:00
|
|
|
classicKEX kexX25519
|
|
|
|
pqKEX kexSIDHp503
|
|
|
|
} // Used by SIDH-ECDH hybrid scheme
|
2018-10-05 22:43:00 +01:00
|
|
|
|
|
|
|
// Routing map for key exchange strategies
|
2019-02-25 17:25:16 +00:00
|
|
|
var kexStrat = map[CurveID]kex{
|
|
|
|
CurveP256: &kexNIST{},
|
|
|
|
CurveP384: &kexNIST{},
|
|
|
|
CurveP521: &kexNIST{},
|
2018-10-05 22:43:00 +01:00
|
|
|
X25519: &kexX25519{},
|
2018-12-05 14:20:21 +00:00
|
|
|
HybridSIDHp503Curve25519: &kexHybridSIDHp503X25519{},
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
2017-09-18 16:50:43 +01:00
|
|
|
func newKeySchedule13(suite *cipherSuite, config *Config, clientRandom []byte) *keySchedule13 {
|
|
|
|
if config.KeyLogWriter == nil {
|
|
|
|
clientRandom = nil
|
|
|
|
config = nil
|
|
|
|
}
|
2017-09-18 15:55:55 +01:00
|
|
|
return &keySchedule13{
|
|
|
|
suite: suite,
|
|
|
|
transcriptHash: hashForSuite(suite).New(),
|
2017-09-18 16:50:43 +01:00
|
|
|
clientRandom: clientRandom,
|
|
|
|
config: config,
|
2017-09-18 15:55:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
2017-11-11 04:41:25 +00:00
|
|
|
if salt != nil {
|
|
|
|
h0 := hash.New().Sum(nil)
|
|
|
|
salt = hkdfExpandLabel(hash, salt, h0, "derived", hash.Size())
|
|
|
|
}
|
2017-09-18 15:55:55 +01:00
|
|
|
ks.secret = hkdfExtract(hash, secret, salt)
|
|
|
|
}
|
|
|
|
|
2018-10-05 22:43:00 +01:00
|
|
|
// Depending on role returns pair of key variant to be used by
|
|
|
|
// local and remote process.
|
|
|
|
func getSidhKeyVariant(isClient bool) (sidh.KeyVariant, sidh.KeyVariant) {
|
|
|
|
if isClient {
|
|
|
|
return sidh.KeyVariant_SIDH_A, sidh.KeyVariant_SIDH_B
|
|
|
|
}
|
|
|
|
return sidh.KeyVariant_SIDH_B, sidh.KeyVariant_SIDH_A
|
|
|
|
}
|
|
|
|
|
2017-09-18 15:55:55 +01:00
|
|
|
// write appends the data to the transcript hash context.
|
|
|
|
func (ks *keySchedule13) write(data []byte) {
|
|
|
|
ks.handshakeCtx = nil
|
|
|
|
ks.transcriptHash.Write(data)
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:50:43 +01:00
|
|
|
func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label, keylogType string) {
|
2017-09-18 15:55:55 +01:00
|
|
|
switch secretLabel {
|
|
|
|
case secretResumptionPskBinder:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "res binder"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretEarlyClient:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "c e traffic"
|
2017-09-18 16:50:43 +01:00
|
|
|
keylogType = "CLIENT_EARLY_TRAFFIC_SECRET"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretHandshakeClient:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "c hs traffic"
|
2017-09-18 16:50:43 +01:00
|
|
|
keylogType = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretHandshakeServer:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "s hs traffic"
|
2017-09-18 16:50:43 +01:00
|
|
|
keylogType = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretApplicationClient:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "c ap traffic"
|
2017-09-18 16:50:43 +01:00
|
|
|
keylogType = "CLIENT_TRAFFIC_SECRET_0"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretApplicationServer:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "s ap traffic"
|
2017-09-18 16:50:43 +01:00
|
|
|
keylogType = "SERVER_TRAFFIC_SECRET_0"
|
2017-09-18 15:55:55 +01:00
|
|
|
case secretResumption:
|
2017-11-11 04:41:25 +00:00
|
|
|
label = "res master"
|
2017-09-18 15:55:55 +01:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// deriveSecret returns the secret derived from the handshake context and label.
|
|
|
|
func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte {
|
2017-09-18 16:50:43 +01:00
|
|
|
label, keylogType := ks.getLabel(secretLabel)
|
2017-09-18 15:55:55 +01:00
|
|
|
if ks.handshakeCtx == nil {
|
|
|
|
ks.handshakeCtx = ks.transcriptHash.Sum(nil)
|
|
|
|
}
|
|
|
|
hash := hashForSuite(ks.suite)
|
2017-09-18 16:50:43 +01:00
|
|
|
secret := hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size())
|
|
|
|
if keylogType != "" && ks.config != nil {
|
|
|
|
ks.config.writeKeyLog(keylogType, ks.clientRandom, secret)
|
|
|
|
}
|
|
|
|
return secret
|
2017-09-18 15:55:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2017-11-30 18:43:18 +00:00
|
|
|
iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", ks.suite.ivLen)
|
2017-09-18 15:55:55 +01:00
|
|
|
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
|
|
|
|
|
2017-11-24 18:10:50 +00:00
|
|
|
hs.c.cipherSuite, hs.hello.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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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:50:43 +01:00
|
|
|
hs.keySchedule = newKeySchedule13(hs.suite, config, hs.clientHello.random)
|
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())
|
|
|
|
earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient)
|
2016-11-25 21:46:50 +00:00
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
if ks.group == 0 {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
|
|
|
|
}
|
|
|
|
sharedSecret, serverKS, err := c.keyAgreementServer(ks)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
2019-02-25 17:25:16 +00:00
|
|
|
hs.hello.keyShare = serverKS
|
2016-11-06 17:01:12 +00:00
|
|
|
|
2017-11-24 18:10:50 +00:00
|
|
|
hs.keySchedule.write(hs.hello.marshal())
|
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
|
2016-11-06 17:01:12 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-11-12 07:44:45 +00:00
|
|
|
// middlebox compatibility mode: send CCS after first handshake message
|
|
|
|
if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
hs.keySchedule.setSecret(sharedSecret)
|
2017-09-18 16:01:36 +01:00
|
|
|
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)
|
|
|
|
|
2018-03-26 16:58:09 +01:00
|
|
|
// EncryptedExtensions
|
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
|
|
|
|
}
|
|
|
|
|
2018-03-26 16:58:09 +01:00
|
|
|
// TODO: we should have 2 separated methods - one for full-handshake and the other for PSK-handshake
|
2017-01-16 12:23:17 +00:00
|
|
|
if !c.didResume {
|
2018-03-26 16:58:09 +01:00
|
|
|
// Server MUST NOT send CertificateRequest if authenticating with PSK
|
2018-03-26 17:04:10 +01:00
|
|
|
if c.config.ClientAuth >= RequestClientCert {
|
2018-03-26 16:58:09 +01:00
|
|
|
|
|
|
|
certReq := new(certificateRequestMsg13)
|
|
|
|
// extension 'signature_algorithms' MUST be specified
|
|
|
|
certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms13
|
2018-06-26 14:25:45 +01:00
|
|
|
certReq.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13)
|
2018-03-26 16:58:09 +01:00
|
|
|
hs.keySchedule.write(certReq.marshal())
|
|
|
|
if _, err := hs.c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2017-09-21 11:34:37 +01:00
|
|
|
// readClientFinished13 is called during the server handshake (when no early
|
|
|
|
// data it available) or after reading all early data. It discards early data if
|
|
|
|
// the server did not accept it and then verifies the Finished message. Once
|
|
|
|
// done it sends the session tickets. Under c.in lock.
|
|
|
|
func (hs *serverHandshakeState) readClientFinished13(hasConfirmLock bool) error {
|
2016-11-23 03:23:34 +00:00
|
|
|
c := hs.c
|
2016-11-06 17:01:12 +00:00
|
|
|
|
2017-09-21 11:34:37 +01:00
|
|
|
// If the client advertised and sends early data while the server does
|
|
|
|
// not accept it, it must be fully skipped until the Finished message.
|
|
|
|
for c.phase == discardingEarlyData {
|
|
|
|
if err := c.readRecord(recordTypeApplicationData); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Assume receipt of Finished message (will be checked below).
|
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
c.phase = waitingClientFinished
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the client sends early data followed by a Finished message (but
|
|
|
|
// no end_of_early_data), the server MUST terminate the connection.
|
|
|
|
if c.phase != waitingClientFinished {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return errors.New("tls: did not expect Client Finished yet")
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2018-03-26 16:58:09 +01:00
|
|
|
// client authentication
|
2018-10-12 14:27:02 +01:00
|
|
|
// (4.4.2) Client MUST send certificate msg if requested by server
|
|
|
|
if c.config.ClientAuth >= RequestClientCert && !c.didResume {
|
|
|
|
certMsg, ok := msg.(*certificateMsg13)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertCertificateRequired)
|
2018-03-26 17:04:10 +01:00
|
|
|
return unexpectedMessageError(certMsg, msg)
|
|
|
|
}
|
|
|
|
|
2018-03-26 16:58:09 +01:00
|
|
|
hs.keySchedule.write(certMsg.marshal())
|
2018-02-27 18:53:21 +00:00
|
|
|
certs := getCertsFromEntries(certMsg.certificates)
|
|
|
|
pubKey, err := hs.processCertsFromClient(certs)
|
2018-03-26 16:58:09 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-10-12 14:27:02 +01:00
|
|
|
if len(certs) > 0 {
|
|
|
|
// 4.4.3: CertificateVerify MUST appear immediately after Certificate msg
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-03-26 16:58:09 +01:00
|
|
|
|
2018-10-12 14:27:02 +01:00
|
|
|
certVerify, ok := msg.(*certificateVerifyMsg)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(certVerify, msg)
|
|
|
|
}
|
2018-03-26 16:58:09 +01:00
|
|
|
|
2018-10-12 14:27:02 +01:00
|
|
|
err, alertCode := verifyPeerHandshakeSignature(
|
|
|
|
certVerify,
|
|
|
|
pubKey,
|
|
|
|
supportedSignatureAlgorithms13,
|
|
|
|
hs.keySchedule.transcriptHash.Sum(nil),
|
|
|
|
"TLS 1.3, client CertificateVerify")
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertCode)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
hs.keySchedule.write(certVerify.marshal())
|
2018-03-26 16:58:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Read next chunk
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-06 17:01:12 +00:00
|
|
|
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.
|
2017-09-21 11:34:37 +01:00
|
|
|
// If a Handshake is pending, c.confirmMutex will never be locked as
|
|
|
|
// ConfirmHandshake will wait for the handshake to complete. If a
|
|
|
|
// handshake was complete, and this was a confirmation, unlock
|
|
|
|
// c.confirmMutex now to allow readers to proceed.
|
|
|
|
if hasConfirmLock {
|
|
|
|
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
|
|
|
|
}
|
2018-07-03 17:57:54 +01:00
|
|
|
|
|
|
|
// If hs.delegatedCredential is set (see hs.readClientHello()) then the
|
2018-08-09 19:24:40 +01:00
|
|
|
// server is using the delegated credential extension. The DC is added as an
|
|
|
|
// extension to the end-entity certificate, i.e., the last CertificateEntry
|
|
|
|
// of Certificate.certficate_list. (For details, see
|
|
|
|
// https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.)
|
2018-07-03 17:57:54 +01:00
|
|
|
if len(certEntries) > 0 && hs.clientHello.delegatedCredential && hs.delegatedCredential != nil {
|
|
|
|
certEntries[0].delegatedCredential = hs.delegatedCredential
|
|
|
|
}
|
|
|
|
|
2017-02-03 19:36:10 +00:00
|
|
|
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))
|
2018-07-03 17:57:54 +01:00
|
|
|
signature, err := hs.privateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
|
2016-11-21 22:25:27 +00:00
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
verifyMsg := &certificateVerifyMsg{
|
|
|
|
hasSignatureAndHash: true,
|
2017-11-14 13:58:35 +00:00
|
|
|
signatureAlgorithm: sigScheme,
|
2016-11-21 22:25:27 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2017-12-01 14:53:26 +00:00
|
|
|
func (c *Conn) handleEndOfEarlyData() error {
|
2016-11-25 21:46:50 +00:00
|
|
|
if c.phase != readingEarlyData || c.vers < VersionTLS13 {
|
2017-12-01 14:53:26 +00:00
|
|
|
return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
|
2016-11-25 21:46:50 +00:00
|
|
|
}
|
2017-12-01 14:53:26 +00:00
|
|
|
msg, err := c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
endOfEarlyData, ok := msg.(*endOfEarlyDataMsg)
|
|
|
|
// No handshake messages are allowed after EOD.
|
|
|
|
if !ok || c.hand.Len() > 0 {
|
|
|
|
return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
|
2017-01-18 17:13:07 +00:00
|
|
|
}
|
2017-12-01 14:53:26 +00:00
|
|
|
c.hs.keySchedule.write(endOfEarlyData.marshal())
|
|
|
|
c.phase = waitingClientFinished
|
2016-11-25 21:46:50 +00:00
|
|
|
c.in.setCipher(c.vers, c.hs.hsClientCipher)
|
2017-12-01 14:53:26 +00:00
|
|
|
return nil
|
2016-11-25 21:46:50 +00:00
|
|
|
}
|
|
|
|
|
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
|
2018-07-03 17:57:54 +01:00
|
|
|
signer, ok := hs.privateKey.(crypto.Signer)
|
2016-11-06 17:01:12 +00:00
|
|
|
if !ok {
|
2018-07-03 17:57:54 +01:00
|
|
|
return 0, errors.New("tls: private key does not implement crypto.Signer")
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
|
|
|
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 {
|
2017-11-14 13:58:35 +00:00
|
|
|
for _, cs := range hs.clientHello.supportedSignatureAlgorithms {
|
|
|
|
if ss == cs {
|
2016-11-06 17:01:12 +00:00
|
|
|
return ss, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return sigScheme, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
// generateKeyShare generates keypair. On success it returns private key and keyShare
|
|
|
|
// structure with keyShare.group set to supported group ID (as per 4.2.7 in RFC 8446)
|
|
|
|
// and keyShare.data set to public key, third argument is nil. On failure, third returned
|
|
|
|
// value (an error) contains error message and first two values are undefined.
|
2018-10-07 15:55:34 +01:00
|
|
|
func (c *Conn) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
|
2019-02-25 17:25:16 +00:00
|
|
|
if val, ok := kexStrat[curveID]; ok {
|
2018-10-05 22:43:00 +01:00
|
|
|
return val.generate(c, curveID)
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
2018-10-05 22:43:00 +01:00
|
|
|
return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
|
|
|
|
2018-10-05 22:43:00 +01:00
|
|
|
// DH key agreement. ks stores public key, secretKey stores private key used for ephemeral
|
|
|
|
// key agreement. Function returns shared secret in case of success or empty slice otherwise.
|
2019-02-25 17:25:16 +00:00
|
|
|
func (c *Conn) keyAgreementClient(ks keyShare, secretKey []byte) ([]byte, error) {
|
|
|
|
if val, ok := kexStrat[ks.group]; ok {
|
|
|
|
return val.keyAgreementClient(c, ks, secretKey)
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: unsupported group")
|
|
|
|
}
|
|
|
|
|
|
|
|
// keyAgreementServer generates ephemeral keypair on the on the server side
|
|
|
|
// and then uses 'keyShare' (client public key) to derive shared secret
|
|
|
|
func (c *Conn) keyAgreementServer(clientKS keyShare) ([]byte, keyShare, error) {
|
|
|
|
if val, ok := kexStrat[clientKS.group]; ok {
|
|
|
|
return val.keyAgreementServer(c, clientKS)
|
|
|
|
}
|
|
|
|
return nil, keyShare{}, errors.New("unsupported group")
|
2016-11-06 17:01:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
|
2017-11-11 04:41:25 +00:00
|
|
|
prefix := "tls13 "
|
|
|
|
hkdfLabel := make([]byte, 4+len(prefix)+len(label)+len(hashValue))
|
2016-11-06 17:01:12 +00:00
|
|
|
hkdfLabel[0] = byte(L >> 8)
|
|
|
|
hkdfLabel[1] = byte(L)
|
2017-11-11 04:41:25 +00:00
|
|
|
hkdfLabel[2] = byte(len(prefix) + len(label))
|
|
|
|
copy(hkdfLabel[3:], prefix)
|
|
|
|
z := hkdfLabel[3+len(prefix):]
|
2016-11-06 17:01:12 +00:00
|
|
|
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-11-12 02:11:32 +00:00
|
|
|
hs.keySchedule.setSecret(s.pskSecret)
|
2017-09-18 16:01:36 +01:00
|
|
|
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-11-24 18:10:50 +00:00
|
|
|
hs.hello.psk = true
|
|
|
|
hs.hello.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-11-12 02:11:32 +00:00
|
|
|
resumptionMasterSecret := hs.keySchedule.deriveSecret(secretResumption)
|
2016-11-21 22:25:27 +00:00
|
|
|
|
|
|
|
ageAddBuf := make([]byte, 4)
|
|
|
|
sessionState := &sessionState13{
|
2017-11-12 02:11:32 +00:00
|
|
|
vers: c.vers,
|
|
|
|
suite: hs.suite.id,
|
|
|
|
createdAt: uint64(time.Now().Unix()),
|
|
|
|
alpnProtocol: c.clientProtocol,
|
|
|
|
SNI: c.serverName,
|
|
|
|
maxEarlyDataLen: c.config.Max0RTTDataSize,
|
2016-11-21 22:25:27 +00:00
|
|
|
}
|
2017-11-12 02:11:32 +00:00
|
|
|
hash := hashForSuite(hs.suite)
|
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-11-12 02:11:32 +00:00
|
|
|
// ticketNonce must be a unique value for this connection.
|
|
|
|
// Assume there are no more than 255 tickets, otherwise two
|
|
|
|
// tickets might have the same PSK which could be a problem if
|
|
|
|
// one of them is compromised.
|
|
|
|
ticketNonce := []byte{byte(i)}
|
|
|
|
sessionState.pskSecret = hkdfExpandLabel(hash, resumptionMasterSecret, ticketNonce, "resumption", hash.Size())
|
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,
|
2017-11-12 02:11:32 +00:00
|
|
|
nonce: ticketNonce,
|
2017-01-30 18:03:46 +00:00
|
|
|
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
|
|
|
}
|
2017-11-27 15:47:45 +00:00
|
|
|
|
2018-05-29 17:23:27 +01:00
|
|
|
func getCertsFromEntries(certEntries []certificateEntry) [][]byte {
|
2018-02-27 18:53:21 +00:00
|
|
|
certs := make([][]byte, len(certEntries))
|
|
|
|
for i, cert := range certEntries {
|
2018-03-26 16:58:09 +01:00
|
|
|
certs[i] = cert.data
|
|
|
|
}
|
2018-02-27 18:53:21 +00:00
|
|
|
return certs
|
2018-03-26 16:58:09 +01:00
|
|
|
}
|
|
|
|
|
2017-09-21 14:27:53 +01:00
|
|
|
func (hs *clientHandshakeState) processEncryptedExtensions(ee *encryptedExtensionsMsg) error {
|
|
|
|
c := hs.c
|
|
|
|
if ee.alpnProtocol != "" {
|
|
|
|
c.clientProtocol = ee.alpnProtocol
|
|
|
|
c.clientProtocolFallback = false
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-06-26 18:19:23 +01:00
|
|
|
func verifyPeerHandshakeSignature(
|
2018-05-29 17:23:27 +01:00
|
|
|
certVerify *certificateVerifyMsg,
|
|
|
|
pubKey crypto.PublicKey,
|
|
|
|
signAlgosKnown []SignatureScheme,
|
|
|
|
transHash []byte,
|
|
|
|
contextString string) (error, alert) {
|
2018-02-27 18:53:21 +00:00
|
|
|
|
|
|
|
_, sigType, hashFunc, err := pickSignatureAlgorithm(
|
2018-05-29 17:23:27 +01:00
|
|
|
pubKey,
|
|
|
|
[]SignatureScheme{certVerify.signatureAlgorithm},
|
|
|
|
signAlgosKnown,
|
|
|
|
VersionTLS13)
|
2017-09-15 19:04:39 +01:00
|
|
|
if err != nil {
|
2018-02-27 18:53:21 +00:00
|
|
|
return err, alertHandshakeFailure
|
2017-09-15 19:04:39 +01:00
|
|
|
}
|
|
|
|
|
2018-02-27 18:53:21 +00:00
|
|
|
digest := prepareDigitallySigned(hashFunc, contextString, transHash)
|
|
|
|
err = verifyHandshakeSignature(sigType, pubKey, hashFunc, digest, certVerify.signature)
|
|
|
|
|
2018-03-26 16:58:09 +01:00
|
|
|
if err != nil {
|
2018-02-27 18:53:21 +00:00
|
|
|
return err, alertDecryptError
|
2018-03-26 16:58:09 +01:00
|
|
|
}
|
2018-02-27 18:53:21 +00:00
|
|
|
|
|
|
|
return nil, alertSuccess
|
2018-03-26 16:58:09 +01:00
|
|
|
}
|
|
|
|
|
2018-03-26 16:20:25 +01:00
|
|
|
func (hs *clientHandshakeState) getCertificate13(certReq *certificateRequestMsg13) (*Certificate, error) {
|
|
|
|
certReq12 := &certificateRequestMsg{
|
|
|
|
hasSignatureAndHash: true,
|
|
|
|
supportedSignatureAlgorithms: certReq.supportedSignatureAlgorithms,
|
|
|
|
certificateAuthorities: certReq.certificateAuthorities,
|
|
|
|
}
|
|
|
|
|
|
|
|
var rsaAvail, ecdsaAvail bool
|
|
|
|
for _, sigAlg := range certReq.supportedSignatureAlgorithms {
|
|
|
|
switch signatureFromSignatureScheme(sigAlg) {
|
|
|
|
case signaturePKCS1v15, signatureRSAPSS:
|
|
|
|
rsaAvail = true
|
|
|
|
case signatureECDSA:
|
|
|
|
ecdsaAvail = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if rsaAvail {
|
|
|
|
certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeRSASign)
|
|
|
|
}
|
|
|
|
if ecdsaAvail {
|
|
|
|
certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeECDSASign)
|
|
|
|
}
|
|
|
|
|
|
|
|
return hs.getCertificate(certReq12)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (hs *clientHandshakeState) sendCertificate13(chainToSend *Certificate, certReq *certificateRequestMsg13) error {
|
|
|
|
c := hs.c
|
|
|
|
|
|
|
|
certEntries := []certificateEntry{}
|
|
|
|
for _, cert := range chainToSend.Certificate {
|
|
|
|
certEntries = append(certEntries, certificateEntry{data: cert})
|
|
|
|
}
|
|
|
|
certMsg := &certificateMsg13{certificates: certEntries}
|
|
|
|
|
|
|
|
hs.keySchedule.write(certMsg.marshal())
|
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(certEntries) == 0 {
|
|
|
|
// No client cert available, nothing to sign.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
key, ok := chainToSend.PrivateKey.(crypto.Signer)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
|
|
|
|
if err != nil {
|
|
|
|
hs.c.sendAlert(alertHandshakeFailure)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
digest := prepareDigitallySigned(hashFunc, "TLS 1.3, client CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
|
|
|
|
signOpts := crypto.SignerOpts(hashFunc)
|
|
|
|
if sigType == signatureRSAPSS {
|
|
|
|
signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
|
|
|
|
}
|
|
|
|
signature, err := key.Sign(c.config.rand(), digest, signOpts)
|
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
verifyMsg := &certificateVerifyMsg{
|
|
|
|
hasSignatureAndHash: true,
|
|
|
|
signatureAlgorithm: signatureAlgorithm,
|
|
|
|
signature: signature,
|
|
|
|
}
|
|
|
|
hs.keySchedule.write(verifyMsg.marshal())
|
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-11-27 15:47:45 +00:00
|
|
|
func (hs *clientHandshakeState) doTLS13Handshake() error {
|
2017-11-27 16:05:46 +00:00
|
|
|
c := hs.c
|
|
|
|
hash := hashForSuite(hs.suite)
|
|
|
|
hashSize := hash.Size()
|
|
|
|
serverHello := hs.serverHello
|
2018-06-24 02:58:58 +01:00
|
|
|
c.scts = serverHello.scts
|
2017-11-12 07:44:45 +00:00
|
|
|
|
|
|
|
// middlebox compatibility mode, send CCS before second flight.
|
|
|
|
if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-11-27 16:05:46 +00:00
|
|
|
// TODO check if keyshare is unacceptable, raise HRR.
|
|
|
|
|
|
|
|
clientKS := hs.hello.keyShares[0]
|
|
|
|
if serverHello.keyShare.group != clientKS.group {
|
|
|
|
c.sendAlert(alertIllegalParameter)
|
|
|
|
return errors.New("bad or missing key share from server")
|
|
|
|
}
|
|
|
|
|
|
|
|
// 0-RTT is not supported yet, so use an empty PSK.
|
|
|
|
hs.keySchedule.setSecret(nil)
|
2019-02-25 17:25:16 +00:00
|
|
|
sharedSecret, err := c.keyAgreementClient(serverHello.keyShare, hs.privateKey)
|
|
|
|
if err != nil {
|
2017-11-27 16:05:46 +00:00
|
|
|
c.sendAlert(alertIllegalParameter)
|
2019-02-25 17:25:16 +00:00
|
|
|
return err
|
2017-11-27 16:05:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate handshake secrets.
|
2019-02-25 17:25:16 +00:00
|
|
|
hs.keySchedule.setSecret(sharedSecret)
|
2017-11-27 16:05:46 +00:00
|
|
|
clientCipher, clientHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
|
|
|
|
serverCipher, serverHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
|
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return errors.New("tls: unexpected data after Server Hello")
|
|
|
|
}
|
|
|
|
// Do not change the sender key yet, the server must authenticate first.
|
|
|
|
c.in.setCipher(c.vers, serverCipher)
|
|
|
|
|
|
|
|
// Calculate MAC key for Finished messages.
|
|
|
|
serverFinishedKey := hkdfExpandLabel(hash, serverHandshakeSecret, nil, "finished", hashSize)
|
|
|
|
clientFinishedKey := hkdfExpandLabel(hash, clientHandshakeSecret, nil, "finished", hashSize)
|
|
|
|
|
|
|
|
msg, err := c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(encryptedExtensions, msg)
|
|
|
|
}
|
2017-09-21 14:27:53 +01:00
|
|
|
if err := hs.processEncryptedExtensions(encryptedExtensions); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-11-27 16:05:46 +00:00
|
|
|
hs.keySchedule.write(encryptedExtensions.marshal())
|
|
|
|
|
|
|
|
// PSKs are not supported, so receive Certificate message.
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-03-26 16:20:25 +01:00
|
|
|
|
|
|
|
var chainToSend *Certificate
|
|
|
|
certReq, isCertRequested := msg.(*certificateRequestMsg13)
|
|
|
|
if isCertRequested {
|
|
|
|
hs.keySchedule.write(certReq.marshal())
|
|
|
|
|
|
|
|
if chainToSend, err = hs.getCertificate13(certReq); err != nil {
|
|
|
|
c.sendAlert(alertInternalError)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 16:05:46 +00:00
|
|
|
certMsg, ok := msg.(*certificateMsg13)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(certMsg, msg)
|
|
|
|
}
|
|
|
|
hs.keySchedule.write(certMsg.marshal())
|
2018-07-03 17:57:54 +01:00
|
|
|
|
2017-09-15 19:04:39 +01:00
|
|
|
// Validate certificates.
|
2018-02-27 18:53:21 +00:00
|
|
|
certs := getCertsFromEntries(certMsg.certificates)
|
|
|
|
if err := hs.processCertsFromServer(certs); err != nil {
|
2017-09-15 19:04:39 +01:00
|
|
|
return err
|
|
|
|
}
|
2017-11-27 16:05:46 +00:00
|
|
|
|
2018-08-09 19:24:40 +01:00
|
|
|
// Receive CertificateVerify message.
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
certVerifyMsg, ok := msg.(*certificateVerifyMsg)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(certVerifyMsg, msg)
|
|
|
|
}
|
|
|
|
|
2018-07-03 17:57:54 +01:00
|
|
|
// Validate the DC if present. The DC is only processed if the extension was
|
|
|
|
// indicated by the ClientHello; otherwise this call will result in an
|
2018-08-09 19:24:40 +01:00
|
|
|
// "illegal_parameter" alert.
|
2018-07-03 17:57:54 +01:00
|
|
|
if len(certMsg.certificates) > 0 {
|
|
|
|
if err := hs.processDelegatedCredentialFromServer(
|
2018-08-09 19:24:40 +01:00
|
|
|
certMsg.certificates[0].delegatedCredential,
|
|
|
|
certVerifyMsg.signatureAlgorithm); err != nil {
|
2018-07-03 17:57:54 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the public key used to verify the handshake.
|
|
|
|
pk := hs.c.peerCertificates[0].PublicKey
|
|
|
|
|
|
|
|
// If the delegated credential extension has successfully been negotiated,
|
|
|
|
// then the CertificateVerify signature will have been produced with the
|
|
|
|
// DelegatedCredential's private key.
|
|
|
|
if hs.c.verifiedDc != nil {
|
2018-07-20 17:47:24 +01:00
|
|
|
pk = hs.c.verifiedDc.cred.publicKey
|
2018-07-03 17:57:54 +01:00
|
|
|
}
|
|
|
|
|
2018-08-09 19:24:40 +01:00
|
|
|
// Verify the handshake signature.
|
2018-06-26 18:19:23 +01:00
|
|
|
err, alertCode := verifyPeerHandshakeSignature(
|
2018-05-29 17:23:27 +01:00
|
|
|
certVerifyMsg,
|
2018-07-03 17:57:54 +01:00
|
|
|
pk,
|
2018-05-29 17:23:27 +01:00
|
|
|
hs.hello.supportedSignatureAlgorithms,
|
|
|
|
hs.keySchedule.transcriptHash.Sum(nil),
|
|
|
|
"TLS 1.3, server CertificateVerify")
|
2018-02-27 18:53:21 +00:00
|
|
|
if err != nil {
|
|
|
|
c.sendAlert(alertCode)
|
2017-09-15 19:04:39 +01:00
|
|
|
return err
|
|
|
|
}
|
2017-11-27 16:05:46 +00:00
|
|
|
hs.keySchedule.write(certVerifyMsg.marshal())
|
|
|
|
|
|
|
|
// Receive Finished message.
|
|
|
|
msg, err = c.readHandshake()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
serverFinished, ok := msg.(*finishedMsg)
|
|
|
|
if !ok {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return unexpectedMessageError(serverFinished, msg)
|
|
|
|
}
|
|
|
|
// Validate server Finished hash.
|
|
|
|
expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
|
|
|
|
if subtle.ConstantTimeCompare(expectedVerifyData, serverFinished.verifyData) != 1 {
|
|
|
|
c.sendAlert(alertDecryptError)
|
|
|
|
return errors.New("tls: server's Finished message is incorrect")
|
|
|
|
}
|
|
|
|
hs.keySchedule.write(serverFinished.marshal())
|
|
|
|
|
2018-03-26 16:20:25 +01:00
|
|
|
// Server has authenticated itself. Calculate application traffic secrets.
|
|
|
|
hs.keySchedule.setSecret(nil) // derive master secret
|
|
|
|
appServerCipher, _ := hs.keySchedule.prepareCipher(secretApplicationServer)
|
|
|
|
appClientCipher, _ := hs.keySchedule.prepareCipher(secretApplicationClient)
|
2018-03-26 17:04:10 +01:00
|
|
|
// TODO store initial traffic secret key for KeyUpdate GH #85
|
2018-03-26 16:20:25 +01:00
|
|
|
|
|
|
|
// Change outbound handshake cipher for final step
|
2017-11-27 16:05:46 +00:00
|
|
|
c.out.setCipher(c.vers, clientCipher)
|
|
|
|
|
2018-03-26 16:20:25 +01:00
|
|
|
// Client auth requires sending a (possibly empty) Certificate followed
|
|
|
|
// by a CertificateVerify message (if there was an actual certificate).
|
|
|
|
if isCertRequested {
|
|
|
|
if err := hs.sendCertificate13(chainToSend, certReq); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2017-11-27 16:05:46 +00:00
|
|
|
|
|
|
|
// Send Finished
|
|
|
|
verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, clientFinishedKey)
|
|
|
|
clientFinished := &finishedMsg{
|
|
|
|
verifyData: verifyData,
|
|
|
|
}
|
|
|
|
if _, err := c.writeRecord(recordTypeHandshake, clientFinished.marshal()); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-03-26 16:20:25 +01:00
|
|
|
// Handshake done, set application traffic secret
|
|
|
|
c.out.setCipher(c.vers, appClientCipher)
|
2017-11-27 16:05:46 +00:00
|
|
|
if c.hand.Len() > 0 {
|
|
|
|
c.sendAlert(alertUnexpectedMessage)
|
|
|
|
return errors.New("tls: unexpected data after handshake")
|
|
|
|
}
|
2018-03-26 16:20:25 +01:00
|
|
|
c.in.setCipher(c.vers, appServerCipher)
|
2017-11-27 15:47:45 +00:00
|
|
|
return nil
|
|
|
|
}
|
2018-06-26 14:25:45 +01:00
|
|
|
|
|
|
|
// supportedSigAlgorithmsCert iterates over schemes and filters out those algorithms
|
|
|
|
// which are not supported for certificate verification.
|
|
|
|
func supportedSigAlgorithmsCert(schemes []SignatureScheme) (ret []SignatureScheme) {
|
|
|
|
for _, sig := range schemes {
|
|
|
|
// X509 doesn't support PSS signatures
|
|
|
|
if !signatureSchemeIsPSS(sig) {
|
|
|
|
ret = append(ret, sig)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2018-10-05 22:43:00 +01:00
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
// Functions below implement kex interface for different DH shared secret agreements
|
2018-10-05 22:43:00 +01:00
|
|
|
|
|
|
|
// KEX: P-256, P-384, P-512 KEX
|
2019-02-25 17:25:16 +00:00
|
|
|
func (kexNIST) generate(c *Conn, groupId CurveID) (private []byte, ks keyShare, err error) {
|
2018-10-05 22:43:00 +01:00
|
|
|
// never fails
|
|
|
|
curve, _ := curveForCurveID(groupId)
|
|
|
|
private, x, y, err := elliptic.GenerateKey(curve, c.config.rand())
|
|
|
|
if err != nil {
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
ks.group = groupId
|
|
|
|
ks.data = elliptic.Marshal(curve, x, y)
|
|
|
|
return
|
|
|
|
}
|
2019-02-25 17:25:16 +00:00
|
|
|
func (kexNIST) keyAgreementClient(c *Conn, ks keyShare, secretKey []byte) ([]byte, error) {
|
2018-10-05 22:43:00 +01:00
|
|
|
// never fails
|
|
|
|
curve, _ := curveForCurveID(ks.group)
|
|
|
|
x, y := elliptic.Unmarshal(curve, ks.data)
|
|
|
|
if x == nil {
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: Point not on a curve")
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
x, _ = curve.ScalarMult(x, y, secretKey)
|
|
|
|
xBytes := x.Bytes()
|
|
|
|
curveSize := (curve.Params().BitSize + 8 - 1) >> 3
|
|
|
|
if len(xBytes) == curveSize {
|
2019-02-25 17:25:16 +00:00
|
|
|
return xBytes, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
buf := make([]byte, curveSize)
|
|
|
|
copy(buf[len(buf)-len(xBytes):], xBytes)
|
2019-02-25 17:25:16 +00:00
|
|
|
return buf, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// KEX: X25519
|
|
|
|
func (kexX25519) generate(c *Conn, groupId CurveID) ([]byte, keyShare, error) {
|
|
|
|
var scalar, public [x25519SharedSecretSz]byte
|
|
|
|
if _, err := io.ReadFull(c.config.rand(), scalar[:]); err != nil {
|
|
|
|
return nil, keyShare{}, err
|
|
|
|
}
|
|
|
|
curve25519.ScalarBaseMult(&public, &scalar)
|
|
|
|
return scalar[:], keyShare{group: X25519, data: public[:]}, nil
|
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
func (kexX25519) keyAgreementClient(c *Conn, ks keyShare, secretKey []byte) ([]byte, error) {
|
2018-10-05 22:43:00 +01:00
|
|
|
var theirPublic, sharedKey, scalar [x25519SharedSecretSz]byte
|
|
|
|
if len(ks.data) != x25519SharedSecretSz {
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: wrong shared secret size")
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
copy(theirPublic[:], ks.data)
|
|
|
|
copy(scalar[:], secretKey)
|
|
|
|
curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
|
2019-02-25 17:25:16 +00:00
|
|
|
return sharedKey[:], nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// KEX: SIDH/503
|
2018-12-05 14:20:21 +00:00
|
|
|
func (kexSIDHp503) generate(c *Conn, groupId CurveID) ([]byte, keyShare, error) {
|
2018-10-05 22:43:00 +01:00
|
|
|
var variant, _ = getSidhKeyVariant(c.isClient)
|
|
|
|
var prvKey = sidh.NewPrivateKey(sidh.FP_503, variant)
|
|
|
|
if prvKey.Generate(c.config.rand()) != nil {
|
|
|
|
return nil, keyShare{}, errors.New("tls: private SIDH key generation failed")
|
|
|
|
}
|
|
|
|
pubKey := prvKey.GeneratePublicKey()
|
2018-12-07 15:35:53 +00:00
|
|
|
return prvKey.Export(), keyShare{group: 0 /*UNUSED*/, data: pubKey.Export()}, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
func (kexSIDHp503) keyAgreementClient(c *Conn, ks keyShare, key []byte) ([]byte, error) {
|
2018-10-05 22:43:00 +01:00
|
|
|
var prvVariant, pubVariant = getSidhKeyVariant(c.isClient)
|
|
|
|
var prvKeySize = P503PrvKeySz
|
|
|
|
|
|
|
|
if len(ks.data) != P503PubKeySz || len(key) != prvKeySize {
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: wrong key size")
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
prvKey := sidh.NewPrivateKey(sidh.FP_503, prvVariant)
|
|
|
|
pubKey := sidh.NewPublicKey(sidh.FP_503, pubVariant)
|
|
|
|
|
|
|
|
if err := prvKey.Import(key); err != nil {
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: internal error")
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
if err := pubKey.Import(ks.data); err != nil {
|
2019-02-25 17:25:16 +00:00
|
|
|
return nil, errors.New("tls: internal error")
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Never fails
|
|
|
|
sharedKey, _ := sidh.DeriveSecret(prvKey, pubKey)
|
2019-02-25 17:25:16 +00:00
|
|
|
return sharedKey, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// KEX Hybrid SIDH/503-X25519
|
2018-12-05 14:20:21 +00:00
|
|
|
func (kex *kexHybridSIDHp503X25519) generate(c *Conn, groupId CurveID) (private []byte, ks keyShare, err error) {
|
|
|
|
var pubHybrid [SIDHp503Curve25519PubKeySz]byte
|
|
|
|
var prvHybrid [SIDHp503Curve25519PrvKeySz]byte
|
2018-10-05 22:43:00 +01:00
|
|
|
|
|
|
|
// Generate ephemeral key for classic x25519
|
2018-12-05 14:20:21 +00:00
|
|
|
private, ks, err = kex.classicKEX.generate(c, groupId)
|
2018-10-05 22:43:00 +01:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
copy(prvHybrid[:], private)
|
|
|
|
copy(pubHybrid[:], ks.data)
|
|
|
|
|
|
|
|
// Generate PQ ephemeral key for SIDH
|
2018-12-05 14:20:21 +00:00
|
|
|
private, ks, err = kex.pqKEX.generate(c, groupId)
|
2018-10-05 22:43:00 +01:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
copy(prvHybrid[x25519SharedSecretSz:], private)
|
|
|
|
copy(pubHybrid[x25519SharedSecretSz:], ks.data)
|
2018-12-05 14:20:21 +00:00
|
|
|
return prvHybrid[:], keyShare{group: HybridSIDHp503Curve25519, data: pubHybrid[:]}, nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
|
2019-02-25 17:25:16 +00:00
|
|
|
func (kex *kexHybridSIDHp503X25519) keyAgreementClient(c *Conn, ks keyShare, key []byte) ([]byte, error) {
|
2018-12-05 14:20:21 +00:00
|
|
|
var sharedKey [SIDHp503Curve25519SharedKeySz]byte
|
2018-10-05 22:43:00 +01:00
|
|
|
var ret []byte
|
|
|
|
var tmpKs keyShare
|
|
|
|
|
|
|
|
// Key agreement for classic
|
|
|
|
tmpKs.group = X25519
|
|
|
|
tmpKs.data = ks.data[:x25519SharedSecretSz]
|
2019-02-25 17:25:16 +00:00
|
|
|
ret, err := kex.classicKEX.keyAgreementClient(c, tmpKs, key[:x25519SharedSecretSz])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
copy(sharedKey[:], ret)
|
|
|
|
|
|
|
|
// Key agreement for PQ
|
2018-12-07 15:35:53 +00:00
|
|
|
tmpKs.group = 0 /*UNUSED*/
|
2018-10-05 22:43:00 +01:00
|
|
|
tmpKs.data = ks.data[x25519SharedSecretSz:]
|
2019-02-25 17:25:16 +00:00
|
|
|
ret, err = kex.pqKEX.keyAgreementClient(c, tmpKs, key[x25519SharedSecretSz:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|
|
|
|
copy(sharedKey[x25519SharedSecretSz:], ret)
|
2019-02-25 17:25:16 +00:00
|
|
|
return sharedKey[:], nil
|
2018-10-05 22:43:00 +01:00
|
|
|
}
|