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