Debian Codegraph @

src/crypto/x509/x509.go

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