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