github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/crypto/tls/auth.go (about)

     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  	cmcrypto "chainmaker.org/chainmaker/common/v2/crypto"
    20  	"github.com/tjfoc/gmsm/sm2"
    21  )
    22  
    23  // verifyHandshakeSignature verifies a signature against pre-hashed
    24  // (if required) handshake contents.
    25  func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error {
    26  	if cmPubkey, ok := pubkey.(cmcrypto.PublicKey); ok {
    27  		pubkey = cmPubkey.ToStandardKey()
    28  	}
    29  	switch sigType {
    30  	case signatureECDSA:
    31  		pubKey, ok := pubkey.(*ecdsa.PublicKey)
    32  		if !ok {
    33  			return fmt.Errorf("expected an ECDSA public key, got %T", pubkey)
    34  		}
    35  		if !ecdsa.VerifyASN1(pubKey, signed, sig) {
    36  			return errors.New("ECDSA verification failure")
    37  		}
    38  	case signatureSM2:
    39  		pubKey, ok := pubkey.(*sm2.PublicKey)
    40  		if !ok {
    41  			return errors.New("tls: SM2 signing requires a SM2 public key")
    42  		}
    43  		if ok := pubKey.Verify(signed, sig); !ok {
    44  			return errors.New("verify sm2 signature error")
    45  		}
    46  	case signatureEd25519:
    47  		pubKey, ok := pubkey.(ed25519.PublicKey)
    48  		if !ok {
    49  			return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey)
    50  		}
    51  		if !ed25519.Verify(pubKey, signed, sig) {
    52  			return errors.New("Ed25519 verification failure")
    53  		}
    54  	case signaturePKCS1v15:
    55  		pubKey, ok := pubkey.(*rsa.PublicKey)
    56  		if !ok {
    57  			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
    58  		}
    59  		if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil {
    60  			return err
    61  		}
    62  	case signatureRSAPSS:
    63  		pubKey, ok := pubkey.(*rsa.PublicKey)
    64  		if !ok {
    65  			return fmt.Errorf("expected an RSA public key, got %T", pubkey)
    66  		}
    67  		signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
    68  		if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil {
    69  			return err
    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 || sigHash == cmcrypto.SM3 {
    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 SM2WithSM3:
   123  		sigType = signatureSM2
   124  	default:
   125  		return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", 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 SM2WithSM3:
   139  		hash = cmcrypto.SM3
   140  	default:
   141  		return 0, 0, fmt.Errorf("unsupported signature algorithm: %#04x", signatureAlgorithm)
   142  	}
   143  	return sigType, hash, nil
   144  }
   145  
   146  // legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for
   147  // a given public key used with TLS 1.0 and 1.1, before the introduction of
   148  // signature algorithm negotiation.
   149  func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) {
   150  	switch pub.(type) {
   151  	case *rsa.PublicKey:
   152  		return signaturePKCS1v15, crypto.MD5SHA1, nil
   153  	case *ecdsa.PublicKey:
   154  		return signatureECDSA, crypto.SHA1, nil
   155  	case *sm2.PublicKey:
   156  		return signatureSM2, cmcrypto.SM3, 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  func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme {
   193  	priv, ok := cert.PrivateKey.(crypto.Signer)
   194  	if !ok {
   195  		return nil
   196  	}
   197  
   198  	var sigAlgs []SignatureScheme
   199  	switch pub := priv.Public().(type) {
   200  	case *ecdsa.PublicKey:
   201  		if version != VersionTLS13 {
   202  			// In TLS 1.2 and earlier, ECDSA algorithms are not
   203  			// constrained to a single curve.
   204  			sigAlgs = []SignatureScheme{
   205  				ECDSAWithP256AndSHA256,
   206  				ECDSAWithP384AndSHA384,
   207  				ECDSAWithP521AndSHA512,
   208  				ECDSAWithSHA1,
   209  			}
   210  			break
   211  		}
   212  		switch pub.Curve {
   213  		case elliptic.P256():
   214  			sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256}
   215  		case elliptic.P384():
   216  			sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384}
   217  		case elliptic.P521():
   218  			sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512}
   219  		default:
   220  			return nil
   221  		}
   222  	case *sm2.PublicKey:
   223  		if pub.Curve != sm2.P256Sm2() {
   224  			return nil
   225  		}
   226  		sigAlgs = []SignatureScheme{
   227  			SM2WithSM3,
   228  		}
   229  	case *rsa.PublicKey:
   230  		size := pub.Size()
   231  		sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes))
   232  		for _, candidate := range rsaSignatureSchemes {
   233  			if size >= candidate.minModulusBytes && version <= candidate.maxVersion {
   234  				sigAlgs = append(sigAlgs, candidate.scheme)
   235  			}
   236  		}
   237  	case ed25519.PublicKey:
   238  		sigAlgs = []SignatureScheme{Ed25519}
   239  	default:
   240  		return nil
   241  	}
   242  
   243  	if cert.SupportedSignatureAlgorithms != nil {
   244  		var filteredSigAlgs []SignatureScheme
   245  		for _, sigAlg := range sigAlgs {
   246  			if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) {
   247  				filteredSigAlgs = append(filteredSigAlgs, sigAlg)
   248  			}
   249  		}
   250  		return filteredSigAlgs
   251  	}
   252  	return sigAlgs
   253  }
   254  
   255  // selectSignatureScheme picks a SignatureScheme from the peer's preference list
   256  // that works with the selected certificate. It's only called for protocol
   257  // versions that support signature algorithms, so TLS 1.2 and 1.3.
   258  func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) {
   259  	supportedAlgs := signatureSchemesForCertificate(vers, c)
   260  	if len(supportedAlgs) == 0 {
   261  		return 0, unsupportedCertificateError(c)
   262  	}
   263  	if len(peerAlgs) == 0 && vers == VersionTLS12 {
   264  		// For TLS 1.2, if the client didn't send signature_algorithms then we
   265  		// can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1.
   266  		peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1, SM2WithSM3}
   267  	}
   268  	// Pick signature scheme in the peer's preference order, as our
   269  	// preference order is not configurable.
   270  	for _, preferredAlg := range peerAlgs {
   271  		if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
   272  			return preferredAlg, nil
   273  		}
   274  	}
   275  	return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms")
   276  }
   277  
   278  // unsupportedCertificateError returns a helpful error for certificates with
   279  // an unsupported private key.
   280  func unsupportedCertificateError(cert *Certificate) error {
   281  	switch cert.PrivateKey.(type) {
   282  	case rsa.PrivateKey, ecdsa.PrivateKey, sm2.PrivateKey:
   283  		return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T",
   284  			cert.PrivateKey, cert.PrivateKey)
   285  	case *ed25519.PrivateKey:
   286  		return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey")
   287  	}
   288  
   289  	signer, ok := cert.PrivateKey.(crypto.Signer)
   290  	if !ok {
   291  		return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer",
   292  			cert.PrivateKey)
   293  	}
   294  
   295  	switch pub := signer.Public().(type) {
   296  	case *ecdsa.PublicKey:
   297  		switch pub.Curve {
   298  		case elliptic.P256():
   299  		case elliptic.P384():
   300  		case elliptic.P521():
   301  		default:
   302  			return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name)
   303  		}
   304  	case *sm2.PublicKey:
   305  		if pub.Curve != sm2.P256Sm2() {
   306  			return fmt.Errorf("tls: require curve P256Sm2, get curve %s", pub.Curve.Params().Name)
   307  		}
   308  	case *rsa.PublicKey:
   309  		return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms")
   310  	case ed25519.PublicKey:
   311  	default:
   312  		return fmt.Errorf("tls: unsupported certificate key (%T)", pub)
   313  	}
   314  
   315  	if cert.SupportedSignatureAlgorithms != nil {
   316  		return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms")
   317  	}
   318  
   319  	return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey)
   320  }