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

View as plain text