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

View as plain text