github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/crypto/x509/x509.go (about)

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