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

View as plain text