...

Source file src/crypto/x509/x509.go

Documentation: crypto/x509

     1  // Copyright 2009 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 x509 implements a subset of the X.509 standard.
     6  //
     7  // It allows parsing and generating certificates, certificate signing
     8  // requests, certificate revocation lists, and encoded public and private keys.
     9  // It provides a certificate verifier, complete with a chain builder.
    10  //
    11  // The package targets the X.509 technical profile defined by the IETF (RFC
    12  // 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline
    13  // Requirements. There is minimal support for features outside of these
    14  // profiles, as the primary goal of the package is to provide compatibility
    15  // with the publicly trusted TLS certificate ecosystem and its policies and
    16  // constraints.
    17  //
    18  // On macOS and Windows, certificate verification is handled by system APIs, but
    19  // the package aims to apply consistent validation rules across operating
    20  // systems.
    21  package x509
    22  
    23  import (
    24  	"bytes"
    25  	"crypto"
    26  	"crypto/ecdh"
    27  	"crypto/ecdsa"
    28  	"crypto/ed25519"
    29  	"crypto/elliptic"
    30  	"crypto/rsa"
    31  	"crypto/sha1"
    32  	"crypto/x509/pkix"
    33  	"encoding/asn1"
    34  	"encoding/pem"
    35  	"errors"
    36  	"fmt"
    37  	"internal/godebug"
    38  	"io"
    39  	"math/big"
    40  	"net"
    41  	"net/url"
    42  	"strconv"
    43  	"time"
    44  	"unicode"
    45  
    46  	// Explicitly import these for their crypto.RegisterHash init side-effects.
    47  	// Keep these as blank imports, even if they're imported above.
    48  	_ "crypto/sha1"
    49  	_ "crypto/sha256"
    50  	_ "crypto/sha512"
    51  
    52  	"golang.org/x/crypto/cryptobyte"
    53  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    54  )
    55  
    56  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    57  // in RFC 3280.
    58  type pkixPublicKey struct {
    59  	Algo      pkix.AlgorithmIdentifier
    60  	BitString asn1.BitString
    61  }
    62  
    63  // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded
    64  // public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
    65  //
    66  // It returns a *[rsa.PublicKey], *[dsa.PublicKey], *[ecdsa.PublicKey],
    67  // [ed25519.PublicKey] (not a pointer), or *[ecdh.PublicKey] (for X25519).
    68  // More types might be supported in the future.
    69  //
    70  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
    71  func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
    72  	var pki publicKeyInfo
    73  	if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
    74  		if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
    75  			return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
    76  		}
    77  		return nil, err
    78  	} else if len(rest) != 0 {
    79  		return nil, errors.New("x509: trailing data after ASN.1 of public-key")
    80  	}
    81  	return parsePublicKey(&pki)
    82  }
    83  
    84  func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
    85  	switch pub := pub.(type) {
    86  	case *rsa.PublicKey:
    87  		publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
    88  			N: pub.N,
    89  			E: pub.E,
    90  		})
    91  		if err != nil {
    92  			return nil, pkix.AlgorithmIdentifier{}, err
    93  		}
    94  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
    95  		// This is a NULL parameters value which is required by
    96  		// RFC 3279, Section 2.3.1.
    97  		publicKeyAlgorithm.Parameters = asn1.NullRawValue
    98  	case *ecdsa.PublicKey:
    99  		oid, ok := oidFromNamedCurve(pub.Curve)
   100  		if !ok {
   101  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   102  		}
   103  		if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
   104  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
   105  		}
   106  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   107  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
   108  		var paramBytes []byte
   109  		paramBytes, err = asn1.Marshal(oid)
   110  		if err != nil {
   111  			return
   112  		}
   113  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   114  	case ed25519.PublicKey:
   115  		publicKeyBytes = pub
   116  		publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
   117  	case *ecdh.PublicKey:
   118  		publicKeyBytes = pub.Bytes()
   119  		if pub.Curve() == ecdh.X25519() {
   120  			publicKeyAlgorithm.Algorithm = oidPublicKeyX25519
   121  		} else {
   122  			oid, ok := oidFromECDHCurve(pub.Curve())
   123  			if !ok {
   124  				return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   125  			}
   126  			publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
   127  			var paramBytes []byte
   128  			paramBytes, err = asn1.Marshal(oid)
   129  			if err != nil {
   130  				return
   131  			}
   132  			publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   133  		}
   134  	default:
   135  		return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
   136  	}
   137  
   138  	return publicKeyBytes, publicKeyAlgorithm, nil
   139  }
   140  
   141  // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
   142  // The encoded public key is a SubjectPublicKeyInfo structure
   143  // (see RFC 5280, Section 4.1).
   144  //
   145  // The following key types are currently supported: *[rsa.PublicKey],
   146  // *[ecdsa.PublicKey], [ed25519.PublicKey] (not a pointer), and *[ecdh.PublicKey].
   147  // Unsupported key types result in an error.
   148  //
   149  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
   150  func MarshalPKIXPublicKey(pub any) ([]byte, error) {
   151  	var publicKeyBytes []byte
   152  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
   153  	var err error
   154  
   155  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
   156  		return nil, err
   157  	}
   158  
   159  	pkix := pkixPublicKey{
   160  		Algo: publicKeyAlgorithm,
   161  		BitString: asn1.BitString{
   162  			Bytes:     publicKeyBytes,
   163  			BitLength: 8 * len(publicKeyBytes),
   164  		},
   165  	}
   166  
   167  	ret, _ := asn1.Marshal(pkix)
   168  	return ret, nil
   169  }
   170  
   171  // These structures reflect the ASN.1 structure of X.509 certificates.:
   172  
   173  type certificate struct {
   174  	TBSCertificate     tbsCertificate
   175  	SignatureAlgorithm pkix.AlgorithmIdentifier
   176  	SignatureValue     asn1.BitString
   177  }
   178  
   179  type tbsCertificate struct {
   180  	Raw                asn1.RawContent
   181  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
   182  	SerialNumber       *big.Int
   183  	SignatureAlgorithm pkix.AlgorithmIdentifier
   184  	Issuer             asn1.RawValue
   185  	Validity           validity
   186  	Subject            asn1.RawValue
   187  	PublicKey          publicKeyInfo
   188  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   189  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   190  	Extensions         []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
   191  }
   192  
   193  type dsaAlgorithmParameters struct {
   194  	P, Q, G *big.Int
   195  }
   196  
   197  type validity struct {
   198  	NotBefore, NotAfter time.Time
   199  }
   200  
   201  type publicKeyInfo struct {
   202  	Raw       asn1.RawContent
   203  	Algorithm pkix.AlgorithmIdentifier
   204  	PublicKey asn1.BitString
   205  }
   206  
   207  // RFC 5280,  4.2.1.1
   208  type authKeyId struct {
   209  	Id []byte `asn1:"optional,tag:0"`
   210  }
   211  
   212  type SignatureAlgorithm int
   213  
   214  const (
   215  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   216  
   217  	MD2WithRSA  // Unsupported.
   218  	MD5WithRSA  // Only supported for signing, not verification.
   219  	SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
   220  	SHA256WithRSA
   221  	SHA384WithRSA
   222  	SHA512WithRSA
   223  	DSAWithSHA1   // Unsupported.
   224  	DSAWithSHA256 // Unsupported.
   225  	ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
   226  	ECDSAWithSHA256
   227  	ECDSAWithSHA384
   228  	ECDSAWithSHA512
   229  	SHA256WithRSAPSS
   230  	SHA384WithRSAPSS
   231  	SHA512WithRSAPSS
   232  	PureEd25519
   233  )
   234  
   235  func (algo SignatureAlgorithm) isRSAPSS() bool {
   236  	for _, details := range signatureAlgorithmDetails {
   237  		if details.algo == algo {
   238  			return details.isRSAPSS
   239  		}
   240  	}
   241  	return false
   242  }
   243  
   244  func (algo SignatureAlgorithm) hashFunc() crypto.Hash {
   245  	for _, details := range signatureAlgorithmDetails {
   246  		if details.algo == algo {
   247  			return details.hash
   248  		}
   249  	}
   250  	return crypto.Hash(0)
   251  }
   252  
   253  func (algo SignatureAlgorithm) String() string {
   254  	for _, details := range signatureAlgorithmDetails {
   255  		if details.algo == algo {
   256  			return details.name
   257  		}
   258  	}
   259  	return strconv.Itoa(int(algo))
   260  }
   261  
   262  type PublicKeyAlgorithm int
   263  
   264  const (
   265  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   266  	RSA
   267  	DSA // Only supported for parsing.
   268  	ECDSA
   269  	Ed25519
   270  )
   271  
   272  var publicKeyAlgoName = [...]string{
   273  	RSA:     "RSA",
   274  	DSA:     "DSA",
   275  	ECDSA:   "ECDSA",
   276  	Ed25519: "Ed25519",
   277  }
   278  
   279  func (algo PublicKeyAlgorithm) String() string {
   280  	if 0 < algo && int(algo) < len(publicKeyAlgoName) {
   281  		return publicKeyAlgoName[algo]
   282  	}
   283  	return strconv.Itoa(int(algo))
   284  }
   285  
   286  // OIDs for signature algorithms
   287  //
   288  //	pkcs-1 OBJECT IDENTIFIER ::= {
   289  //		iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   290  //
   291  // RFC 3279 2.2.1 RSA Signature Algorithms
   292  //
   293  //	md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   294  //
   295  //	sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   296  //
   297  //	dsaWithSha1 OBJECT IDENTIFIER ::= {
   298  //		iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   299  //
   300  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   301  //
   302  //	ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   303  //		iso(1) member-body(2) us(840) ansi-x962(10045)
   304  //		signatures(4) ecdsa-with-SHA1(1)}
   305  //
   306  // RFC 4055 5 PKCS #1 Version 1.5
   307  //
   308  //	sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   309  //
   310  //	sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   311  //
   312  //	sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   313  //
   314  // RFC 5758 3.1 DSA Signature Algorithms
   315  //
   316  //	dsaWithSha256 OBJECT IDENTIFIER ::= {
   317  //		joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   318  //		csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   319  //
   320  // RFC 5758 3.2 ECDSA Signature Algorithm
   321  //
   322  //	ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   323  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   324  //
   325  //	ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   326  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   327  //
   328  //	ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   329  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   330  //
   331  // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
   332  //
   333  //	id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   334  var (
   335  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   336  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   337  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   338  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   339  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   340  	oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
   341  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   342  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
   343  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   344  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   345  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   346  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   347  	oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
   348  
   349  	oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
   350  	oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
   351  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
   352  
   353  	oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
   354  
   355  	// oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
   356  	// but it's specified by ISO. Microsoft's makecert.exe has been known
   357  	// to produce certificates with this OID.
   358  	oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
   359  )
   360  
   361  var signatureAlgorithmDetails = []struct {
   362  	algo       SignatureAlgorithm
   363  	name       string
   364  	oid        asn1.ObjectIdentifier
   365  	params     asn1.RawValue
   366  	pubKeyAlgo PublicKeyAlgorithm
   367  	hash       crypto.Hash
   368  	isRSAPSS   bool
   369  }{
   370  	{MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, asn1.NullRawValue, RSA, crypto.MD5, false},
   371  	{SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
   372  	{SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
   373  	{SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, asn1.NullRawValue, RSA, crypto.SHA256, false},
   374  	{SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, asn1.NullRawValue, RSA, crypto.SHA384, false},
   375  	{SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, asn1.NullRawValue, RSA, crypto.SHA512, false},
   376  	{SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, pssParametersSHA256, RSA, crypto.SHA256, true},
   377  	{SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, pssParametersSHA384, RSA, crypto.SHA384, true},
   378  	{SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, pssParametersSHA512, RSA, crypto.SHA512, true},
   379  	{DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, emptyRawValue, DSA, crypto.SHA1, false},
   380  	{DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, emptyRawValue, DSA, crypto.SHA256, false},
   381  	{ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, emptyRawValue, ECDSA, crypto.SHA1, false},
   382  	{ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, emptyRawValue, ECDSA, crypto.SHA256, false},
   383  	{ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, emptyRawValue, ECDSA, crypto.SHA384, false},
   384  	{ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, emptyRawValue, ECDSA, crypto.SHA512, false},
   385  	{PureEd25519, "Ed25519", oidSignatureEd25519, emptyRawValue, Ed25519, crypto.Hash(0) /* no pre-hashing */, false},
   386  }
   387  
   388  var emptyRawValue = asn1.RawValue{}
   389  
   390  // DER encoded RSA PSS parameters for the
   391  // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
   392  // The parameters contain the following values:
   393  //   - hashAlgorithm contains the associated hash identifier with NULL parameters
   394  //   - maskGenAlgorithm always contains the default mgf1SHA1 identifier
   395  //   - saltLength contains the length of the associated hash
   396  //   - trailerField always contains the default trailerFieldBC value
   397  var (
   398  	pssParametersSHA256 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}}
   399  	pssParametersSHA384 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}}
   400  	pssParametersSHA512 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}}
   401  )
   402  
   403  // pssParameters reflects the parameters in an AlgorithmIdentifier that
   404  // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
   405  type pssParameters struct {
   406  	// The following three fields are not marked as
   407  	// optional because the default values specify SHA-1,
   408  	// which is no longer suitable for use in signatures.
   409  	Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
   410  	MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
   411  	SaltLength   int                      `asn1:"explicit,tag:2"`
   412  	TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
   413  }
   414  
   415  func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
   416  	if ai.Algorithm.Equal(oidSignatureEd25519) {
   417  		// RFC 8410, Section 3
   418  		// > For all of the OIDs, the parameters MUST be absent.
   419  		if len(ai.Parameters.FullBytes) != 0 {
   420  			return UnknownSignatureAlgorithm
   421  		}
   422  	}
   423  
   424  	if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
   425  		for _, details := range signatureAlgorithmDetails {
   426  			if ai.Algorithm.Equal(details.oid) {
   427  				return details.algo
   428  			}
   429  		}
   430  		return UnknownSignatureAlgorithm
   431  	}
   432  
   433  	// RSA PSS is special because it encodes important parameters
   434  	// in the Parameters.
   435  
   436  	var params pssParameters
   437  	if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
   438  		return UnknownSignatureAlgorithm
   439  	}
   440  
   441  	var mgf1HashFunc pkix.AlgorithmIdentifier
   442  	if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
   443  		return UnknownSignatureAlgorithm
   444  	}
   445  
   446  	// PSS is greatly overburdened with options. This code forces them into
   447  	// three buckets by requiring that the MGF1 hash function always match the
   448  	// message hash function (as recommended in RFC 3447, Section 8.1), that the
   449  	// salt length matches the hash length, and that the trailer field has the
   450  	// default value.
   451  	if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
   452  		!params.MGF.Algorithm.Equal(oidMGF1) ||
   453  		!mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
   454  		(len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
   455  		params.TrailerField != 1 {
   456  		return UnknownSignatureAlgorithm
   457  	}
   458  
   459  	switch {
   460  	case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
   461  		return SHA256WithRSAPSS
   462  	case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
   463  		return SHA384WithRSAPSS
   464  	case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
   465  		return SHA512WithRSAPSS
   466  	}
   467  
   468  	return UnknownSignatureAlgorithm
   469  }
   470  
   471  var (
   472  	// RFC 3279, 2.3 Public Key Algorithms
   473  	//
   474  	//	pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   475  	//		rsadsi(113549) pkcs(1) 1 }
   476  	//
   477  	// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   478  	//
   479  	//	id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   480  	//		x9-57(10040) x9cm(4) 1 }
   481  	oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   482  	oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   483  	// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   484  	//
   485  	//	id-ecPublicKey OBJECT IDENTIFIER ::= {
   486  	//		iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   487  	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   488  	// RFC 8410, Section 3
   489  	//
   490  	//	id-X25519    OBJECT IDENTIFIER ::= { 1 3 101 110 }
   491  	//	id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   492  	oidPublicKeyX25519  = asn1.ObjectIdentifier{1, 3, 101, 110}
   493  	oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
   494  )
   495  
   496  // getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
   497  // identifier for public key types supported in certificates and CSRs. Marshal
   498  // and Parse functions may support a different set of public key types.
   499  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   500  	switch {
   501  	case oid.Equal(oidPublicKeyRSA):
   502  		return RSA
   503  	case oid.Equal(oidPublicKeyDSA):
   504  		return DSA
   505  	case oid.Equal(oidPublicKeyECDSA):
   506  		return ECDSA
   507  	case oid.Equal(oidPublicKeyEd25519):
   508  		return Ed25519
   509  	}
   510  	return UnknownPublicKeyAlgorithm
   511  }
   512  
   513  // RFC 5480, 2.1.1.1. Named Curve
   514  //
   515  //	secp224r1 OBJECT IDENTIFIER ::= {
   516  //	  iso(1) identified-organization(3) certicom(132) curve(0) 33 }
   517  //
   518  //	secp256r1 OBJECT IDENTIFIER ::= {
   519  //	  iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   520  //	  prime(1) 7 }
   521  //
   522  //	secp384r1 OBJECT IDENTIFIER ::= {
   523  //	  iso(1) identified-organization(3) certicom(132) curve(0) 34 }
   524  //
   525  //	secp521r1 OBJECT IDENTIFIER ::= {
   526  //	  iso(1) identified-organization(3) certicom(132) curve(0) 35 }
   527  //
   528  // NB: secp256r1 is equivalent to prime256v1
   529  var (
   530  	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   531  	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   532  	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   533  	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   534  )
   535  
   536  func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
   537  	switch {
   538  	case oid.Equal(oidNamedCurveP224):
   539  		return elliptic.P224()
   540  	case oid.Equal(oidNamedCurveP256):
   541  		return elliptic.P256()
   542  	case oid.Equal(oidNamedCurveP384):
   543  		return elliptic.P384()
   544  	case oid.Equal(oidNamedCurveP521):
   545  		return elliptic.P521()
   546  	}
   547  	return nil
   548  }
   549  
   550  func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   551  	switch curve {
   552  	case elliptic.P224():
   553  		return oidNamedCurveP224, true
   554  	case elliptic.P256():
   555  		return oidNamedCurveP256, true
   556  	case elliptic.P384():
   557  		return oidNamedCurveP384, true
   558  	case elliptic.P521():
   559  		return oidNamedCurveP521, true
   560  	}
   561  
   562  	return nil, false
   563  }
   564  
   565  func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
   566  	switch curve {
   567  	case ecdh.X25519():
   568  		return oidPublicKeyX25519, true
   569  	case ecdh.P256():
   570  		return oidNamedCurveP256, true
   571  	case ecdh.P384():
   572  		return oidNamedCurveP384, true
   573  	case ecdh.P521():
   574  		return oidNamedCurveP521, true
   575  	}
   576  
   577  	return nil, false
   578  }
   579  
   580  // KeyUsage represents the set of actions that are valid for a given key. It's
   581  // a bitmap of the KeyUsage* constants.
   582  type KeyUsage int
   583  
   584  const (
   585  	KeyUsageDigitalSignature KeyUsage = 1 << iota
   586  	KeyUsageContentCommitment
   587  	KeyUsageKeyEncipherment
   588  	KeyUsageDataEncipherment
   589  	KeyUsageKeyAgreement
   590  	KeyUsageCertSign
   591  	KeyUsageCRLSign
   592  	KeyUsageEncipherOnly
   593  	KeyUsageDecipherOnly
   594  )
   595  
   596  // RFC 5280, 4.2.1.12  Extended Key Usage
   597  //
   598  //	anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   599  //
   600  //	id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   601  //
   602  //	id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   603  //	id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   604  //	id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   605  //	id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   606  //	id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   607  //	id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   608  var (
   609  	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   610  	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   611  	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   612  	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   613  	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   614  	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   615  	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   616  	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   617  	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   618  	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   619  	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   620  	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   621  	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
   622  	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
   623  )
   624  
   625  // ExtKeyUsage represents an extended set of actions that are valid for a given key.
   626  // Each of the ExtKeyUsage* constants define a unique action.
   627  type ExtKeyUsage int
   628  
   629  const (
   630  	ExtKeyUsageAny ExtKeyUsage = iota
   631  	ExtKeyUsageServerAuth
   632  	ExtKeyUsageClientAuth
   633  	ExtKeyUsageCodeSigning
   634  	ExtKeyUsageEmailProtection
   635  	ExtKeyUsageIPSECEndSystem
   636  	ExtKeyUsageIPSECTunnel
   637  	ExtKeyUsageIPSECUser
   638  	ExtKeyUsageTimeStamping
   639  	ExtKeyUsageOCSPSigning
   640  	ExtKeyUsageMicrosoftServerGatedCrypto
   641  	ExtKeyUsageNetscapeServerGatedCrypto
   642  	ExtKeyUsageMicrosoftCommercialCodeSigning
   643  	ExtKeyUsageMicrosoftKernelCodeSigning
   644  )
   645  
   646  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   647  var extKeyUsageOIDs = []struct {
   648  	extKeyUsage ExtKeyUsage
   649  	oid         asn1.ObjectIdentifier
   650  }{
   651  	{ExtKeyUsageAny, oidExtKeyUsageAny},
   652  	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   653  	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   654  	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   655  	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   656  	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   657  	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   658  	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   659  	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   660  	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   661  	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   662  	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   663  	{ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
   664  	{ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
   665  }
   666  
   667  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
   668  	for _, pair := range extKeyUsageOIDs {
   669  		if oid.Equal(pair.oid) {
   670  			return pair.extKeyUsage, true
   671  		}
   672  	}
   673  	return
   674  }
   675  
   676  func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   677  	for _, pair := range extKeyUsageOIDs {
   678  		if eku == pair.extKeyUsage {
   679  			return pair.oid, true
   680  		}
   681  	}
   682  	return
   683  }
   684  
   685  // A Certificate represents an X.509 certificate.
   686  type Certificate struct {
   687  	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
   688  	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
   689  	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
   690  	RawSubject              []byte // DER encoded Subject
   691  	RawIssuer               []byte // DER encoded Issuer
   692  
   693  	Signature          []byte
   694  	SignatureAlgorithm SignatureAlgorithm
   695  
   696  	PublicKeyAlgorithm PublicKeyAlgorithm
   697  	PublicKey          any
   698  
   699  	Version             int
   700  	SerialNumber        *big.Int
   701  	Issuer              pkix.Name
   702  	Subject             pkix.Name
   703  	NotBefore, NotAfter time.Time // Validity bounds.
   704  	KeyUsage            KeyUsage
   705  
   706  	// Extensions contains raw X.509 extensions. When parsing certificates,
   707  	// this can be used to extract non-critical extensions that are not
   708  	// parsed by this package. When marshaling certificates, the Extensions
   709  	// field is ignored, see ExtraExtensions.
   710  	Extensions []pkix.Extension
   711  
   712  	// ExtraExtensions contains extensions to be copied, raw, into any
   713  	// marshaled certificates. Values override any extensions that would
   714  	// otherwise be produced based on the other fields. The ExtraExtensions
   715  	// field is not populated when parsing certificates, see Extensions.
   716  	ExtraExtensions []pkix.Extension
   717  
   718  	// UnhandledCriticalExtensions contains a list of extension IDs that
   719  	// were not (fully) processed when parsing. Verify will fail if this
   720  	// slice is non-empty, unless verification is delegated to an OS
   721  	// library which understands all the critical extensions.
   722  	//
   723  	// Users can access these extensions using Extensions and can remove
   724  	// elements from this slice if they believe that they have been
   725  	// handled.
   726  	UnhandledCriticalExtensions []asn1.ObjectIdentifier
   727  
   728  	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
   729  	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
   730  
   731  	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
   732  	// and MaxPathLenZero are valid.
   733  	BasicConstraintsValid bool
   734  	IsCA                  bool
   735  
   736  	// MaxPathLen and MaxPathLenZero indicate the presence and
   737  	// value of the BasicConstraints' "pathLenConstraint".
   738  	//
   739  	// When parsing a certificate, a positive non-zero MaxPathLen
   740  	// means that the field was specified, -1 means it was unset,
   741  	// and MaxPathLenZero being true mean that the field was
   742  	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
   743  	// should be treated equivalent to -1 (unset).
   744  	//
   745  	// When generating a certificate, an unset pathLenConstraint
   746  	// can be requested with either MaxPathLen == -1 or using the
   747  	// zero value for both MaxPathLen and MaxPathLenZero.
   748  	MaxPathLen int
   749  	// MaxPathLenZero indicates that BasicConstraintsValid==true
   750  	// and MaxPathLen==0 should be interpreted as an actual
   751  	// maximum path length of zero. Otherwise, that combination is
   752  	// interpreted as MaxPathLen not being set.
   753  	MaxPathLenZero bool
   754  
   755  	SubjectKeyId   []byte
   756  	AuthorityKeyId []byte
   757  
   758  	// RFC 5280, 4.2.2.1 (Authority Information Access)
   759  	OCSPServer            []string
   760  	IssuingCertificateURL []string
   761  
   762  	// Subject Alternate Name values. (Note that these values may not be valid
   763  	// if invalid values were contained within a parsed certificate. For
   764  	// example, an element of DNSNames may not be a valid DNS domain name.)
   765  	DNSNames       []string
   766  	EmailAddresses []string
   767  	IPAddresses    []net.IP
   768  	URIs           []*url.URL
   769  
   770  	// Name constraints
   771  	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   772  	PermittedDNSDomains         []string
   773  	ExcludedDNSDomains          []string
   774  	PermittedIPRanges           []*net.IPNet
   775  	ExcludedIPRanges            []*net.IPNet
   776  	PermittedEmailAddresses     []string
   777  	ExcludedEmailAddresses      []string
   778  	PermittedURIDomains         []string
   779  	ExcludedURIDomains          []string
   780  
   781  	// CRL Distribution Points
   782  	CRLDistributionPoints []string
   783  
   784  	// PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
   785  	// of which are limited to int32. If a certificate contains a policy which
   786  	// cannot be represented by asn1.ObjectIdentifier, it will not be included in
   787  	// PolicyIdentifiers, but will be present in Policies, which contains all parsed
   788  	// policy OIDs.
   789  	PolicyIdentifiers []asn1.ObjectIdentifier
   790  
   791  	// Policies contains all policy identifiers included in the certificate.
   792  	// In Go 1.22, encoding/gob cannot handle and ignores this field.
   793  	Policies []OID
   794  }
   795  
   796  // ErrUnsupportedAlgorithm results from attempting to perform an operation that
   797  // involves algorithms that are not currently implemented.
   798  var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
   799  
   800  // An InsecureAlgorithmError indicates that the [SignatureAlgorithm] used to
   801  // generate the signature is not secure, and the signature has been rejected.
   802  //
   803  // To temporarily restore support for SHA-1 signatures, include the value
   804  // "x509sha1=1" in the GODEBUG environment variable. Note that this option will
   805  // be removed in a future release.
   806  type InsecureAlgorithmError SignatureAlgorithm
   807  
   808  func (e InsecureAlgorithmError) Error() string {
   809  	var override string
   810  	if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
   811  		override = " (temporarily override with GODEBUG=x509sha1=1)"
   812  	}
   813  	return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
   814  }
   815  
   816  // ConstraintViolationError results when a requested usage is not permitted by
   817  // a certificate. For example: checking a signature when the public key isn't a
   818  // certificate signing key.
   819  type ConstraintViolationError struct{}
   820  
   821  func (ConstraintViolationError) Error() string {
   822  	return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
   823  }
   824  
   825  func (c *Certificate) Equal(other *Certificate) bool {
   826  	if c == nil || other == nil {
   827  		return c == other
   828  	}
   829  	return bytes.Equal(c.Raw, other.Raw)
   830  }
   831  
   832  func (c *Certificate) hasSANExtension() bool {
   833  	return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
   834  }
   835  
   836  // CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
   837  //
   838  // This is a low-level API that performs very limited checks, and not a full
   839  // path verifier. Most users should use [Certificate.Verify] instead.
   840  func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
   841  	// RFC 5280, 4.2.1.9:
   842  	// "If the basic constraints extension is not present in a version 3
   843  	// certificate, or the extension is present but the cA boolean is not
   844  	// asserted, then the certified public key MUST NOT be used to verify
   845  	// certificate signatures."
   846  	if parent.Version == 3 && !parent.BasicConstraintsValid ||
   847  		parent.BasicConstraintsValid && !parent.IsCA {
   848  		return ConstraintViolationError{}
   849  	}
   850  
   851  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
   852  		return ConstraintViolationError{}
   853  	}
   854  
   855  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   856  		return ErrUnsupportedAlgorithm
   857  	}
   858  
   859  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
   860  }
   861  
   862  // CheckSignature verifies that signature is a valid signature over signed from
   863  // c's public key.
   864  //
   865  // This is a low-level API that performs no validity checks on the certificate.
   866  //
   867  // [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]
   868  // signatures are currently accepted.
   869  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
   870  	return checkSignature(algo, signed, signature, c.PublicKey, true)
   871  }
   872  
   873  func (c *Certificate) hasNameConstraints() bool {
   874  	return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
   875  }
   876  
   877  func (c *Certificate) getSANExtension() []byte {
   878  	for _, e := range c.Extensions {
   879  		if e.Id.Equal(oidExtensionSubjectAltName) {
   880  			return e.Value
   881  		}
   882  	}
   883  	return nil
   884  }
   885  
   886  func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
   887  	return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
   888  }
   889  
   890  var x509sha1 = godebug.New("x509sha1")
   891  
   892  // checkSignature verifies that signature is a valid signature over signed from
   893  // a crypto.PublicKey.
   894  func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
   895  	var hashType crypto.Hash
   896  	var pubKeyAlgo PublicKeyAlgorithm
   897  
   898  	for _, details := range signatureAlgorithmDetails {
   899  		if details.algo == algo {
   900  			hashType = details.hash
   901  			pubKeyAlgo = details.pubKeyAlgo
   902  			break
   903  		}
   904  	}
   905  
   906  	switch hashType {
   907  	case crypto.Hash(0):
   908  		if pubKeyAlgo != Ed25519 {
   909  			return ErrUnsupportedAlgorithm
   910  		}
   911  	case crypto.MD5:
   912  		return InsecureAlgorithmError(algo)
   913  	case crypto.SHA1:
   914  		// SHA-1 signatures are mostly disabled. See go.dev/issue/41682.
   915  		if !allowSHA1 {
   916  			if x509sha1.Value() != "1" {
   917  				return InsecureAlgorithmError(algo)
   918  			}
   919  			x509sha1.IncNonDefault()
   920  		}
   921  		fallthrough
   922  	default:
   923  		if !hashType.Available() {
   924  			return ErrUnsupportedAlgorithm
   925  		}
   926  		h := hashType.New()
   927  		h.Write(signed)
   928  		signed = h.Sum(nil)
   929  	}
   930  
   931  	switch pub := publicKey.(type) {
   932  	case *rsa.PublicKey:
   933  		if pubKeyAlgo != RSA {
   934  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   935  		}
   936  		if algo.isRSAPSS() {
   937  			return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
   938  		} else {
   939  			return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
   940  		}
   941  	case *ecdsa.PublicKey:
   942  		if pubKeyAlgo != ECDSA {
   943  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   944  		}
   945  		if !ecdsa.VerifyASN1(pub, signed, signature) {
   946  			return errors.New("x509: ECDSA verification failure")
   947  		}
   948  		return
   949  	case ed25519.PublicKey:
   950  		if pubKeyAlgo != Ed25519 {
   951  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   952  		}
   953  		if !ed25519.Verify(pub, signed, signature) {
   954  			return errors.New("x509: Ed25519 verification failure")
   955  		}
   956  		return
   957  	}
   958  	return ErrUnsupportedAlgorithm
   959  }
   960  
   961  // CheckCRLSignature checks that the signature in crl is from c.
   962  //
   963  // Deprecated: Use [RevocationList.CheckSignatureFrom] instead.
   964  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
   965  	algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
   966  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
   967  }
   968  
   969  type UnhandledCriticalExtension struct{}
   970  
   971  func (h UnhandledCriticalExtension) Error() string {
   972  	return "x509: unhandled critical extension"
   973  }
   974  
   975  type basicConstraints struct {
   976  	IsCA       bool `asn1:"optional"`
   977  	MaxPathLen int  `asn1:"optional,default:-1"`
   978  }
   979  
   980  // RFC 5280 4.2.1.4
   981  type policyInformation struct {
   982  	Policy asn1.ObjectIdentifier
   983  	// policyQualifiers omitted
   984  }
   985  
   986  const (
   987  	nameTypeEmail = 1
   988  	nameTypeDNS   = 2
   989  	nameTypeURI   = 6
   990  	nameTypeIP    = 7
   991  )
   992  
   993  // RFC 5280, 4.2.2.1
   994  type authorityInfoAccess struct {
   995  	Method   asn1.ObjectIdentifier
   996  	Location asn1.RawValue
   997  }
   998  
   999  // RFC 5280, 4.2.1.14
  1000  type distributionPoint struct {
  1001  	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  1002  	Reason            asn1.BitString        `asn1:"optional,tag:1"`
  1003  	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
  1004  }
  1005  
  1006  type distributionPointName struct {
  1007  	FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
  1008  	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  1009  }
  1010  
  1011  func reverseBitsInAByte(in byte) byte {
  1012  	b1 := in>>4 | in<<4
  1013  	b2 := b1>>2&0x33 | b1<<2&0xcc
  1014  	b3 := b2>>1&0x55 | b2<<1&0xaa
  1015  	return b3
  1016  }
  1017  
  1018  // asn1BitLength returns the bit-length of bitString by considering the
  1019  // most-significant bit in a byte to be the "first" bit. This convention
  1020  // matches ASN.1, but differs from almost everything else.
  1021  func asn1BitLength(bitString []byte) int {
  1022  	bitLen := len(bitString) * 8
  1023  
  1024  	for i := range bitString {
  1025  		b := bitString[len(bitString)-i-1]
  1026  
  1027  		for bit := uint(0); bit < 8; bit++ {
  1028  			if (b>>bit)&1 == 1 {
  1029  				return bitLen
  1030  			}
  1031  			bitLen--
  1032  		}
  1033  	}
  1034  
  1035  	return 0
  1036  }
  1037  
  1038  var (
  1039  	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
  1040  	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
  1041  	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
  1042  	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
  1043  	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
  1044  	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
  1045  	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
  1046  	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
  1047  	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  1048  	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  1049  	oidExtensionCRLNumber             = []int{2, 5, 29, 20}
  1050  	oidExtensionReasonCode            = []int{2, 5, 29, 21}
  1051  )
  1052  
  1053  var (
  1054  	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  1055  	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  1056  )
  1057  
  1058  // oidInExtensions reports whether an extension with the given oid exists in
  1059  // extensions.
  1060  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  1061  	for _, e := range extensions {
  1062  		if e.Id.Equal(oid) {
  1063  			return true
  1064  		}
  1065  	}
  1066  	return false
  1067  }
  1068  
  1069  // marshalSANs marshals a list of addresses into a the contents of an X.509
  1070  // SubjectAlternativeName extension.
  1071  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
  1072  	var rawValues []asn1.RawValue
  1073  	for _, name := range dnsNames {
  1074  		if err := isIA5String(name); err != nil {
  1075  			return nil, err
  1076  		}
  1077  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
  1078  	}
  1079  	for _, email := range emailAddresses {
  1080  		if err := isIA5String(email); err != nil {
  1081  			return nil, err
  1082  		}
  1083  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
  1084  	}
  1085  	for _, rawIP := range ipAddresses {
  1086  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
  1087  		ip := rawIP.To4()
  1088  		if ip == nil {
  1089  			ip = rawIP
  1090  		}
  1091  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
  1092  	}
  1093  	for _, uri := range uris {
  1094  		uriStr := uri.String()
  1095  		if err := isIA5String(uriStr); err != nil {
  1096  			return nil, err
  1097  		}
  1098  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
  1099  	}
  1100  	return asn1.Marshal(rawValues)
  1101  }
  1102  
  1103  func isIA5String(s string) error {
  1104  	for _, r := range s {
  1105  		// Per RFC5280 "IA5String is limited to the set of ASCII characters"
  1106  		if r > unicode.MaxASCII {
  1107  			return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
  1108  		}
  1109  	}
  1110  
  1111  	return nil
  1112  }
  1113  
  1114  var x509usepolicies = godebug.New("x509usepolicies")
  1115  
  1116  func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
  1117  	ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
  1118  	n := 0
  1119  
  1120  	if template.KeyUsage != 0 &&
  1121  		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1122  		ret[n], err = marshalKeyUsage(template.KeyUsage)
  1123  		if err != nil {
  1124  			return nil, err
  1125  		}
  1126  		n++
  1127  	}
  1128  
  1129  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1130  		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1131  		ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
  1132  		if err != nil {
  1133  			return nil, err
  1134  		}
  1135  		n++
  1136  	}
  1137  
  1138  	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1139  		ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
  1140  		if err != nil {
  1141  			return nil, err
  1142  		}
  1143  		n++
  1144  	}
  1145  
  1146  	if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1147  		ret[n].Id = oidExtensionSubjectKeyId
  1148  		ret[n].Value, err = asn1.Marshal(subjectKeyId)
  1149  		if err != nil {
  1150  			return
  1151  		}
  1152  		n++
  1153  	}
  1154  
  1155  	if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1156  		ret[n].Id = oidExtensionAuthorityKeyId
  1157  		ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
  1158  		if err != nil {
  1159  			return
  1160  		}
  1161  		n++
  1162  	}
  1163  
  1164  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1165  		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1166  		ret[n].Id = oidExtensionAuthorityInfoAccess
  1167  		var aiaValues []authorityInfoAccess
  1168  		for _, name := range template.OCSPServer {
  1169  			aiaValues = append(aiaValues, authorityInfoAccess{
  1170  				Method:   oidAuthorityInfoAccessOcsp,
  1171  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1172  			})
  1173  		}
  1174  		for _, name := range template.IssuingCertificateURL {
  1175  			aiaValues = append(aiaValues, authorityInfoAccess{
  1176  				Method:   oidAuthorityInfoAccessIssuers,
  1177  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1178  			})
  1179  		}
  1180  		ret[n].Value, err = asn1.Marshal(aiaValues)
  1181  		if err != nil {
  1182  			return
  1183  		}
  1184  		n++
  1185  	}
  1186  
  1187  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1188  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1189  		ret[n].Id = oidExtensionSubjectAltName
  1190  		// From RFC 5280, Section 4.2.1.6:
  1191  		// “If the subject field contains an empty sequence ... then
  1192  		// subjectAltName extension ... is marked as critical”
  1193  		ret[n].Critical = subjectIsEmpty
  1194  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1195  		if err != nil {
  1196  			return
  1197  		}
  1198  		n++
  1199  	}
  1200  
  1201  	usePolicies := x509usepolicies.Value() == "1"
  1202  	if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&
  1203  		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1204  		ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
  1205  		if err != nil {
  1206  			return nil, err
  1207  		}
  1208  		n++
  1209  	}
  1210  
  1211  	if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
  1212  		len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
  1213  		len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
  1214  		len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
  1215  		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1216  		ret[n].Id = oidExtensionNameConstraints
  1217  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1218  
  1219  		ipAndMask := func(ipNet *net.IPNet) []byte {
  1220  			maskedIP := ipNet.IP.Mask(ipNet.Mask)
  1221  			ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
  1222  			ipAndMask = append(ipAndMask, maskedIP...)
  1223  			ipAndMask = append(ipAndMask, ipNet.Mask...)
  1224  			return ipAndMask
  1225  		}
  1226  
  1227  		serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
  1228  			var b cryptobyte.Builder
  1229  
  1230  			for _, name := range dns {
  1231  				if err = isIA5String(name); err != nil {
  1232  					return nil, err
  1233  				}
  1234  
  1235  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1236  					b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
  1237  						b.AddBytes([]byte(name))
  1238  					})
  1239  				})
  1240  			}
  1241  
  1242  			for _, ipNet := range ips {
  1243  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1244  					b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
  1245  						b.AddBytes(ipAndMask(ipNet))
  1246  					})
  1247  				})
  1248  			}
  1249  
  1250  			for _, email := range emails {
  1251  				if err = isIA5String(email); err != nil {
  1252  					return nil, err
  1253  				}
  1254  
  1255  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1256  					b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
  1257  						b.AddBytes([]byte(email))
  1258  					})
  1259  				})
  1260  			}
  1261  
  1262  			for _, uriDomain := range uriDomains {
  1263  				if err = isIA5String(uriDomain); err != nil {
  1264  					return nil, err
  1265  				}
  1266  
  1267  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1268  					b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
  1269  						b.AddBytes([]byte(uriDomain))
  1270  					})
  1271  				})
  1272  			}
  1273  
  1274  			return b.Bytes()
  1275  		}
  1276  
  1277  		permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
  1278  		if err != nil {
  1279  			return nil, err
  1280  		}
  1281  
  1282  		excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
  1283  		if err != nil {
  1284  			return nil, err
  1285  		}
  1286  
  1287  		var b cryptobyte.Builder
  1288  		b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1289  			if len(permitted) > 0 {
  1290  				b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1291  					b.AddBytes(permitted)
  1292  				})
  1293  			}
  1294  
  1295  			if len(excluded) > 0 {
  1296  				b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1297  					b.AddBytes(excluded)
  1298  				})
  1299  			}
  1300  		})
  1301  
  1302  		ret[n].Value, err = b.Bytes()
  1303  		if err != nil {
  1304  			return nil, err
  1305  		}
  1306  		n++
  1307  	}
  1308  
  1309  	if len(template.CRLDistributionPoints) > 0 &&
  1310  		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1311  		ret[n].Id = oidExtensionCRLDistributionPoints
  1312  
  1313  		var crlDp []distributionPoint
  1314  		for _, name := range template.CRLDistributionPoints {
  1315  			dp := distributionPoint{
  1316  				DistributionPoint: distributionPointName{
  1317  					FullName: []asn1.RawValue{
  1318  						{Tag: 6, Class: 2, Bytes: []byte(name)},
  1319  					},
  1320  				},
  1321  			}
  1322  			crlDp = append(crlDp, dp)
  1323  		}
  1324  
  1325  		ret[n].Value, err = asn1.Marshal(crlDp)
  1326  		if err != nil {
  1327  			return
  1328  		}
  1329  		n++
  1330  	}
  1331  
  1332  	// Adding another extension here? Remember to update the maximum number
  1333  	// of elements in the make() at the top of the function and the list of
  1334  	// template fields used in CreateCertificate documentation.
  1335  
  1336  	return append(ret[:n], template.ExtraExtensions...), nil
  1337  }
  1338  
  1339  func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
  1340  	ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
  1341  
  1342  	var a [2]byte
  1343  	a[0] = reverseBitsInAByte(byte(ku))
  1344  	a[1] = reverseBitsInAByte(byte(ku >> 8))
  1345  
  1346  	l := 1
  1347  	if a[1] != 0 {
  1348  		l = 2
  1349  	}
  1350  
  1351  	bitString := a[:l]
  1352  	var err error
  1353  	ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1354  	return ext, err
  1355  }
  1356  
  1357  func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1358  	ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
  1359  
  1360  	oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
  1361  	for i, u := range extUsages {
  1362  		if oid, ok := oidFromExtKeyUsage(u); ok {
  1363  			oids[i] = oid
  1364  		} else {
  1365  			return ext, errors.New("x509: unknown extended key usage")
  1366  		}
  1367  	}
  1368  
  1369  	copy(oids[len(extUsages):], unknownUsages)
  1370  
  1371  	var err error
  1372  	ext.Value, err = asn1.Marshal(oids)
  1373  	return ext, err
  1374  }
  1375  
  1376  func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
  1377  	ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
  1378  	// Leaving MaxPathLen as zero indicates that no maximum path
  1379  	// length is desired, unless MaxPathLenZero is set. A value of
  1380  	// -1 causes encoding/asn1 to omit the value as desired.
  1381  	if maxPathLen == 0 && !maxPathLenZero {
  1382  		maxPathLen = -1
  1383  	}
  1384  	var err error
  1385  	ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
  1386  	return ext, err
  1387  }
  1388  
  1389  func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1390  	ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
  1391  
  1392  	b := cryptobyte.NewBuilder(make([]byte, 0, 128))
  1393  	b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
  1394  		if x509usepolicies.Value() == "1" {
  1395  			x509usepolicies.IncNonDefault()
  1396  			for _, v := range policies {
  1397  				child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
  1398  					child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
  1399  						if len(v.der) == 0 {
  1400  							child.SetError(errors.New("invalid policy object identifier"))
  1401  							return
  1402  						}
  1403  						child.AddBytes(v.der)
  1404  					})
  1405  				})
  1406  			}
  1407  		} else {
  1408  			for _, v := range policyIdentifiers {
  1409  				child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
  1410  					child.AddASN1ObjectIdentifier(v)
  1411  				})
  1412  			}
  1413  		}
  1414  	})
  1415  
  1416  	var err error
  1417  	ext.Value, err = b.Bytes()
  1418  	return ext, err
  1419  }
  1420  
  1421  func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
  1422  	var ret []pkix.Extension
  1423  
  1424  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1425  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1426  		sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1427  		if err != nil {
  1428  			return nil, err
  1429  		}
  1430  
  1431  		ret = append(ret, pkix.Extension{
  1432  			Id:    oidExtensionSubjectAltName,
  1433  			Value: sanBytes,
  1434  		})
  1435  	}
  1436  
  1437  	return append(ret, template.ExtraExtensions...), nil
  1438  }
  1439  
  1440  func subjectBytes(cert *Certificate) ([]byte, error) {
  1441  	if len(cert.RawSubject) > 0 {
  1442  		return cert.RawSubject, nil
  1443  	}
  1444  
  1445  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1446  }
  1447  
  1448  // signingParamsForKey returns the signature algorithm and its Algorithm
  1449  // Identifier to use for signing, based on the key type. If sigAlgo is not zero
  1450  // then it overrides the default.
  1451  func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
  1452  	var ai pkix.AlgorithmIdentifier
  1453  	var pubType PublicKeyAlgorithm
  1454  	var defaultAlgo SignatureAlgorithm
  1455  
  1456  	switch pub := key.Public().(type) {
  1457  	case *rsa.PublicKey:
  1458  		pubType = RSA
  1459  		defaultAlgo = SHA256WithRSA
  1460  
  1461  	case *ecdsa.PublicKey:
  1462  		pubType = ECDSA
  1463  		switch pub.Curve {
  1464  		case elliptic.P224(), elliptic.P256():
  1465  			defaultAlgo = ECDSAWithSHA256
  1466  		case elliptic.P384():
  1467  			defaultAlgo = ECDSAWithSHA384
  1468  		case elliptic.P521():
  1469  			defaultAlgo = ECDSAWithSHA512
  1470  		default:
  1471  			return 0, ai, errors.New("x509: unsupported elliptic curve")
  1472  		}
  1473  
  1474  	case ed25519.PublicKey:
  1475  		pubType = Ed25519
  1476  		defaultAlgo = PureEd25519
  1477  
  1478  	default:
  1479  		return 0, ai, errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
  1480  	}
  1481  
  1482  	if sigAlgo == 0 {
  1483  		sigAlgo = defaultAlgo
  1484  	}
  1485  
  1486  	for _, details := range signatureAlgorithmDetails {
  1487  		if details.algo == sigAlgo {
  1488  			if details.pubKeyAlgo != pubType {
  1489  				return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1490  			}
  1491  			if details.hash == crypto.MD5 {
  1492  				return 0, ai, errors.New("x509: signing with MD5 is not supported")
  1493  			}
  1494  
  1495  			return sigAlgo, pkix.AlgorithmIdentifier{
  1496  				Algorithm:  details.oid,
  1497  				Parameters: details.params,
  1498  			}, nil
  1499  		}
  1500  	}
  1501  
  1502  	return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
  1503  }
  1504  
  1505  func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
  1506  	signed := tbs
  1507  	hashFunc := sigAlg.hashFunc()
  1508  	if hashFunc != 0 {
  1509  		h := hashFunc.New()
  1510  		h.Write(signed)
  1511  		signed = h.Sum(nil)
  1512  	}
  1513  
  1514  	var signerOpts crypto.SignerOpts = hashFunc
  1515  	if sigAlg.isRSAPSS() {
  1516  		signerOpts = &rsa.PSSOptions{
  1517  			SaltLength: rsa.PSSSaltLengthEqualsHash,
  1518  			Hash:       hashFunc,
  1519  		}
  1520  	}
  1521  
  1522  	signature, err := key.Sign(rand, signed, signerOpts)
  1523  	if err != nil {
  1524  		return nil, err
  1525  	}
  1526  
  1527  	// Check the signature to ensure the crypto.Signer behaved correctly.
  1528  	if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
  1529  		return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
  1530  	}
  1531  
  1532  	return signature, nil
  1533  }
  1534  
  1535  // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
  1536  // just an empty SEQUENCE.
  1537  var emptyASN1Subject = []byte{0x30, 0}
  1538  
  1539  // CreateCertificate creates a new X.509 v3 certificate based on a template.
  1540  // The following members of template are currently used:
  1541  //
  1542  //   - AuthorityKeyId
  1543  //   - BasicConstraintsValid
  1544  //   - CRLDistributionPoints
  1545  //   - DNSNames
  1546  //   - EmailAddresses
  1547  //   - ExcludedDNSDomains
  1548  //   - ExcludedEmailAddresses
  1549  //   - ExcludedIPRanges
  1550  //   - ExcludedURIDomains
  1551  //   - ExtKeyUsage
  1552  //   - ExtraExtensions
  1553  //   - IPAddresses
  1554  //   - IsCA
  1555  //   - IssuingCertificateURL
  1556  //   - KeyUsage
  1557  //   - MaxPathLen
  1558  //   - MaxPathLenZero
  1559  //   - NotAfter
  1560  //   - NotBefore
  1561  //   - OCSPServer
  1562  //   - PermittedDNSDomains
  1563  //   - PermittedDNSDomainsCritical
  1564  //   - PermittedEmailAddresses
  1565  //   - PermittedIPRanges
  1566  //   - PermittedURIDomains
  1567  //   - PolicyIdentifiers (see note below)
  1568  //   - Policies (see note below)
  1569  //   - SerialNumber
  1570  //   - SignatureAlgorithm
  1571  //   - Subject
  1572  //   - SubjectKeyId
  1573  //   - URIs
  1574  //   - UnknownExtKeyUsage
  1575  //
  1576  // The certificate is signed by parent. If parent is equal to template then the
  1577  // certificate is self-signed. The parameter pub is the public key of the
  1578  // certificate to be generated and priv is the private key of the signer.
  1579  //
  1580  // The returned slice is the certificate in DER encoding.
  1581  //
  1582  // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
  1583  // ed25519.PublicKey. pub must be a supported key type, and priv must be a
  1584  // crypto.Signer with a supported public key.
  1585  //
  1586  // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
  1587  // unless the resulting certificate is self-signed. Otherwise the value from
  1588  // template will be used.
  1589  //
  1590  // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
  1591  // will be generated from the hash of the public key.
  1592  //
  1593  // The PolicyIdentifier and Policies fields are both used to marshal certificate
  1594  // policy OIDs. By default, only the PolicyIdentifier is marshaled, but if the
  1595  // GODEBUG setting "x509usepolicies" has the value "1", the Policies field will
  1596  // be marshaled instead of the PolicyIdentifier field. The Policies field can
  1597  // be used to marshal policy OIDs which have components that are larger than 31
  1598  // bits.
  1599  func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
  1600  	key, ok := priv.(crypto.Signer)
  1601  	if !ok {
  1602  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1603  	}
  1604  
  1605  	if template.SerialNumber == nil {
  1606  		return nil, errors.New("x509: no SerialNumber given")
  1607  	}
  1608  
  1609  	// RFC 5280 Section 4.1.2.2: serial number must positive
  1610  	//
  1611  	// We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people
  1612  	// get this wrong, in part because the encoding can itself alter the length of the
  1613  	// serial. For now we accept these non-conformant serials.
  1614  	if template.SerialNumber.Sign() == -1 {
  1615  		return nil, errors.New("x509: serial number must be positive")
  1616  	}
  1617  
  1618  	if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
  1619  		return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
  1620  	}
  1621  
  1622  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
  1623  	if err != nil {
  1624  		return nil, err
  1625  	}
  1626  
  1627  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  1628  	if err != nil {
  1629  		return nil, err
  1630  	}
  1631  	if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
  1632  		return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
  1633  	}
  1634  
  1635  	asn1Issuer, err := subjectBytes(parent)
  1636  	if err != nil {
  1637  		return nil, err
  1638  	}
  1639  
  1640  	asn1Subject, err := subjectBytes(template)
  1641  	if err != nil {
  1642  		return nil, err
  1643  	}
  1644  
  1645  	authorityKeyId := template.AuthorityKeyId
  1646  	if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
  1647  		authorityKeyId = parent.SubjectKeyId
  1648  	}
  1649  
  1650  	subjectKeyId := template.SubjectKeyId
  1651  	if len(subjectKeyId) == 0 && template.IsCA {
  1652  		// SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
  1653  		//   (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  1654  		//   value of the BIT STRING subjectPublicKey (excluding the tag,
  1655  		//   length, and number of unused bits).
  1656  		h := sha1.Sum(publicKeyBytes)
  1657  		subjectKeyId = h[:]
  1658  	}
  1659  
  1660  	// Check that the signer's public key matches the private key, if available.
  1661  	type privateKey interface {
  1662  		Equal(crypto.PublicKey) bool
  1663  	}
  1664  	if privPub, ok := key.Public().(privateKey); !ok {
  1665  		return nil, errors.New("x509: internal error: supported public key does not implement Equal")
  1666  	} else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
  1667  		return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
  1668  	}
  1669  
  1670  	extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
  1671  	if err != nil {
  1672  		return nil, err
  1673  	}
  1674  
  1675  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1676  	c := tbsCertificate{
  1677  		Version:            2,
  1678  		SerialNumber:       template.SerialNumber,
  1679  		SignatureAlgorithm: algorithmIdentifier,
  1680  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  1681  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1682  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  1683  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1684  		Extensions:         extensions,
  1685  	}
  1686  
  1687  	tbsCertContents, err := asn1.Marshal(c)
  1688  	if err != nil {
  1689  		return nil, err
  1690  	}
  1691  	c.Raw = tbsCertContents
  1692  
  1693  	signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
  1694  	if err != nil {
  1695  		return nil, err
  1696  	}
  1697  
  1698  	return asn1.Marshal(certificate{
  1699  		TBSCertificate:     c,
  1700  		SignatureAlgorithm: algorithmIdentifier,
  1701  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1702  	})
  1703  }
  1704  
  1705  // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  1706  // CRL.
  1707  var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  1708  
  1709  // pemType is the type of a PEM encoded CRL.
  1710  var pemType = "X509 CRL"
  1711  
  1712  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1713  // encoded CRLs will appear where they should be DER encoded, so this function
  1714  // will transparently handle PEM encoding as long as there isn't any leading
  1715  // garbage.
  1716  //
  1717  // Deprecated: Use [ParseRevocationList] instead.
  1718  func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
  1719  	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1720  		block, _ := pem.Decode(crlBytes)
  1721  		if block != nil && block.Type == pemType {
  1722  			crlBytes = block.Bytes
  1723  		}
  1724  	}
  1725  	return ParseDERCRL(crlBytes)
  1726  }
  1727  
  1728  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1729  //
  1730  // Deprecated: Use [ParseRevocationList] instead.
  1731  func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
  1732  	certList := new(pkix.CertificateList)
  1733  	if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
  1734  		return nil, err
  1735  	} else if len(rest) != 0 {
  1736  		return nil, errors.New("x509: trailing data after CRL")
  1737  	}
  1738  	return certList, nil
  1739  }
  1740  
  1741  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1742  // contains the given list of revoked certificates.
  1743  //
  1744  // Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
  1745  // To generate a standards compliant CRL, use [CreateRevocationList] instead.
  1746  func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1747  	key, ok := priv.(crypto.Signer)
  1748  	if !ok {
  1749  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1750  	}
  1751  
  1752  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
  1753  	if err != nil {
  1754  		return nil, err
  1755  	}
  1756  
  1757  	// Force revocation times to UTC per RFC 5280.
  1758  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  1759  	for i, rc := range revokedCerts {
  1760  		rc.RevocationTime = rc.RevocationTime.UTC()
  1761  		revokedCertsUTC[i] = rc
  1762  	}
  1763  
  1764  	tbsCertList := pkix.TBSCertificateList{
  1765  		Version:             1,
  1766  		Signature:           algorithmIdentifier,
  1767  		Issuer:              c.Subject.ToRDNSequence(),
  1768  		ThisUpdate:          now.UTC(),
  1769  		NextUpdate:          expiry.UTC(),
  1770  		RevokedCertificates: revokedCertsUTC,
  1771  	}
  1772  
  1773  	// Authority Key Id
  1774  	if len(c.SubjectKeyId) > 0 {
  1775  		var aki pkix.Extension
  1776  		aki.Id = oidExtensionAuthorityKeyId
  1777  		aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  1778  		if err != nil {
  1779  			return nil, err
  1780  		}
  1781  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  1782  	}
  1783  
  1784  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1785  	if err != nil {
  1786  		return nil, err
  1787  	}
  1788  	tbsCertList.Raw = tbsCertListContents
  1789  
  1790  	signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
  1791  	if err != nil {
  1792  		return nil, err
  1793  	}
  1794  
  1795  	return asn1.Marshal(pkix.CertificateList{
  1796  		TBSCertList:        tbsCertList,
  1797  		SignatureAlgorithm: algorithmIdentifier,
  1798  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1799  	})
  1800  }
  1801  
  1802  // CertificateRequest represents a PKCS #10, certificate signature request.
  1803  type CertificateRequest struct {
  1804  	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  1805  	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  1806  	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
  1807  	RawSubject               []byte // DER encoded Subject.
  1808  
  1809  	Version            int
  1810  	Signature          []byte
  1811  	SignatureAlgorithm SignatureAlgorithm
  1812  
  1813  	PublicKeyAlgorithm PublicKeyAlgorithm
  1814  	PublicKey          any
  1815  
  1816  	Subject pkix.Name
  1817  
  1818  	// Attributes contains the CSR attributes that can parse as
  1819  	// pkix.AttributeTypeAndValueSET.
  1820  	//
  1821  	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
  1822  	// generating the requestedExtensions attribute.
  1823  	Attributes []pkix.AttributeTypeAndValueSET
  1824  
  1825  	// Extensions contains all requested extensions, in raw form. When parsing
  1826  	// CSRs, this can be used to extract extensions that are not parsed by this
  1827  	// package.
  1828  	Extensions []pkix.Extension
  1829  
  1830  	// ExtraExtensions contains extensions to be copied, raw, into any CSR
  1831  	// marshaled by CreateCertificateRequest. Values override any extensions
  1832  	// that would otherwise be produced based on the other fields but are
  1833  	// overridden by any extensions specified in Attributes.
  1834  	//
  1835  	// The ExtraExtensions field is not populated by ParseCertificateRequest,
  1836  	// see Extensions instead.
  1837  	ExtraExtensions []pkix.Extension
  1838  
  1839  	// Subject Alternate Name values.
  1840  	DNSNames       []string
  1841  	EmailAddresses []string
  1842  	IPAddresses    []net.IP
  1843  	URIs           []*url.URL
  1844  }
  1845  
  1846  // These structures reflect the ASN.1 structure of X.509 certificate
  1847  // signature requests (see RFC 2986):
  1848  
  1849  type tbsCertificateRequest struct {
  1850  	Raw           asn1.RawContent
  1851  	Version       int
  1852  	Subject       asn1.RawValue
  1853  	PublicKey     publicKeyInfo
  1854  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  1855  }
  1856  
  1857  type certificateRequest struct {
  1858  	Raw                asn1.RawContent
  1859  	TBSCSR             tbsCertificateRequest
  1860  	SignatureAlgorithm pkix.AlgorithmIdentifier
  1861  	SignatureValue     asn1.BitString
  1862  }
  1863  
  1864  // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
  1865  // extensions in a CSR.
  1866  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  1867  
  1868  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  1869  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  1870  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  1871  	var rawAttributes []asn1.RawValue
  1872  	b, err := asn1.Marshal(attributes)
  1873  	if err != nil {
  1874  		return nil, err
  1875  	}
  1876  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  1877  	if err != nil {
  1878  		return nil, err
  1879  	}
  1880  	if len(rest) != 0 {
  1881  		return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  1882  	}
  1883  	return rawAttributes, nil
  1884  }
  1885  
  1886  // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
  1887  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  1888  	var attributes []pkix.AttributeTypeAndValueSET
  1889  	for _, rawAttr := range rawAttributes {
  1890  		var attr pkix.AttributeTypeAndValueSET
  1891  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  1892  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  1893  		// (i.e.: challengePassword or unstructuredName).
  1894  		if err == nil && len(rest) == 0 {
  1895  			attributes = append(attributes, attr)
  1896  		}
  1897  	}
  1898  	return attributes
  1899  }
  1900  
  1901  // parseCSRExtensions parses the attributes from a CSR and extracts any
  1902  // requested extensions.
  1903  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  1904  	// pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
  1905  	type pkcs10Attribute struct {
  1906  		Id     asn1.ObjectIdentifier
  1907  		Values []asn1.RawValue `asn1:"set"`
  1908  	}
  1909  
  1910  	var ret []pkix.Extension
  1911  	requestedExts := make(map[string]bool)
  1912  	for _, rawAttr := range rawAttributes {
  1913  		var attr pkcs10Attribute
  1914  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  1915  			// Ignore attributes that don't parse.
  1916  			continue
  1917  		}
  1918  
  1919  		if !attr.Id.Equal(oidExtensionRequest) {
  1920  			continue
  1921  		}
  1922  
  1923  		var extensions []pkix.Extension
  1924  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  1925  			return nil, err
  1926  		}
  1927  		for _, ext := range extensions {
  1928  			oidStr := ext.Id.String()
  1929  			if requestedExts[oidStr] {
  1930  				return nil, errors.New("x509: certificate request contains duplicate requested extensions")
  1931  			}
  1932  			requestedExts[oidStr] = true
  1933  		}
  1934  		ret = append(ret, extensions...)
  1935  	}
  1936  
  1937  	return ret, nil
  1938  }
  1939  
  1940  // CreateCertificateRequest creates a new certificate request based on a
  1941  // template. The following members of template are used:
  1942  //
  1943  //   - SignatureAlgorithm
  1944  //   - Subject
  1945  //   - DNSNames
  1946  //   - EmailAddresses
  1947  //   - IPAddresses
  1948  //   - URIs
  1949  //   - ExtraExtensions
  1950  //   - Attributes (deprecated)
  1951  //
  1952  // priv is the private key to sign the CSR with, and the corresponding public
  1953  // key will be included in the CSR. It must implement crypto.Signer and its
  1954  // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
  1955  // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
  1956  // ed25519.PrivateKey satisfies this.)
  1957  //
  1958  // The returned slice is the certificate request in DER encoding.
  1959  func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
  1960  	key, ok := priv.(crypto.Signer)
  1961  	if !ok {
  1962  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1963  	}
  1964  
  1965  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
  1966  	if err != nil {
  1967  		return nil, err
  1968  	}
  1969  
  1970  	var publicKeyBytes []byte
  1971  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1972  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  1973  	if err != nil {
  1974  		return nil, err
  1975  	}
  1976  
  1977  	extensions, err := buildCSRExtensions(template)
  1978  	if err != nil {
  1979  		return nil, err
  1980  	}
  1981  
  1982  	// Make a copy of template.Attributes because we may alter it below.
  1983  	attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
  1984  	for _, attr := range template.Attributes {
  1985  		values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
  1986  		copy(values, attr.Value)
  1987  		attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  1988  			Type:  attr.Type,
  1989  			Value: values,
  1990  		})
  1991  	}
  1992  
  1993  	extensionsAppended := false
  1994  	if len(extensions) > 0 {
  1995  		// Append the extensions to an existing attribute if possible.
  1996  		for _, atvSet := range attributes {
  1997  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  1998  				continue
  1999  			}
  2000  
  2001  			// specifiedExtensions contains all the extensions that we
  2002  			// found specified via template.Attributes.
  2003  			specifiedExtensions := make(map[string]bool)
  2004  
  2005  			for _, atvs := range atvSet.Value {
  2006  				for _, atv := range atvs {
  2007  					specifiedExtensions[atv.Type.String()] = true
  2008  				}
  2009  			}
  2010  
  2011  			newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
  2012  			newValue = append(newValue, atvSet.Value[0]...)
  2013  
  2014  			for _, e := range extensions {
  2015  				if specifiedExtensions[e.Id.String()] {
  2016  					// Attributes already contained a value for
  2017  					// this extension and it takes priority.
  2018  					continue
  2019  				}
  2020  
  2021  				newValue = append(newValue, pkix.AttributeTypeAndValue{
  2022  					// There is no place for the critical
  2023  					// flag in an AttributeTypeAndValue.
  2024  					Type:  e.Id,
  2025  					Value: e.Value,
  2026  				})
  2027  			}
  2028  
  2029  			atvSet.Value[0] = newValue
  2030  			extensionsAppended = true
  2031  			break
  2032  		}
  2033  	}
  2034  
  2035  	rawAttributes, err := newRawAttributes(attributes)
  2036  	if err != nil {
  2037  		return nil, err
  2038  	}
  2039  
  2040  	// If not included in attributes, add a new attribute for the
  2041  	// extensions.
  2042  	if len(extensions) > 0 && !extensionsAppended {
  2043  		attr := struct {
  2044  			Type  asn1.ObjectIdentifier
  2045  			Value [][]pkix.Extension `asn1:"set"`
  2046  		}{
  2047  			Type:  oidExtensionRequest,
  2048  			Value: [][]pkix.Extension{extensions},
  2049  		}
  2050  
  2051  		b, err := asn1.Marshal(attr)
  2052  		if err != nil {
  2053  			return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
  2054  		}
  2055  
  2056  		var rawValue asn1.RawValue
  2057  		if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
  2058  			return nil, err
  2059  		}
  2060  
  2061  		rawAttributes = append(rawAttributes, rawValue)
  2062  	}
  2063  
  2064  	asn1Subject := template.RawSubject
  2065  	if len(asn1Subject) == 0 {
  2066  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  2067  		if err != nil {
  2068  			return nil, err
  2069  		}
  2070  	}
  2071  
  2072  	tbsCSR := tbsCertificateRequest{
  2073  		Version: 0, // PKCS #10, RFC 2986
  2074  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  2075  		PublicKey: publicKeyInfo{
  2076  			Algorithm: publicKeyAlgorithm,
  2077  			PublicKey: asn1.BitString{
  2078  				Bytes:     publicKeyBytes,
  2079  				BitLength: len(publicKeyBytes) * 8,
  2080  			},
  2081  		},
  2082  		RawAttributes: rawAttributes,
  2083  	}
  2084  
  2085  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  2086  	if err != nil {
  2087  		return nil, err
  2088  	}
  2089  	tbsCSR.Raw = tbsCSRContents
  2090  
  2091  	signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
  2092  	if err != nil {
  2093  		return nil, err
  2094  	}
  2095  
  2096  	return asn1.Marshal(certificateRequest{
  2097  		TBSCSR:             tbsCSR,
  2098  		SignatureAlgorithm: algorithmIdentifier,
  2099  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2100  	})
  2101  }
  2102  
  2103  // ParseCertificateRequest parses a single certificate request from the
  2104  // given ASN.1 DER data.
  2105  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  2106  	var csr certificateRequest
  2107  
  2108  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  2109  	if err != nil {
  2110  		return nil, err
  2111  	} else if len(rest) != 0 {
  2112  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  2113  	}
  2114  
  2115  	return parseCertificateRequest(&csr)
  2116  }
  2117  
  2118  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  2119  	out := &CertificateRequest{
  2120  		Raw:                      in.Raw,
  2121  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  2122  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  2123  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  2124  
  2125  		Signature:          in.SignatureValue.RightAlign(),
  2126  		SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
  2127  
  2128  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  2129  
  2130  		Version:    in.TBSCSR.Version,
  2131  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  2132  	}
  2133  
  2134  	var err error
  2135  	if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
  2136  		out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
  2137  		if err != nil {
  2138  			return nil, err
  2139  		}
  2140  	}
  2141  
  2142  	var subject pkix.RDNSequence
  2143  	if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  2144  		return nil, err
  2145  	} else if len(rest) != 0 {
  2146  		return nil, errors.New("x509: trailing data after X.509 Subject")
  2147  	}
  2148  
  2149  	out.Subject.FillFromRDNSequence(&subject)
  2150  
  2151  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  2152  		return nil, err
  2153  	}
  2154  
  2155  	for _, extension := range out.Extensions {
  2156  		switch {
  2157  		case extension.Id.Equal(oidExtensionSubjectAltName):
  2158  			out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
  2159  			if err != nil {
  2160  				return nil, err
  2161  			}
  2162  		}
  2163  	}
  2164  
  2165  	return out, nil
  2166  }
  2167  
  2168  // CheckSignature reports whether the signature on c is valid.
  2169  func (c *CertificateRequest) CheckSignature() error {
  2170  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
  2171  }
  2172  
  2173  // RevocationListEntry represents an entry in the revokedCertificates
  2174  // sequence of a CRL.
  2175  type RevocationListEntry struct {
  2176  	// Raw contains the raw bytes of the revokedCertificates entry. It is set when
  2177  	// parsing a CRL; it is ignored when generating a CRL.
  2178  	Raw []byte
  2179  
  2180  	// SerialNumber represents the serial number of a revoked certificate. It is
  2181  	// both used when creating a CRL and populated when parsing a CRL. It must not
  2182  	// be nil.
  2183  	SerialNumber *big.Int
  2184  	// RevocationTime represents the time at which the certificate was revoked. It
  2185  	// is both used when creating a CRL and populated when parsing a CRL. It must
  2186  	// not be the zero time.
  2187  	RevocationTime time.Time
  2188  	// ReasonCode represents the reason for revocation, using the integer enum
  2189  	// values specified in RFC 5280 Section 5.3.1. When creating a CRL, the zero
  2190  	// value will result in the reasonCode extension being omitted. When parsing a
  2191  	// CRL, the zero value may represent either the reasonCode extension being
  2192  	// absent (which implies the default revocation reason of 0/Unspecified), or
  2193  	// it may represent the reasonCode extension being present and explicitly
  2194  	// containing a value of 0/Unspecified (which should not happen according to
  2195  	// the DER encoding rules, but can and does happen anyway).
  2196  	ReasonCode int
  2197  
  2198  	// Extensions contains raw X.509 extensions. When parsing CRL entries,
  2199  	// this can be used to extract non-critical extensions that are not
  2200  	// parsed by this package. When marshaling CRL entries, the Extensions
  2201  	// field is ignored, see ExtraExtensions.
  2202  	Extensions []pkix.Extension
  2203  	// ExtraExtensions contains extensions to be copied, raw, into any
  2204  	// marshaled CRL entries. Values override any extensions that would
  2205  	// otherwise be produced based on the other fields. The ExtraExtensions
  2206  	// field is not populated when parsing CRL entries, see Extensions.
  2207  	ExtraExtensions []pkix.Extension
  2208  }
  2209  
  2210  // RevocationList represents a [Certificate] Revocation List (CRL) as specified
  2211  // by RFC 5280.
  2212  type RevocationList struct {
  2213  	// Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
  2214  	// signatureAlgorithm, and signatureValue.)
  2215  	Raw []byte
  2216  	// RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
  2217  	// DER.
  2218  	RawTBSRevocationList []byte
  2219  	// RawIssuer contains the DER encoded Issuer.
  2220  	RawIssuer []byte
  2221  
  2222  	// Issuer contains the DN of the issuing certificate.
  2223  	Issuer pkix.Name
  2224  	// AuthorityKeyId is used to identify the public key associated with the
  2225  	// issuing certificate. It is populated from the authorityKeyIdentifier
  2226  	// extension when parsing a CRL. It is ignored when creating a CRL; the
  2227  	// extension is populated from the issuing certificate itself.
  2228  	AuthorityKeyId []byte
  2229  
  2230  	Signature []byte
  2231  	// SignatureAlgorithm is used to determine the signature algorithm to be
  2232  	// used when signing the CRL. If 0 the default algorithm for the signing
  2233  	// key will be used.
  2234  	SignatureAlgorithm SignatureAlgorithm
  2235  
  2236  	// RevokedCertificateEntries represents the revokedCertificates sequence in
  2237  	// the CRL. It is used when creating a CRL and also populated when parsing a
  2238  	// CRL. When creating a CRL, it may be empty or nil, in which case the
  2239  	// revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.
  2240  	RevokedCertificateEntries []RevocationListEntry
  2241  
  2242  	// RevokedCertificates is used to populate the revokedCertificates
  2243  	// sequence in the CRL if RevokedCertificateEntries is empty. It may be empty
  2244  	// or nil, in which case an empty CRL will be created.
  2245  	//
  2246  	// Deprecated: Use RevokedCertificateEntries instead.
  2247  	RevokedCertificates []pkix.RevokedCertificate
  2248  
  2249  	// Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
  2250  	// which should be a monotonically increasing sequence number for a given
  2251  	// CRL scope and CRL issuer. It is also populated from the cRLNumber
  2252  	// extension when parsing a CRL.
  2253  	Number *big.Int
  2254  
  2255  	// ThisUpdate is used to populate the thisUpdate field in the CRL, which
  2256  	// indicates the issuance date of the CRL.
  2257  	ThisUpdate time.Time
  2258  	// NextUpdate is used to populate the nextUpdate field in the CRL, which
  2259  	// indicates the date by which the next CRL will be issued. NextUpdate
  2260  	// must be greater than ThisUpdate.
  2261  	NextUpdate time.Time
  2262  
  2263  	// Extensions contains raw X.509 extensions. When creating a CRL,
  2264  	// the Extensions field is ignored, see ExtraExtensions.
  2265  	Extensions []pkix.Extension
  2266  
  2267  	// ExtraExtensions contains any additional extensions to add directly to
  2268  	// the CRL.
  2269  	ExtraExtensions []pkix.Extension
  2270  }
  2271  
  2272  // These structures reflect the ASN.1 structure of X.509 CRLs better than
  2273  // the existing crypto/x509/pkix variants do. These mirror the existing
  2274  // certificate structs in this file.
  2275  //
  2276  // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
  2277  // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
  2278  type certificateList struct {
  2279  	TBSCertList        tbsCertificateList
  2280  	SignatureAlgorithm pkix.AlgorithmIdentifier
  2281  	SignatureValue     asn1.BitString
  2282  }
  2283  
  2284  type tbsCertificateList struct {
  2285  	Raw                 asn1.RawContent
  2286  	Version             int `asn1:"optional,default:0"`
  2287  	Signature           pkix.AlgorithmIdentifier
  2288  	Issuer              asn1.RawValue
  2289  	ThisUpdate          time.Time
  2290  	NextUpdate          time.Time                 `asn1:"optional"`
  2291  	RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
  2292  	Extensions          []pkix.Extension          `asn1:"tag:0,optional,explicit"`
  2293  }
  2294  
  2295  // CreateRevocationList creates a new X.509 v2 [Certificate] Revocation List,
  2296  // according to RFC 5280, based on template.
  2297  //
  2298  // The CRL is signed by priv which should be the private key associated with
  2299  // the public key in the issuer certificate.
  2300  //
  2301  // The issuer may not be nil, and the crlSign bit must be set in [KeyUsage] in
  2302  // order to use it as a CRL issuer.
  2303  //
  2304  // The issuer distinguished name CRL field and authority key identifier
  2305  // extension are populated using the issuer certificate. issuer must have
  2306  // SubjectKeyId set.
  2307  func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
  2308  	if template == nil {
  2309  		return nil, errors.New("x509: template can not be nil")
  2310  	}
  2311  	if issuer == nil {
  2312  		return nil, errors.New("x509: issuer can not be nil")
  2313  	}
  2314  	if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
  2315  		return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
  2316  	}
  2317  	if len(issuer.SubjectKeyId) == 0 {
  2318  		return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
  2319  	}
  2320  	if template.NextUpdate.Before(template.ThisUpdate) {
  2321  		return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
  2322  	}
  2323  	if template.Number == nil {
  2324  		return nil, errors.New("x509: template contains nil Number field")
  2325  	}
  2326  
  2327  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
  2328  	if err != nil {
  2329  		return nil, err
  2330  	}
  2331  
  2332  	var revokedCerts []pkix.RevokedCertificate
  2333  	// Only process the deprecated RevokedCertificates field if it is populated
  2334  	// and the new RevokedCertificateEntries field is not populated.
  2335  	if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
  2336  		// Force revocation times to UTC per RFC 5280.
  2337  		revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
  2338  		for i, rc := range template.RevokedCertificates {
  2339  			rc.RevocationTime = rc.RevocationTime.UTC()
  2340  			revokedCerts[i] = rc
  2341  		}
  2342  	} else {
  2343  		// Convert the ReasonCode field to a proper extension, and force revocation
  2344  		// times to UTC per RFC 5280.
  2345  		revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
  2346  		for i, rce := range template.RevokedCertificateEntries {
  2347  			if rce.SerialNumber == nil {
  2348  				return nil, errors.New("x509: template contains entry with nil SerialNumber field")
  2349  			}
  2350  			if rce.RevocationTime.IsZero() {
  2351  				return nil, errors.New("x509: template contains entry with zero RevocationTime field")
  2352  			}
  2353  
  2354  			rc := pkix.RevokedCertificate{
  2355  				SerialNumber:   rce.SerialNumber,
  2356  				RevocationTime: rce.RevocationTime.UTC(),
  2357  			}
  2358  
  2359  			// Copy over any extra extensions, except for a Reason Code extension,
  2360  			// because we'll synthesize that ourselves to ensure it is correct.
  2361  			exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
  2362  			for _, ext := range rce.ExtraExtensions {
  2363  				if ext.Id.Equal(oidExtensionReasonCode) {
  2364  					return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
  2365  				}
  2366  				exts = append(exts, ext)
  2367  			}
  2368  
  2369  			// Only add a reasonCode extension if the reason is non-zero, as per
  2370  			// RFC 5280 Section 5.3.1.
  2371  			if rce.ReasonCode != 0 {
  2372  				reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
  2373  				if err != nil {
  2374  					return nil, err
  2375  				}
  2376  
  2377  				exts = append(exts, pkix.Extension{
  2378  					Id:    oidExtensionReasonCode,
  2379  					Value: reasonBytes,
  2380  				})
  2381  			}
  2382  
  2383  			if len(exts) > 0 {
  2384  				rc.Extensions = exts
  2385  			}
  2386  			revokedCerts[i] = rc
  2387  		}
  2388  	}
  2389  
  2390  	aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
  2391  	if err != nil {
  2392  		return nil, err
  2393  	}
  2394  
  2395  	if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
  2396  		return nil, errors.New("x509: CRL number exceeds 20 octets")
  2397  	}
  2398  	crlNum, err := asn1.Marshal(template.Number)
  2399  	if err != nil {
  2400  		return nil, err
  2401  	}
  2402  
  2403  	// Correctly use the issuer's subject sequence if one is specified.
  2404  	issuerSubject, err := subjectBytes(issuer)
  2405  	if err != nil {
  2406  		return nil, err
  2407  	}
  2408  
  2409  	tbsCertList := tbsCertificateList{
  2410  		Version:    1, // v2
  2411  		Signature:  algorithmIdentifier,
  2412  		Issuer:     asn1.RawValue{FullBytes: issuerSubject},
  2413  		ThisUpdate: template.ThisUpdate.UTC(),
  2414  		NextUpdate: template.NextUpdate.UTC(),
  2415  		Extensions: []pkix.Extension{
  2416  			{
  2417  				Id:    oidExtensionAuthorityKeyId,
  2418  				Value: aki,
  2419  			},
  2420  			{
  2421  				Id:    oidExtensionCRLNumber,
  2422  				Value: crlNum,
  2423  			},
  2424  		},
  2425  	}
  2426  	if len(revokedCerts) > 0 {
  2427  		tbsCertList.RevokedCertificates = revokedCerts
  2428  	}
  2429  
  2430  	if len(template.ExtraExtensions) > 0 {
  2431  		tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
  2432  	}
  2433  
  2434  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2435  	if err != nil {
  2436  		return nil, err
  2437  	}
  2438  
  2439  	// Optimization to only marshal this struct once, when signing and
  2440  	// then embedding in certificateList below.
  2441  	tbsCertList.Raw = tbsCertListContents
  2442  
  2443  	signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
  2444  	if err != nil {
  2445  		return nil, err
  2446  	}
  2447  
  2448  	return asn1.Marshal(certificateList{
  2449  		TBSCertList:        tbsCertList,
  2450  		SignatureAlgorithm: algorithmIdentifier,
  2451  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2452  	})
  2453  }
  2454  
  2455  // CheckSignatureFrom verifies that the signature on rl is a valid signature
  2456  // from issuer.
  2457  func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
  2458  	if parent.Version == 3 && !parent.BasicConstraintsValid ||
  2459  		parent.BasicConstraintsValid && !parent.IsCA {
  2460  		return ConstraintViolationError{}
  2461  	}
  2462  
  2463  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
  2464  		return ConstraintViolationError{}
  2465  	}
  2466  
  2467  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
  2468  		return ErrUnsupportedAlgorithm
  2469  	}
  2470  
  2471  	return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)
  2472  }
  2473  

View as plain text