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