Source file src/crypto/x509/x509.go

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

View as plain text