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