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