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