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