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