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  	"crypto/tls/internal/fips140tls"
    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  		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  //
   172  // This function must be kept in sync with supportedSignatureAlgorithms.
   173  // FIPS filtering is applied in the caller, selectSignatureScheme.
   174  func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
   175  	priv, ok := cert.PrivateKey.(crypto.Signer)
   176  	if !ok {
   177  		return nil
   178  	}
   179  
   180  	var sigAlgs []SignatureScheme
   181  	switch pub := priv.Public().(type) {
   182  	case *ecdsa.PublicKey:
   183  		if version != VersionTLS13 {
   184  			// In TLS 1.2 and earlier, ECDSA algorithms are not
   185  			// constrained to a single curve.
   186  			sigAlgs = []SignatureScheme{
   187  				ECDSAWithP256AndSHA256,
   188  				ECDSAWithP384AndSHA384,
   189  				ECDSAWithP521AndSHA512,
   190  				ECDSAWithSHA1,
   191  			}
   192  			break
   193  		}
   194  		switch pub.Curve {
   195  		case elliptic.P256():
   196  			sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
   197  		case elliptic.P384():
   198  			sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
   199  		case elliptic.P521():
   200  			sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
   201  		default:
   202  			return nil
   203  		}
   204  	case *rsa.PublicKey:
   205  		size := pub.Size()
   206  		sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
   207  		for _, candidate := range rsaSignatureSchemes {
   208  			if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
   209  				sigAlgs = append(sigAlgs, candidate.scheme)
   210  			}
   211  		}
   212  	case ed25519.PublicKey:
   213  		sigAlgs = []SignatureScheme{Ed25519}
   214  	default:
   215  		return nil
   216  	}
   217  
   218  	if cert.SupportedSignatureAlgorithms != nil {
   219  		var filteredSigAlgs []SignatureScheme
   220  		for _, sigAlg := range sigAlgs {
   221  			if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) {
   222  				filteredSigAlgs = append(filteredSigAlgs, sigAlg)
   223  			}
   224  		}
   225  		return filteredSigAlgs
   226  	}
   227  	return sigAlgs
   228  }
   229  
   230  // selectSignatureScheme picks a SignatureScheme from the peer's preference list
   231  // that works with the selected certificate. It's only called for protocol
   232  // versions that support signature algorithms, so TLS 1.2 and 1.3.
   233  func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
   234  	supportedAlgs := signatureSchemesForCertificate(vers, c)
   235  	if len(supportedAlgs) == 0 {
   236  		return 0, unsupportedCertificateError(c)
   237  	}
   238  	if len(peerAlgs) == 0 && vers == VersionTLS12 {
   239  		// For TLS 1.2, if the client didn't send signature_algorithms then we
   240  		// can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
   241  		peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1}
   242  	}
   243  	// Pick signature scheme in the peer's preference order, as our
   244  	// preference order is not configurable.
   245  	for _, preferredAlg := range peerAlgs {
   246  		if fips140tls.Required() && !isSupportedSignatureAlgorithm(preferredAlg, defaultSupportedSignatureAlgorithmsFIPS) {
   247  			continue
   248  		}
   249  		if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
   250  			return preferredAlg, nil
   251  		}
   252  	}
   253  	return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms")
   254  }
   255  
   256  // unsupportedCertificateError returns a helpful error for certificates with
   257  // an unsupported private key.
   258  func unsupportedCertificateError(cert *Certificate) error {
   259  	switch cert.PrivateKey.(type) {
   260  	case rsa.PrivateKey, ecdsa.PrivateKey:
   261  		return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T",
   262  			cert.PrivateKey, cert.PrivateKey)
   263  	case *ed25519.PrivateKey:
   264  		return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey")
   265  	}
   266  
   267  	signer, ok := cert.PrivateKey.(crypto.Signer)
   268  	if !ok {
   269  		return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer",
   270  			cert.PrivateKey)
   271  	}
   272  
   273  	switch pub := signer.Public().(type) {
   274  	case *ecdsa.PublicKey:
   275  		switch pub.Curve {
   276  		case elliptic.P256():
   277  		case elliptic.P384():
   278  		case elliptic.P521():
   279  		default:
   280  			return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
   281  		}
   282  	case *rsa.PublicKey:
   283  		return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
   284  	case ed25519.PublicKey:
   285  	default:
   286  		return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
   287  	}
   288  
   289  	if cert.SupportedSignatureAlgorithms != nil {
   290  		return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
   291  	}
   292  
   293  	return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
   294  }
   295  

View as plain text