Source file 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  	"slices"
    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  		if !ecdsa.VerifyASN1(pubKey, signed, sig) {
    31  			return errors.New("ECDSA verification failure")
    32  		}
    33  	case signatureEd25519:
    34  		pubKey, ok := pubkey.(ed25519.PublicKey)
    35  		if !ok {
    36  			return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey)
    37  		}
    38  		if !ed25519.Verify(pubKey, signed, sig) {
    39  			return errors.New("Ed25519 verification failure")
    40  		}
    41  	case signaturePKCS1v15:
    42  		pubKey, ok := pubkey.(*rsa.PublicKey)
    43  		if !ok {
    44  			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
    45  		}
    46  		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil {
    47  			return err
    48  		}
    49  	case signatureRSAPSS:
    50  		pubKey, ok := pubkey.(*rsa.PublicKey)
    51  		if !ok {
    52  			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
    53  		}
    54  		signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
    55  		if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil {
    56  			return err
    57  		}
    58  	default:
    59  		return errors.New("internal error: unknown signature type")
    60  	}
    61  	return nil
    62  }
    63  
    64  const (
    65  	serverSignatureContext = "TLS 1.3, server CertificateVerify\x00"
    66  	clientSignatureContext = "TLS 1.3, client CertificateVerify\x00"
    67  )
    68  
    69  var signaturePadding = []byte{
    70  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    71  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    72  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    73  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    74  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    75  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    76  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    77  	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
    78  }
    79  
    80  // signedMessage returns the pre-hashed (if necessary) message to be signed by
    81  // certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3.
    82  func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte {
    83  	if sigHash == directSigning {
    84  		b := &bytes.Buffer{}
    85  		b.Write(signaturePadding)
    86  		io.WriteString(b, context)
    87  		b.Write(transcript.Sum(nil))
    88  		return b.Bytes()
    89  	}
    90  	h := sigHash.New()
    91  	h.Write(signaturePadding)
    92  	io.WriteString(h, context)
    93  	h.Write(transcript.Sum(nil))
    94  	return h.Sum(nil)
    95  }
    96  
    97  // typeAndHashFromSignatureScheme returns the corresponding signature type and
    98  // crypto.Hash for a given TLS SignatureScheme.
    99  func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error) {
   100  	switch signatureAlgorithm {
   101  	case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
   102  		sigType = signaturePKCS1v15
   103  	case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
   104  		sigType = signatureRSAPSS
   105  	case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
   106  		sigType = signatureECDSA
   107  	case Ed25519:
   108  		sigType = signatureEd25519
   109  	default:
   110  		return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
   111  	}
   112  	switch signatureAlgorithm {
   113  	case PKCS1WithSHA1, ECDSAWithSHA1:
   114  		hash = crypto.SHA1
   115  	case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256:
   116  		hash = crypto.SHA256
   117  	case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384:
   118  		hash = crypto.SHA384
   119  	case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512:
   120  		hash = crypto.SHA512
   121  	case Ed25519:
   122  		hash = directSigning
   123  	default:
   124  		return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm)
   125  	}
   126  	return sigType, hash, nil
   127  }
   128  
   129  // legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for
   130  // a given public key used with TLS 1.0 and 1.1, before the introduction of
   131  // signature algorithm negotiation.
   132  func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) {
   133  	switch pub.(type) {
   134  	case *rsa.PublicKey:
   135  		return signaturePKCS1v15, crypto.MD5SHA1, nil
   136  	case *ecdsa.PublicKey:
   137  		return signatureECDSA, crypto.SHA1, nil
   138  	case ed25519.PublicKey:
   139  		// RFC 8422 specifies support for Ed25519 in TLS 1.0 and 1.1,
   140  		// but it requires holding on to a handshake transcript to do a
   141  		// full signature, and not even OpenSSL bothers with the
   142  		// complexity, so we can't even test it properly.
   143  		return 0, 0, fmt.Errorf("tls: Ed25519 public keys are not supported before TLS 1.2")
   144  	default:
   145  		return 0, 0, fmt.Errorf("tls: unsupported public key: %T", pub)
   146  	}
   147  }
   148  
   149  var rsaSignatureSchemes = []struct {
   150  	scheme          SignatureScheme
   151  	minModulusBytes int
   152  	maxVersion      uint16
   153  }{
   154  	// RSA-PSS is used with PSSSaltLengthEqualsHash, and requires
   155  	//    emLen >= hLen + sLen + 2
   156  	{PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13},
   157  	{PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13},
   158  	{PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13},
   159  	// PKCS #1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires
   160  	//    emLen >= len(prefix) + hLen + 11
   161  	// TLS 1.3 dropped support for PKCS #1 v1.5 in favor of RSA-PSS.
   162  	{PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12},
   163  	{PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12},
   164  	{PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12},
   165  	{PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12},
   166  }
   167  
   168  // signatureSchemesForCertificate returns the list of supported SignatureSchemes
   169  // for a given certificate, based on the public key and the protocol version,
   170  // and optionally filtered by its explicit SupportedSignatureAlgorithms.
   171  func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
   172  	priv, ok := cert.PrivateKey.(crypto.Signer)
   173  	if !ok {
   174  		return nil
   175  	}
   176  
   177  	var sigAlgs []SignatureScheme
   178  	switch pub := priv.Public().(type) {
   179  	case *ecdsa.PublicKey:
   180  		if version != VersionTLS13 {
   181  			// In TLS 1.2 and earlier, ECDSA algorithms are not
   182  			// constrained to a single curve.
   183  			sigAlgs = []SignatureScheme{
   184  				ECDSAWithP256AndSHA256,
   185  				ECDSAWithP384AndSHA384,
   186  				ECDSAWithP521AndSHA512,
   187  				ECDSAWithSHA1,
   188  			}
   189  			break
   190  		}
   191  		switch pub.Curve {
   192  		case elliptic.P256():
   193  			sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
   194  		case elliptic.P384():
   195  			sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
   196  		case elliptic.P521():
   197  			sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
   198  		default:
   199  			return nil
   200  		}
   201  	case *rsa.PublicKey:
   202  		size := pub.Size()
   203  		sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
   204  		for _, candidate := range rsaSignatureSchemes {
   205  			if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
   206  				sigAlgs = append(sigAlgs, candidate.scheme)
   207  			}
   208  		}
   209  	case ed25519.PublicKey:
   210  		sigAlgs = []SignatureScheme{Ed25519}
   211  	default:
   212  		return nil
   213  	}
   214  
   215  	if cert.SupportedSignatureAlgorithms != nil {
   216  		sigAlgs = slices.DeleteFunc(sigAlgs, func(sigAlg SignatureScheme) bool {
   217  			return !isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms)
   218  		})
   219  	}
   220  
   221  	// Filter out any unsupported signature algorithms, for example due to
   222  	// FIPS 140-3 policy, or any downstream changes to defaults.go.
   223  	supportedAlgs := supportedSignatureAlgorithms()
   224  	sigAlgs = slices.DeleteFunc(sigAlgs, func(sigAlg SignatureScheme) bool {
   225  		return !isSupportedSignatureAlgorithm(sigAlg, supportedAlgs)
   226  	})
   227  
   228  	return sigAlgs
   229  }
   230  
   231  // selectSignatureScheme picks a SignatureScheme from the peer's preference list
   232  // that works with the selected certificate. It's only called for protocol
   233  // versions that support signature algorithms, so TLS 1.2 and 1.3.
   234  func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
   235  	supportedAlgs := signatureSchemesForCertificate(vers, c)
   236  	if len(supportedAlgs) == 0 {
   237  		return 0, unsupportedCertificateError(c)
   238  	}
   239  	if len(peerAlgs) == 0 && vers == VersionTLS12 {
   240  		// For TLS 1.2, if the client didn't send signature_algorithms then we
   241  		// can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
   242  		peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1}
   243  	}
   244  	// Pick signature scheme in the peer's preference order, as our
   245  	// preference order is not configurable.
   246  	for _, preferredAlg := range peerAlgs {
   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  		return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
   282  	case ed25519.PublicKey:
   283  	default:
   284  		return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
   285  	}
   286  
   287  	if cert.SupportedSignatureAlgorithms != nil {
   288  		return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
   289  	}
   290  
   291  	return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
   292  }
   293  

View as plain text