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