1// Copyright 2017 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package tls
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/ed25519"
12	"crypto/elliptic"
13	"crypto/rsa"
14	"encoding/asn1"
15	"errors"
16	"fmt"
17	"hash"
18	"io"
19)
20
21// verifyHandshakeSignature verifies a signature against pre-hashed
22// (if required) handshake contents.
23func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error {
24	switch sigType {
25	case signatureECDSA:
26		pubKey, ok := pubkey.(*ecdsa.PublicKey)
27		if !ok {
28			return fmt.Errorf("expected an ECDSA public key, got %T", pubkey)
29		}
30		ecdsaSig := new(ecdsaSignature)
31		if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
32			return err
33		}
34		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
35			return errors.New("ECDSA signature contained zero or negative values")
36		}
37		if !ecdsa.Verify(pubKey, signed, ecdsaSig.R, ecdsaSig.S) {
38			return errors.New("ECDSA verification failure")
39		}
40	case signatureEd25519:
41		pubKey, ok := pubkey.(ed25519.PublicKey)
42		if !ok {
43			return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey)
44		}
45		if !ed25519.Verify(pubKey, signed, sig) {
46			return errors.New("Ed25519 verification failure")
47		}
48	case signaturePKCS1v15:
49		pubKey, ok := pubkey.(*rsa.PublicKey)
50		if !ok {
51			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
52		}
53		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil {
54			return err
55		}
56	case signatureRSAPSS:
57		pubKey, ok := pubkey.(*rsa.PublicKey)
58		if !ok {
59			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
60		}
61		signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
62		if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil {
63			return err
64		}
65	default:
66		return errors.New("internal error: unknown signature type")
67	}
68	return nil
69}
70
71const (
72	serverSignatureContext = "TLS 1.3, server CertificateVerify\x00"
73	clientSignatureContext = "TLS 1.3, client CertificateVerify\x00"
74)
75
76var signaturePadding = []byte{
77	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
78	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
79	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
80	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
81	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
82	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
83	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
84	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
85}
86
87// signedMessage returns the pre-hashed (if necessary) message to be signed by
88// certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3.
89func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte {
90	if sigHash == directSigning {
91		b := &bytes.Buffer{}
92		b.Write(signaturePadding)
93		io.WriteString(b, context)
94		b.Write(transcript.Sum(nil))
95		return b.Bytes()
96	}
97	h := sigHash.New()
98	h.Write(signaturePadding)
99	io.WriteString(h, context)
100	h.Write(transcript.Sum(nil))
101	return h.Sum(nil)
102}
103
104// typeAndHashFromSignatureScheme returns the corresponding signature type and
105// crypto.Hash for a given TLS SignatureScheme.
106func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error) {
107	switch signatureAlgorithm {
108	case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
109		sigType = signaturePKCS1v15
110	case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
111		sigType = signatureRSAPSS
112	case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
113		sigType = signatureECDSA
114	case Ed25519:
115		sigType = signatureEd25519
116	default:
117		return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", signatureAlgorithm)
118	}
119	switch signatureAlgorithm {
120	case PKCS1WithSHA1, ECDSAWithSHA1:
121		hash = crypto.SHA1
122	case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256:
123		hash = crypto.SHA256
124	case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384:
125		hash = crypto.SHA384
126	case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512:
127		hash = crypto.SHA512
128	case Ed25519:
129		hash = directSigning
130	default:
131		return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", signatureAlgorithm)
132	}
133	return sigType, hash, nil
134}
135
136// legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for
137// a given public key used with TLS 1.0 and 1.1, before the introduction of
138// signature algorithm negotiation.
139func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) {
140	switch pub.(type) {
141	case *rsa.PublicKey:
142		return signaturePKCS1v15, crypto.MD5SHA1, nil
143	case *ecdsa.PublicKey:
144		return signatureECDSA, crypto.SHA1, nil
145	case ed25519.PublicKey:
146		// RFC 8422 specifies support for Ed25519 in TLS 1.0 and 1.1,
147		// but it requires holding on to a handshake transcript to do a
148		// full signature, and not even OpenSSL bothers with the
149		// complexity, so we can't even test it properly.
150		return 0, 0, fmt.Errorf("tls: Ed25519 public keys are not supported before TLS 1.2")
151	default:
152		return 0, 0, fmt.Errorf("tls: unsupported public key: %T", pub)
153	}
154}
155
156var rsaSignatureSchemes = []struct {
157	scheme          SignatureScheme
158	minModulusBytes int
159	maxVersion      uint16
160}{
161	// RSA-PSS is used with PSSSaltLengthEqualsHash, and requires
162	//    emLen >= hLen + sLen + 2
163	{PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13},
164	{PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13},
165	{PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13},
166	// PKCS#1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires
167	//    emLen >= len(prefix) + hLen + 11
168	// TLS 1.3 dropped support for PKCS#1 v1.5 in favor of RSA-PSS.
169	{PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12},
170	{PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12},
171	{PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12},
172	{PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12},
173}
174
175// signatureSchemesForCertificate returns the list of supported SignatureSchemes
176// for a given certificate, based on the public key and the protocol version,
177// and optionally filtered by its explicit SupportedSignatureAlgorithms.
178//
179// This function must be kept in sync with supportedSignatureAlgorithms.
180func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
181	priv, ok := cert.PrivateKey.(crypto.Signer)
182	if !ok {
183		return nil
184	}
185
186	var sigAlgs []SignatureScheme
187	switch pub := priv.Public().(type) {
188	case *ecdsa.PublicKey:
189		if version != VersionTLS13 {
190			// In TLS 1.2 and earlier, ECDSA algorithms are not
191			// constrained to a single curve.
192			sigAlgs = []SignatureScheme{
193				ECDSAWithP256AndSHA256,
194				ECDSAWithP384AndSHA384,
195				ECDSAWithP521AndSHA512,
196				ECDSAWithSHA1,
197			}
198			break
199		}
200		switch pub.Curve {
201		case elliptic.P256():
202			sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
203		case elliptic.P384():
204			sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
205		case elliptic.P521():
206			sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
207		default:
208			return nil
209		}
210	case *rsa.PublicKey:
211		size := pub.Size()
212		sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
213		for _, candidate := range rsaSignatureSchemes {
214			if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
215				sigAlgs = append(sigAlgs, candidate.scheme)
216			}
217		}
218	case ed25519.PublicKey:
219		sigAlgs = []SignatureScheme{Ed25519}
220	default:
221		return nil
222	}
223
224	if cert.SupportedSignatureAlgorithms != nil {
225		var filteredSigAlgs []SignatureScheme
226		for _, sigAlg := range sigAlgs {
227			if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) {
228				filteredSigAlgs = append(filteredSigAlgs, sigAlg)
229			}
230		}
231		return filteredSigAlgs
232	}
233	return sigAlgs
234}
235
236// selectSignatureScheme picks a SignatureScheme from the peer's preference list
237// that works with the selected certificate. It's only called for protocol
238// versions that support signature algorithms, so TLS 1.2 and 1.3.
239func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
240	supportedAlgs := signatureSchemesForCertificate(vers, c)
241	if len(supportedAlgs) == 0 {
242		return 0, unsupportedCertificateError(c)
243	}
244	if len(peerAlgs) == 0 && vers == VersionTLS12 {
245		// For TLS 1.2, if the client didn't send signature_algorithms then we
246		// can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
247		peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1}
248	}
249	// Pick signature scheme in the peer's preference order, as our
250	// preference order is not configurable.
251	for _, preferredAlg := range peerAlgs {
252		if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
253			return preferredAlg, nil
254		}
255	}
256	return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms")
257}
258
259// unsupportedCertificateError returns a helpful error for certificates with
260// an unsupported private key.
261func unsupportedCertificateError(cert *Certificate) error {
262	switch cert.PrivateKey.(type) {
263	case rsa.PrivateKey, ecdsa.PrivateKey:
264		return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T",
265			cert.PrivateKey, cert.PrivateKey)
266	case *ed25519.PrivateKey:
267		return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey")
268	}
269
270	signer, ok := cert.PrivateKey.(crypto.Signer)
271	if !ok {
272		return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer",
273			cert.PrivateKey)
274	}
275
276	switch pub := signer.Public().(type) {
277	case *ecdsa.PublicKey:
278		switch pub.Curve {
279		case elliptic.P256():
280		case elliptic.P384():
281		case elliptic.P521():
282		default:
283			return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
284		}
285	case *rsa.PublicKey:
286		return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
287	case ed25519.PublicKey:
288	default:
289		return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
290	}
291
292	if cert.SupportedSignatureAlgorithms != nil {
293		return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
294	}
295
296	return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
297}
298