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