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

View as plain text