]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/auth.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / crypto / tls / auth.go
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
5 package tls
6
7 import (
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.
23 func 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
71 const (
72         serverSignatureContext = "TLS 1.3, server CertificateVerify\x00"
73         clientSignatureContext = "TLS 1.3, client CertificateVerify\x00"
74 )
75
76 var 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.
89 func 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.
106 func 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.
139 func 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
156 // signatureSchemesForCertificate returns the list of supported SignatureSchemes
157 // for a given certificate, based on the public key and the protocol version,
158 // and optionally filtered by its explicit SupportedSignatureAlgorithms.
159 //
160 // This function must be kept in sync with supportedSignatureAlgorithms.
161 func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
162         priv, ok := cert.PrivateKey.(crypto.Signer)
163         if !ok {
164                 return nil
165         }
166
167         var sigAlgs []SignatureScheme
168         switch pub := priv.Public().(type) {
169         case *ecdsa.PublicKey:
170                 if version != VersionTLS13 {
171                         // In TLS 1.2 and earlier, ECDSA algorithms are not
172                         // constrained to a single curve.
173                         sigAlgs = []SignatureScheme{
174                                 ECDSAWithP256AndSHA256,
175                                 ECDSAWithP384AndSHA384,
176                                 ECDSAWithP521AndSHA512,
177                                 ECDSAWithSHA1,
178                         }
179                         break
180                 }
181                 switch pub.Curve {
182                 case elliptic.P256():
183                         sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
184                 case elliptic.P384():
185                         sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
186                 case elliptic.P521():
187                         sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
188                 default:
189                         return nil
190                 }
191         case *rsa.PublicKey:
192                 if version != VersionTLS13 {
193                         sigAlgs = []SignatureScheme{
194                                 PSSWithSHA256,
195                                 PSSWithSHA384,
196                                 PSSWithSHA512,
197                                 PKCS1WithSHA256,
198                                 PKCS1WithSHA384,
199                                 PKCS1WithSHA512,
200                                 PKCS1WithSHA1,
201                         }
202                         break
203                 }
204                 // TLS 1.3 dropped support for PKCS#1 v1.5 in favor of RSA-PSS.
205                 sigAlgs = []SignatureScheme{
206                         PSSWithSHA256,
207                         PSSWithSHA384,
208                         PSSWithSHA512,
209                 }
210         case ed25519.PublicKey:
211                 sigAlgs = []SignatureScheme{Ed25519}
212         default:
213                 return nil
214         }
215
216         if cert.SupportedSignatureAlgorithms != nil {
217                 var filteredSigAlgs []SignatureScheme
218                 for _, sigAlg := range sigAlgs {
219                         if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) {
220                                 filteredSigAlgs = append(filteredSigAlgs, sigAlg)
221                         }
222                 }
223                 return filteredSigAlgs
224         }
225         return sigAlgs
226 }
227
228 // selectSignatureScheme picks a SignatureScheme from the peer's preference list
229 // that works with the selected certificate. It's only called for protocol
230 // versions that support signature algorithms, so TLS 1.2 and 1.3.
231 func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
232         supportedAlgs := signatureSchemesForCertificate(vers, c)
233         if len(supportedAlgs) == 0 {
234                 return 0, unsupportedCertificateError(c)
235         }
236         if len(peerAlgs) == 0 && vers == VersionTLS12 {
237                 // For TLS 1.2, if the client didn't send signature_algorithms then we
238                 // can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
239                 peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1}
240         }
241         // Pick signature scheme in the peer's preference order, as our
242         // preference order is not configurable.
243         for _, preferredAlg := range peerAlgs {
244                 if needFIPS() && !isSupportedSignatureAlgorithm(preferredAlg, fipsSupportedSignatureAlgorithms) {
245                         continue
246                 }
247                 if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
248                         return preferredAlg, nil
249                 }
250         }
251         return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms")
252 }
253
254 // unsupportedCertificateError returns a helpful error for certificates with
255 // an unsupported private key.
256 func unsupportedCertificateError(cert *Certificate) error {
257         switch cert.PrivateKey.(type) {
258         case rsa.PrivateKey, ecdsa.PrivateKey:
259                 return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T",
260                         cert.PrivateKey, cert.PrivateKey)
261         case *ed25519.PrivateKey:
262                 return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey")
263         }
264
265         signer, ok := cert.PrivateKey.(crypto.Signer)
266         if !ok {
267                 return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer",
268                         cert.PrivateKey)
269         }
270
271         switch pub := signer.Public().(type) {
272         case *ecdsa.PublicKey:
273                 switch pub.Curve {
274                 case elliptic.P256():
275                 case elliptic.P384():
276                 case elliptic.P521():
277                 default:
278                         return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
279                 }
280         case *rsa.PublicKey:
281         case ed25519.PublicKey:
282         default:
283                 return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
284         }
285
286         if cert.SupportedSignatureAlgorithms != nil {
287                 return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
288         }
289
290         return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
291 }