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 publicKeyBytes, err = pub.Bytes()
105 if err != nil {
106 return nil, pkix.AlgorithmIdentifier{}, err
107 }
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 //go:generate stringer -linecomment -type=KeyUsage,ExtKeyUsage -output=x509_string.go
586
587 const (
588 KeyUsageDigitalSignature KeyUsage = 1 << iota // digitalSignature
589 KeyUsageContentCommitment // contentCommitment
590 KeyUsageKeyEncipherment // keyEncipherment
591 KeyUsageDataEncipherment // dataEncipherment
592 KeyUsageKeyAgreement // keyAgreement
593 KeyUsageCertSign // keyCertSign
594 KeyUsageCRLSign // cRLSign
595 KeyUsageEncipherOnly // encipherOnly
596 KeyUsageDecipherOnly // decipherOnly
597 )
598
599 // RFC 5280, 4.2.1.12 Extended Key Usage
600 //
601 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
602 //
603 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
604 //
605 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
606 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
607 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
608 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
609 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
610 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
611 //
612 // https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.3
613 var (
614 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
615 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
616 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
617 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
618 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
619 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
620 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
621 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
622 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
623 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
624 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
625 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
626 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
627 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
628 )
629
630 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
631 // Each of the ExtKeyUsage* constants define a unique action.
632 type ExtKeyUsage int
633
634 const (
635 ExtKeyUsageAny ExtKeyUsage = iota // anyExtendedKeyUsage
636 ExtKeyUsageServerAuth // serverAuth
637 ExtKeyUsageClientAuth // clientAuth
638 ExtKeyUsageCodeSigning // codeSigning
639 ExtKeyUsageEmailProtection // emailProtection
640 ExtKeyUsageIPSECEndSystem // ipsecEndSystem
641 ExtKeyUsageIPSECTunnel // ipsecTunnel
642 ExtKeyUsageIPSECUser // ipsecUser
643 ExtKeyUsageTimeStamping // timeStamping
644 ExtKeyUsageOCSPSigning // OCSPSigning
645 ExtKeyUsageMicrosoftServerGatedCrypto // msSGC
646 ExtKeyUsageNetscapeServerGatedCrypto // nsSGC
647 ExtKeyUsageMicrosoftCommercialCodeSigning // msCodeCom
648 ExtKeyUsageMicrosoftKernelCodeSigning // msKernelCode
649 )
650
651 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
652 var extKeyUsageOIDs = []struct {
653 extKeyUsage ExtKeyUsage
654 oid asn1.ObjectIdentifier
655 }{
656 {ExtKeyUsageAny, oidExtKeyUsageAny},
657 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
658 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
659 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
660 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
661 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
662 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
663 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
664 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
665 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
666 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
667 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
668 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
669 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
670 }
671
672 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
673 for _, pair := range extKeyUsageOIDs {
674 if oid.Equal(pair.oid) {
675 return pair.extKeyUsage, true
676 }
677 }
678 return
679 }
680
681 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
682 for _, pair := range extKeyUsageOIDs {
683 if eku == pair.extKeyUsage {
684 return pair.oid, true
685 }
686 }
687 return
688 }
689
690 // OID returns the ASN.1 object identifier of the EKU.
691 func (eku ExtKeyUsage) OID() OID {
692 asn1OID, ok := oidFromExtKeyUsage(eku)
693 if !ok {
694 panic("x509: internal error: known ExtKeyUsage has no OID")
695 }
696 oid, err := OIDFromASN1OID(asn1OID)
697 if err != nil {
698 panic("x509: internal error: known ExtKeyUsage has invalid OID")
699 }
700 return oid
701 }
702
703 // A Certificate represents an X.509 certificate.
704 type Certificate struct {
705 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
706 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
707 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
708 RawSubject []byte // DER encoded Subject
709 RawIssuer []byte // DER encoded Issuer
710
711 Signature []byte
712 SignatureAlgorithm SignatureAlgorithm
713
714 PublicKeyAlgorithm PublicKeyAlgorithm
715 PublicKey any
716
717 Version int
718 SerialNumber *big.Int
719 Issuer pkix.Name
720 Subject pkix.Name
721 NotBefore, NotAfter time.Time // Validity bounds.
722 KeyUsage KeyUsage
723
724 // Extensions contains raw X.509 extensions. When parsing certificates,
725 // this can be used to extract non-critical extensions that are not
726 // parsed by this package. When marshaling certificates, the Extensions
727 // field is ignored, see ExtraExtensions.
728 Extensions []pkix.Extension
729
730 // ExtraExtensions contains extensions to be copied, raw, into any
731 // marshaled certificates. Values override any extensions that would
732 // otherwise be produced based on the other fields. The ExtraExtensions
733 // field is not populated when parsing certificates, see Extensions.
734 ExtraExtensions []pkix.Extension
735
736 // UnhandledCriticalExtensions contains a list of extension IDs that
737 // were not (fully) processed when parsing. Verify will fail if this
738 // slice is non-empty, unless verification is delegated to an OS
739 // library which understands all the critical extensions.
740 //
741 // Users can access these extensions using Extensions and can remove
742 // elements from this slice if they believe that they have been
743 // handled.
744 UnhandledCriticalExtensions []asn1.ObjectIdentifier
745
746 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
747 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
748
749 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
750 // and MaxPathLenZero are valid.
751 BasicConstraintsValid bool
752 IsCA bool
753
754 // MaxPathLen and MaxPathLenZero indicate the presence and
755 // value of the BasicConstraints' "pathLenConstraint".
756 //
757 // When parsing a certificate, a positive non-zero MaxPathLen
758 // means that the field was specified, -1 means it was unset,
759 // and MaxPathLenZero being true mean that the field was
760 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
761 // should be treated equivalent to -1 (unset).
762 //
763 // When generating a certificate, an unset pathLenConstraint
764 // can be requested with either MaxPathLen == -1 or using the
765 // zero value for both MaxPathLen and MaxPathLenZero.
766 MaxPathLen int
767 // MaxPathLenZero indicates that BasicConstraintsValid==true
768 // and MaxPathLen==0 should be interpreted as an actual
769 // maximum path length of zero. Otherwise, that combination is
770 // interpreted as MaxPathLen not being set.
771 MaxPathLenZero bool
772
773 SubjectKeyId []byte
774 AuthorityKeyId []byte
775
776 // RFC 5280, 4.2.2.1 (Authority Information Access)
777 OCSPServer []string
778 IssuingCertificateURL []string
779
780 // Subject Alternate Name values. (Note that these values may not be valid
781 // if invalid values were contained within a parsed certificate. For
782 // example, an element of DNSNames may not be a valid DNS domain name.)
783 DNSNames []string
784 EmailAddresses []string
785 IPAddresses []net.IP
786 URIs []*url.URL
787
788 // Name constraints
789 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
790 PermittedDNSDomains []string
791 ExcludedDNSDomains []string
792 PermittedIPRanges []*net.IPNet
793 ExcludedIPRanges []*net.IPNet
794 PermittedEmailAddresses []string
795 ExcludedEmailAddresses []string
796 PermittedURIDomains []string
797 ExcludedURIDomains []string
798
799 // CRL Distribution Points
800 CRLDistributionPoints []string
801
802 // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
803 // of which are limited to int32. If a certificate contains a policy which
804 // cannot be represented by asn1.ObjectIdentifier, it will not be included in
805 // PolicyIdentifiers, but will be present in Policies, which contains all parsed
806 // policy OIDs.
807 // See CreateCertificate for context about how this field and the Policies field
808 // interact.
809 PolicyIdentifiers []asn1.ObjectIdentifier
810
811 // Policies contains all policy identifiers included in the certificate.
812 // See CreateCertificate for context about how this field and the PolicyIdentifiers field
813 // interact.
814 // In Go 1.22, encoding/gob cannot handle and ignores this field.
815 Policies []OID
816
817 // InhibitAnyPolicy and InhibitAnyPolicyZero indicate the presence and value
818 // of the inhibitAnyPolicy extension.
819 //
820 // The value of InhibitAnyPolicy indicates the number of additional
821 // certificates in the path after this certificate that may use the
822 // anyPolicy policy OID to indicate a match with any other policy.
823 //
824 // When parsing a certificate, a positive non-zero InhibitAnyPolicy means
825 // that the field was specified, -1 means it was unset, and
826 // InhibitAnyPolicyZero being true mean that the field was explicitly set to
827 // zero. The case of InhibitAnyPolicy==0 with InhibitAnyPolicyZero==false
828 // should be treated equivalent to -1 (unset).
829 InhibitAnyPolicy int
830 // InhibitAnyPolicyZero indicates that InhibitAnyPolicy==0 should be
831 // interpreted as an actual maximum path length of zero. Otherwise, that
832 // combination is interpreted as InhibitAnyPolicy not being set.
833 InhibitAnyPolicyZero bool
834
835 // InhibitPolicyMapping and InhibitPolicyMappingZero indicate the presence
836 // and value of the inhibitPolicyMapping field of the policyConstraints
837 // extension.
838 //
839 // The value of InhibitPolicyMapping indicates the number of additional
840 // certificates in the path after this certificate that may use policy
841 // mapping.
842 //
843 // When parsing a certificate, a positive non-zero InhibitPolicyMapping
844 // means that the field was specified, -1 means it was unset, and
845 // InhibitPolicyMappingZero being true mean that the field was explicitly
846 // set to zero. The case of InhibitPolicyMapping==0 with
847 // InhibitPolicyMappingZero==false should be treated equivalent to -1
848 // (unset).
849 InhibitPolicyMapping int
850 // InhibitPolicyMappingZero indicates that InhibitPolicyMapping==0 should be
851 // interpreted as an actual maximum path length of zero. Otherwise, that
852 // combination is interpreted as InhibitAnyPolicy not being set.
853 InhibitPolicyMappingZero bool
854
855 // RequireExplicitPolicy and RequireExplicitPolicyZero indicate the presence
856 // and value of the requireExplicitPolicy field of the policyConstraints
857 // extension.
858 //
859 // The value of RequireExplicitPolicy indicates the number of additional
860 // certificates in the path after this certificate before an explicit policy
861 // is required for the rest of the path. When an explicit policy is required,
862 // each subsequent certificate in the path must contain a required policy OID,
863 // or a policy OID which has been declared as equivalent through the policy
864 // mapping extension.
865 //
866 // When parsing a certificate, a positive non-zero RequireExplicitPolicy
867 // means that the field was specified, -1 means it was unset, and
868 // RequireExplicitPolicyZero being true mean that the field was explicitly
869 // set to zero. The case of RequireExplicitPolicy==0 with
870 // RequireExplicitPolicyZero==false should be treated equivalent to -1
871 // (unset).
872 RequireExplicitPolicy int
873 // RequireExplicitPolicyZero indicates that RequireExplicitPolicy==0 should be
874 // interpreted as an actual maximum path length of zero. Otherwise, that
875 // combination is interpreted as InhibitAnyPolicy not being set.
876 RequireExplicitPolicyZero bool
877
878 // PolicyMappings contains a list of policy mappings included in the certificate.
879 PolicyMappings []PolicyMapping
880 }
881
882 // PolicyMapping represents a policy mapping entry in the policyMappings extension.
883 type PolicyMapping struct {
884 // IssuerDomainPolicy contains a policy OID the issuing certificate considers
885 // equivalent to SubjectDomainPolicy in the subject certificate.
886 IssuerDomainPolicy OID
887 // SubjectDomainPolicy contains a OID the issuing certificate considers
888 // equivalent to IssuerDomainPolicy in the subject certificate.
889 SubjectDomainPolicy OID
890 }
891
892 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
893 // involves algorithms that are not currently implemented.
894 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
895
896 // An InsecureAlgorithmError indicates that the [SignatureAlgorithm] used to
897 // generate the signature is not secure, and the signature has been rejected.
898 type InsecureAlgorithmError SignatureAlgorithm
899
900 func (e InsecureAlgorithmError) Error() string {
901 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
902 }
903
904 // ConstraintViolationError results when a requested usage is not permitted by
905 // a certificate. For example: checking a signature when the public key isn't a
906 // certificate signing key.
907 type ConstraintViolationError struct{}
908
909 func (ConstraintViolationError) Error() string {
910 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
911 }
912
913 func (c *Certificate) Equal(other *Certificate) bool {
914 if c == nil || other == nil {
915 return c == other
916 }
917 return bytes.Equal(c.Raw, other.Raw)
918 }
919
920 func (c *Certificate) hasSANExtension() bool {
921 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
922 }
923
924 // CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
925 //
926 // This is a low-level API that performs very limited checks, and not a full
927 // path verifier. Most users should use [Certificate.Verify] instead.
928 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
929 // RFC 5280, 4.2.1.9:
930 // "If the basic constraints extension is not present in a version 3
931 // certificate, or the extension is present but the cA boolean is not
932 // asserted, then the certified public key MUST NOT be used to verify
933 // certificate signatures."
934 if parent.Version == 3 && !parent.BasicConstraintsValid ||
935 parent.BasicConstraintsValid && !parent.IsCA {
936 return ConstraintViolationError{}
937 }
938
939 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
940 return ConstraintViolationError{}
941 }
942
943 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
944 return ErrUnsupportedAlgorithm
945 }
946
947 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
948 }
949
950 // CheckSignature verifies that signature is a valid signature over signed from
951 // c's public key.
952 //
953 // This is a low-level API that performs no validity checks on the certificate.
954 //
955 // [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]
956 // signatures are currently accepted.
957 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
958 return checkSignature(algo, signed, signature, c.PublicKey, true)
959 }
960
961 func (c *Certificate) hasNameConstraints() bool {
962 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
963 }
964
965 func (c *Certificate) getSANExtension() []byte {
966 for _, e := range c.Extensions {
967 if e.Id.Equal(oidExtensionSubjectAltName) {
968 return e.Value
969 }
970 }
971 return nil
972 }
973
974 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
975 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
976 }
977
978 // checkSignature verifies that signature is a valid signature over signed from
979 // a crypto.PublicKey.
980 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
981 var hashType crypto.Hash
982 var pubKeyAlgo PublicKeyAlgorithm
983
984 for _, details := range signatureAlgorithmDetails {
985 if details.algo == algo {
986 hashType = details.hash
987 pubKeyAlgo = details.pubKeyAlgo
988 break
989 }
990 }
991
992 switch hashType {
993 case crypto.Hash(0):
994 if pubKeyAlgo != Ed25519 {
995 return ErrUnsupportedAlgorithm
996 }
997 case crypto.MD5:
998 return InsecureAlgorithmError(algo)
999 case crypto.SHA1:
1000 // SHA-1 signatures are only allowed for CRLs and CSRs.
1001 if !allowSHA1 {
1002 return InsecureAlgorithmError(algo)
1003 }
1004 fallthrough
1005 default:
1006 if !hashType.Available() {
1007 return ErrUnsupportedAlgorithm
1008 }
1009 h := hashType.New()
1010 h.Write(signed)
1011 signed = h.Sum(nil)
1012 }
1013
1014 switch pub := publicKey.(type) {
1015 case *rsa.PublicKey:
1016 if pubKeyAlgo != RSA {
1017 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1018 }
1019 if algo.isRSAPSS() {
1020 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
1021 } else {
1022 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
1023 }
1024 case *ecdsa.PublicKey:
1025 if pubKeyAlgo != ECDSA {
1026 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1027 }
1028 if !ecdsa.VerifyASN1(pub, signed, signature) {
1029 return errors.New("x509: ECDSA verification failure")
1030 }
1031 return
1032 case ed25519.PublicKey:
1033 if pubKeyAlgo != Ed25519 {
1034 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1035 }
1036 if !ed25519.Verify(pub, signed, signature) {
1037 return errors.New("x509: Ed25519 verification failure")
1038 }
1039 return
1040 }
1041 return ErrUnsupportedAlgorithm
1042 }
1043
1044 // CheckCRLSignature checks that the signature in crl is from c.
1045 //
1046 // Deprecated: Use [RevocationList.CheckSignatureFrom] instead.
1047 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1048 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1049 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1050 }
1051
1052 type UnhandledCriticalExtension struct{}
1053
1054 func (h UnhandledCriticalExtension) Error() string {
1055 return "x509: unhandled critical extension"
1056 }
1057
1058 type basicConstraints struct {
1059 IsCA bool `asn1:"optional"`
1060 MaxPathLen int `asn1:"optional,default:-1"`
1061 }
1062
1063 // RFC 5280 4.2.1.4
1064 type policyInformation struct {
1065 Policy asn1.ObjectIdentifier
1066 // policyQualifiers omitted
1067 }
1068
1069 const (
1070 nameTypeEmail = 1
1071 nameTypeDNS = 2
1072 nameTypeURI = 6
1073 nameTypeIP = 7
1074 )
1075
1076 // RFC 5280, 4.2.2.1
1077 type authorityInfoAccess struct {
1078 Method asn1.ObjectIdentifier
1079 Location asn1.RawValue
1080 }
1081
1082 // RFC 5280, 4.2.1.14
1083 type distributionPoint struct {
1084 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1085 Reason asn1.BitString `asn1:"optional,tag:1"`
1086 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1087 }
1088
1089 type distributionPointName struct {
1090 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1091 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1092 }
1093
1094 func reverseBitsInAByte(in byte) byte {
1095 b1 := in>>4 | in<<4
1096 b2 := b1>>2&0x33 | b1<<2&0xcc
1097 b3 := b2>>1&0x55 | b2<<1&0xaa
1098 return b3
1099 }
1100
1101 // asn1BitLength returns the bit-length of bitString by considering the
1102 // most-significant bit in a byte to be the "first" bit. This convention
1103 // matches ASN.1, but differs from almost everything else.
1104 func asn1BitLength(bitString []byte) int {
1105 bitLen := len(bitString) * 8
1106
1107 for i := range bitString {
1108 b := bitString[len(bitString)-i-1]
1109
1110 for bit := uint(0); bit < 8; bit++ {
1111 if (b>>bit)&1 == 1 {
1112 return bitLen
1113 }
1114 bitLen--
1115 }
1116 }
1117
1118 return 0
1119 }
1120
1121 var (
1122 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1123 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1124 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1125 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1126 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1127 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1128 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1129 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1130 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1131 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1132 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1133 oidExtensionReasonCode = []int{2, 5, 29, 21}
1134 )
1135
1136 var (
1137 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1138 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1139 )
1140
1141 // oidInExtensions reports whether an extension with the given oid exists in
1142 // extensions.
1143 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1144 for _, e := range extensions {
1145 if e.Id.Equal(oid) {
1146 return true
1147 }
1148 }
1149 return false
1150 }
1151
1152 // marshalSANs marshals a list of addresses into a the contents of an X.509
1153 // SubjectAlternativeName extension.
1154 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1155 var rawValues []asn1.RawValue
1156 for _, name := range dnsNames {
1157 if err := isIA5String(name); err != nil {
1158 return nil, err
1159 }
1160 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1161 }
1162 for _, email := range emailAddresses {
1163 if err := isIA5String(email); err != nil {
1164 return nil, err
1165 }
1166 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1167 }
1168 for _, rawIP := range ipAddresses {
1169 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1170 ip := rawIP.To4()
1171 if ip == nil {
1172 ip = rawIP
1173 }
1174 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1175 }
1176 for _, uri := range uris {
1177 uriStr := uri.String()
1178 if err := isIA5String(uriStr); err != nil {
1179 return nil, err
1180 }
1181 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1182 }
1183 return asn1.Marshal(rawValues)
1184 }
1185
1186 func isIA5String(s string) error {
1187 for _, r := range s {
1188 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1189 if r > unicode.MaxASCII {
1190 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1191 }
1192 }
1193
1194 return nil
1195 }
1196
1197 var x509usepolicies = godebug.New("x509usepolicies")
1198
1199 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1200 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1201 n := 0
1202
1203 if template.KeyUsage != 0 &&
1204 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1205 ret[n], err = marshalKeyUsage(template.KeyUsage)
1206 if err != nil {
1207 return nil, err
1208 }
1209 n++
1210 }
1211
1212 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1213 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1214 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1215 if err != nil {
1216 return nil, err
1217 }
1218 n++
1219 }
1220
1221 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1222 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1223 if err != nil {
1224 return nil, err
1225 }
1226 n++
1227 }
1228
1229 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1230 ret[n].Id = oidExtensionSubjectKeyId
1231 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1232 if err != nil {
1233 return
1234 }
1235 n++
1236 }
1237
1238 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1239 ret[n].Id = oidExtensionAuthorityKeyId
1240 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1241 if err != nil {
1242 return
1243 }
1244 n++
1245 }
1246
1247 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1248 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1249 ret[n].Id = oidExtensionAuthorityInfoAccess
1250 var aiaValues []authorityInfoAccess
1251 for _, name := range template.OCSPServer {
1252 aiaValues = append(aiaValues, authorityInfoAccess{
1253 Method: oidAuthorityInfoAccessOcsp,
1254 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1255 })
1256 }
1257 for _, name := range template.IssuingCertificateURL {
1258 aiaValues = append(aiaValues, authorityInfoAccess{
1259 Method: oidAuthorityInfoAccessIssuers,
1260 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1261 })
1262 }
1263 ret[n].Value, err = asn1.Marshal(aiaValues)
1264 if err != nil {
1265 return
1266 }
1267 n++
1268 }
1269
1270 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1271 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1272 ret[n].Id = oidExtensionSubjectAltName
1273 // From RFC 5280, Section 4.2.1.6:
1274 // “If the subject field contains an empty sequence ... then
1275 // subjectAltName extension ... is marked as critical”
1276 ret[n].Critical = subjectIsEmpty
1277 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1278 if err != nil {
1279 return
1280 }
1281 n++
1282 }
1283
1284 usePolicies := x509usepolicies.Value() != "0"
1285 if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&
1286 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1287 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
1288 if err != nil {
1289 return nil, err
1290 }
1291 n++
1292 }
1293
1294 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1295 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1296 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1297 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1298 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1299 ret[n].Id = oidExtensionNameConstraints
1300 ret[n].Critical = template.PermittedDNSDomainsCritical
1301
1302 ipAndMask := func(ipNet *net.IPNet) []byte {
1303 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1304 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1305 ipAndMask = append(ipAndMask, maskedIP...)
1306 ipAndMask = append(ipAndMask, ipNet.Mask...)
1307 return ipAndMask
1308 }
1309
1310 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1311 var b cryptobyte.Builder
1312
1313 for _, name := range dns {
1314 if err = isIA5String(name); err != nil {
1315 return nil, err
1316 }
1317
1318 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1319 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1320 b.AddBytes([]byte(name))
1321 })
1322 })
1323 }
1324
1325 for _, ipNet := range ips {
1326 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1327 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1328 b.AddBytes(ipAndMask(ipNet))
1329 })
1330 })
1331 }
1332
1333 for _, email := range emails {
1334 if err = isIA5String(email); err != nil {
1335 return nil, err
1336 }
1337
1338 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1339 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1340 b.AddBytes([]byte(email))
1341 })
1342 })
1343 }
1344
1345 for _, uriDomain := range uriDomains {
1346 if err = isIA5String(uriDomain); err != nil {
1347 return nil, err
1348 }
1349
1350 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1351 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1352 b.AddBytes([]byte(uriDomain))
1353 })
1354 })
1355 }
1356
1357 return b.Bytes()
1358 }
1359
1360 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1361 if err != nil {
1362 return nil, err
1363 }
1364
1365 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1366 if err != nil {
1367 return nil, err
1368 }
1369
1370 var b cryptobyte.Builder
1371 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1372 if len(permitted) > 0 {
1373 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1374 b.AddBytes(permitted)
1375 })
1376 }
1377
1378 if len(excluded) > 0 {
1379 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1380 b.AddBytes(excluded)
1381 })
1382 }
1383 })
1384
1385 ret[n].Value, err = b.Bytes()
1386 if err != nil {
1387 return nil, err
1388 }
1389 n++
1390 }
1391
1392 if len(template.CRLDistributionPoints) > 0 &&
1393 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1394 ret[n].Id = oidExtensionCRLDistributionPoints
1395
1396 var crlDp []distributionPoint
1397 for _, name := range template.CRLDistributionPoints {
1398 dp := distributionPoint{
1399 DistributionPoint: distributionPointName{
1400 FullName: []asn1.RawValue{
1401 {Tag: 6, Class: 2, Bytes: []byte(name)},
1402 },
1403 },
1404 }
1405 crlDp = append(crlDp, dp)
1406 }
1407
1408 ret[n].Value, err = asn1.Marshal(crlDp)
1409 if err != nil {
1410 return
1411 }
1412 n++
1413 }
1414
1415 // Adding another extension here? Remember to update the maximum number
1416 // of elements in the make() at the top of the function and the list of
1417 // template fields used in CreateCertificate documentation.
1418
1419 return append(ret[:n], template.ExtraExtensions...), nil
1420 }
1421
1422 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1423 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1424
1425 var a [2]byte
1426 a[0] = reverseBitsInAByte(byte(ku))
1427 a[1] = reverseBitsInAByte(byte(ku >> 8))
1428
1429 l := 1
1430 if a[1] != 0 {
1431 l = 2
1432 }
1433
1434 bitString := a[:l]
1435 var err error
1436 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1437 return ext, err
1438 }
1439
1440 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1441 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1442
1443 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1444 for i, u := range extUsages {
1445 if oid, ok := oidFromExtKeyUsage(u); ok {
1446 oids[i] = oid
1447 } else {
1448 return ext, errors.New("x509: unknown extended key usage")
1449 }
1450 }
1451
1452 copy(oids[len(extUsages):], unknownUsages)
1453
1454 var err error
1455 ext.Value, err = asn1.Marshal(oids)
1456 return ext, err
1457 }
1458
1459 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1460 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1461 // Leaving MaxPathLen as zero indicates that no maximum path
1462 // length is desired, unless MaxPathLenZero is set. A value of
1463 // -1 causes encoding/asn1 to omit the value as desired.
1464 if maxPathLen == 0 && !maxPathLenZero {
1465 maxPathLen = -1
1466 }
1467 var err error
1468 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1469 return ext, err
1470 }
1471
1472 func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1473 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1474
1475 b := cryptobyte.NewBuilder(make([]byte, 0, 128))
1476 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1477 if x509usepolicies.Value() != "0" {
1478 x509usepolicies.IncNonDefault()
1479 for _, v := range policies {
1480 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1481 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
1482 if len(v.der) == 0 {
1483 child.SetError(errors.New("invalid policy object identifier"))
1484 return
1485 }
1486 child.AddBytes(v.der)
1487 })
1488 })
1489 }
1490 } else {
1491 for _, v := range policyIdentifiers {
1492 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1493 child.AddASN1ObjectIdentifier(v)
1494 })
1495 }
1496 }
1497 })
1498
1499 var err error
1500 ext.Value, err = b.Bytes()
1501 return ext, err
1502 }
1503
1504 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1505 var ret []pkix.Extension
1506
1507 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1508 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1509 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1510 if err != nil {
1511 return nil, err
1512 }
1513
1514 ret = append(ret, pkix.Extension{
1515 Id: oidExtensionSubjectAltName,
1516 Value: sanBytes,
1517 })
1518 }
1519
1520 return append(ret, template.ExtraExtensions...), nil
1521 }
1522
1523 func subjectBytes(cert *Certificate) ([]byte, error) {
1524 if len(cert.RawSubject) > 0 {
1525 return cert.RawSubject, nil
1526 }
1527
1528 return asn1.Marshal(cert.Subject.ToRDNSequence())
1529 }
1530
1531 // signingParamsForKey returns the signature algorithm and its Algorithm
1532 // Identifier to use for signing, based on the key type. If sigAlgo is not zero
1533 // then it overrides the default.
1534 func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
1535 var ai pkix.AlgorithmIdentifier
1536 var pubType PublicKeyAlgorithm
1537 var defaultAlgo SignatureAlgorithm
1538
1539 switch pub := key.Public().(type) {
1540 case *rsa.PublicKey:
1541 pubType = RSA
1542 defaultAlgo = SHA256WithRSA
1543
1544 case *ecdsa.PublicKey:
1545 pubType = ECDSA
1546 switch pub.Curve {
1547 case elliptic.P224(), elliptic.P256():
1548 defaultAlgo = ECDSAWithSHA256
1549 case elliptic.P384():
1550 defaultAlgo = ECDSAWithSHA384
1551 case elliptic.P521():
1552 defaultAlgo = ECDSAWithSHA512
1553 default:
1554 return 0, ai, errors.New("x509: unsupported elliptic curve")
1555 }
1556
1557 case ed25519.PublicKey:
1558 pubType = Ed25519
1559 defaultAlgo = PureEd25519
1560
1561 default:
1562 return 0, ai, errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1563 }
1564
1565 if sigAlgo == 0 {
1566 sigAlgo = defaultAlgo
1567 }
1568
1569 for _, details := range signatureAlgorithmDetails {
1570 if details.algo == sigAlgo {
1571 if details.pubKeyAlgo != pubType {
1572 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
1573 }
1574 if details.hash == crypto.MD5 {
1575 return 0, ai, errors.New("x509: signing with MD5 is not supported")
1576 }
1577
1578 return sigAlgo, pkix.AlgorithmIdentifier{
1579 Algorithm: details.oid,
1580 Parameters: details.params,
1581 }, nil
1582 }
1583 }
1584
1585 return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
1586 }
1587
1588 func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
1589 hashFunc := sigAlg.hashFunc()
1590
1591 var signerOpts crypto.SignerOpts = hashFunc
1592 if sigAlg.isRSAPSS() {
1593 signerOpts = &rsa.PSSOptions{
1594 SaltLength: rsa.PSSSaltLengthEqualsHash,
1595 Hash: hashFunc,
1596 }
1597 }
1598
1599 signature, err := crypto.SignMessage(key, rand, tbs, signerOpts)
1600 if err != nil {
1601 return nil, err
1602 }
1603
1604 // Check the signature to ensure the crypto.Signer behaved correctly.
1605 if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
1606 return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
1607 }
1608
1609 return signature, nil
1610 }
1611
1612 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1613 // just an empty SEQUENCE.
1614 var emptyASN1Subject = []byte{0x30, 0}
1615
1616 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1617 // The following members of template are currently used:
1618 //
1619 // - AuthorityKeyId
1620 // - BasicConstraintsValid
1621 // - CRLDistributionPoints
1622 // - DNSNames
1623 // - EmailAddresses
1624 // - ExcludedDNSDomains
1625 // - ExcludedEmailAddresses
1626 // - ExcludedIPRanges
1627 // - ExcludedURIDomains
1628 // - ExtKeyUsage
1629 // - ExtraExtensions
1630 // - IPAddresses
1631 // - IsCA
1632 // - IssuingCertificateURL
1633 // - KeyUsage
1634 // - MaxPathLen
1635 // - MaxPathLenZero
1636 // - NotAfter
1637 // - NotBefore
1638 // - OCSPServer
1639 // - PermittedDNSDomains
1640 // - PermittedDNSDomainsCritical
1641 // - PermittedEmailAddresses
1642 // - PermittedIPRanges
1643 // - PermittedURIDomains
1644 // - PolicyIdentifiers (see note below)
1645 // - Policies (see note below)
1646 // - SerialNumber
1647 // - SignatureAlgorithm
1648 // - Subject
1649 // - SubjectKeyId
1650 // - URIs
1651 // - UnknownExtKeyUsage
1652 //
1653 // The certificate is signed by parent. If parent is equal to template then the
1654 // certificate is self-signed. The parameter pub is the public key of the
1655 // certificate to be generated and priv is the private key of the signer.
1656 //
1657 // The returned slice is the certificate in DER encoding.
1658 //
1659 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1660 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1661 // crypto.Signer or crypto.MessageSigner with a supported public key.
1662 //
1663 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1664 // unless the resulting certificate is self-signed. Otherwise the value from
1665 // template will be used.
1666 //
1667 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1668 // will be generated from the hash of the public key.
1669 //
1670 // If template.SerialNumber is nil, a serial number will be generated which
1671 // conforms to RFC 5280, Section 4.1.2.2 using entropy from rand.
1672 //
1673 // The PolicyIdentifier and Policies fields can both be used to marshal certificate
1674 // policy OIDs. By default, only the Policies is marshaled, but if the
1675 // GODEBUG setting "x509usepolicies" has the value "0", the PolicyIdentifiers field will
1676 // be marshaled instead of the Policies field. This changed in Go 1.24. The Policies field can
1677 // be used to marshal policy OIDs which have components that are larger than 31
1678 // bits.
1679 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1680 key, ok := priv.(crypto.Signer)
1681 if !ok {
1682 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1683 }
1684
1685 serialNumber := template.SerialNumber
1686 if serialNumber == nil {
1687 // Generate a serial number following RFC 5280, Section 4.1.2.2 if one
1688 // is not provided. The serial number must be positive and at most 20
1689 // octets *when encoded*.
1690 serialBytes := make([]byte, 20)
1691 if _, err := io.ReadFull(rand, serialBytes); err != nil {
1692 return nil, err
1693 }
1694 // If the top bit is set, the serial will be padded with a leading zero
1695 // byte during encoding, so that it's not interpreted as a negative
1696 // integer. This padding would make the serial 21 octets so we clear the
1697 // top bit to ensure the correct length in all cases.
1698 serialBytes[0] &= 0b0111_1111
1699 serialNumber = new(big.Int).SetBytes(serialBytes)
1700 }
1701
1702 // RFC 5280 Section 4.1.2.2: serial number must be positive
1703 //
1704 // We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people
1705 // get this wrong, in part because the encoding can itself alter the length of the
1706 // serial. For now we accept these non-conformant serials.
1707 if serialNumber.Sign() == -1 {
1708 return nil, errors.New("x509: serial number must be positive")
1709 }
1710
1711 if template.BasicConstraintsValid && template.MaxPathLen < -1 {
1712 return nil, errors.New("x509: invalid MaxPathLen, must be greater or equal to -1")
1713 }
1714
1715 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1716 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1717 }
1718
1719 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
1720 if err != nil {
1721 return nil, err
1722 }
1723
1724 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1725 if err != nil {
1726 return nil, err
1727 }
1728 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1729 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1730 }
1731
1732 asn1Issuer, err := subjectBytes(parent)
1733 if err != nil {
1734 return nil, err
1735 }
1736
1737 asn1Subject, err := subjectBytes(template)
1738 if err != nil {
1739 return nil, err
1740 }
1741
1742 authorityKeyId := template.AuthorityKeyId
1743 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1744 authorityKeyId = parent.SubjectKeyId
1745 }
1746
1747 subjectKeyId := template.SubjectKeyId
1748 if len(subjectKeyId) == 0 && template.IsCA {
1749 if x509sha256skid.Value() == "0" {
1750 x509sha256skid.IncNonDefault()
1751 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1752 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1753 // value of the BIT STRING subjectPublicKey (excluding the tag,
1754 // length, and number of unused bits).
1755 h := sha1.Sum(publicKeyBytes)
1756 subjectKeyId = h[:]
1757 } else {
1758 // SubjectKeyId generated using method 1 in RFC 7093, Section 2:
1759 // 1) The keyIdentifier is composed of the leftmost 160-bits of the
1760 // SHA-256 hash of the value of the BIT STRING subjectPublicKey
1761 // (excluding the tag, length, and number of unused bits).
1762 h := sha256.Sum256(publicKeyBytes)
1763 subjectKeyId = h[:20]
1764 }
1765 }
1766
1767 // Check that the signer's public key matches the private key, if available.
1768 type privateKey interface {
1769 Equal(crypto.PublicKey) bool
1770 }
1771 if privPub, ok := key.Public().(privateKey); !ok {
1772 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1773 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1774 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1775 }
1776
1777 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1778 if err != nil {
1779 return nil, err
1780 }
1781
1782 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1783 c := tbsCertificate{
1784 Version: 2,
1785 SerialNumber: serialNumber,
1786 SignatureAlgorithm: algorithmIdentifier,
1787 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1788 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1789 Subject: asn1.RawValue{FullBytes: asn1Subject},
1790 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1791 Extensions: extensions,
1792 }
1793
1794 tbsCertContents, err := asn1.Marshal(c)
1795 if err != nil {
1796 return nil, err
1797 }
1798 c.Raw = tbsCertContents
1799
1800 signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
1801 if err != nil {
1802 return nil, err
1803 }
1804
1805 return asn1.Marshal(certificate{
1806 TBSCertificate: c,
1807 SignatureAlgorithm: algorithmIdentifier,
1808 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1809 })
1810 }
1811
1812 var x509sha256skid = godebug.New("x509sha256skid")
1813
1814 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1815 // CRL.
1816 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1817
1818 // pemType is the type of a PEM encoded CRL.
1819 var pemType = "X509 CRL"
1820
1821 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1822 // encoded CRLs will appear where they should be DER encoded, so this function
1823 // will transparently handle PEM encoding as long as there isn't any leading
1824 // garbage.
1825 //
1826 // Deprecated: Use [ParseRevocationList] instead.
1827 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1828 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1829 block, _ := pem.Decode(crlBytes)
1830 if block != nil && block.Type == pemType {
1831 crlBytes = block.Bytes
1832 }
1833 }
1834 return ParseDERCRL(crlBytes)
1835 }
1836
1837 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1838 //
1839 // Deprecated: Use [ParseRevocationList] instead.
1840 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1841 certList := new(pkix.CertificateList)
1842 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1843 return nil, err
1844 } else if len(rest) != 0 {
1845 return nil, errors.New("x509: trailing data after CRL")
1846 }
1847 return certList, nil
1848 }
1849
1850 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1851 // contains the given list of revoked certificates.
1852 //
1853 // Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1854 // To generate a standards compliant CRL, use [CreateRevocationList] instead.
1855 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1856 key, ok := priv.(crypto.Signer)
1857 if !ok {
1858 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1859 }
1860
1861 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
1862 if err != nil {
1863 return nil, err
1864 }
1865
1866 // Force revocation times to UTC per RFC 5280.
1867 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1868 for i, rc := range revokedCerts {
1869 rc.RevocationTime = rc.RevocationTime.UTC()
1870 revokedCertsUTC[i] = rc
1871 }
1872
1873 tbsCertList := pkix.TBSCertificateList{
1874 Version: 1,
1875 Signature: algorithmIdentifier,
1876 Issuer: c.Subject.ToRDNSequence(),
1877 ThisUpdate: now.UTC(),
1878 NextUpdate: expiry.UTC(),
1879 RevokedCertificates: revokedCertsUTC,
1880 }
1881
1882 // Authority Key Id
1883 if len(c.SubjectKeyId) > 0 {
1884 var aki pkix.Extension
1885 aki.Id = oidExtensionAuthorityKeyId
1886 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1887 if err != nil {
1888 return nil, err
1889 }
1890 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1891 }
1892
1893 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1894 if err != nil {
1895 return nil, err
1896 }
1897 tbsCertList.Raw = tbsCertListContents
1898
1899 signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
1900 if err != nil {
1901 return nil, err
1902 }
1903
1904 return asn1.Marshal(pkix.CertificateList{
1905 TBSCertList: tbsCertList,
1906 SignatureAlgorithm: algorithmIdentifier,
1907 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1908 })
1909 }
1910
1911 // CertificateRequest represents a PKCS #10, certificate signature request.
1912 type CertificateRequest struct {
1913 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1914 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1915 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1916 RawSubject []byte // DER encoded Subject.
1917
1918 Version int
1919 Signature []byte
1920 SignatureAlgorithm SignatureAlgorithm
1921
1922 PublicKeyAlgorithm PublicKeyAlgorithm
1923 PublicKey any
1924
1925 Subject pkix.Name
1926
1927 // Attributes contains the CSR attributes that can parse as
1928 // pkix.AttributeTypeAndValueSET.
1929 //
1930 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1931 // generating the requestedExtensions attribute.
1932 Attributes []pkix.AttributeTypeAndValueSET
1933
1934 // Extensions contains all requested extensions, in raw form. When parsing
1935 // CSRs, this can be used to extract extensions that are not parsed by this
1936 // package.
1937 Extensions []pkix.Extension
1938
1939 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1940 // marshaled by CreateCertificateRequest. Values override any extensions
1941 // that would otherwise be produced based on the other fields but are
1942 // overridden by any extensions specified in Attributes.
1943 //
1944 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1945 // see Extensions instead.
1946 ExtraExtensions []pkix.Extension
1947
1948 // Subject Alternate Name values.
1949 DNSNames []string
1950 EmailAddresses []string
1951 IPAddresses []net.IP
1952 URIs []*url.URL
1953 }
1954
1955 // These structures reflect the ASN.1 structure of X.509 certificate
1956 // signature requests (see RFC 2986):
1957
1958 type tbsCertificateRequest struct {
1959 Raw asn1.RawContent
1960 Version int
1961 Subject asn1.RawValue
1962 PublicKey publicKeyInfo
1963 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1964 }
1965
1966 type certificateRequest struct {
1967 Raw asn1.RawContent
1968 TBSCSR tbsCertificateRequest
1969 SignatureAlgorithm pkix.AlgorithmIdentifier
1970 SignatureValue asn1.BitString
1971 }
1972
1973 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1974 // extensions in a CSR.
1975 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1976
1977 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1978 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1979 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1980 var rawAttributes []asn1.RawValue
1981 b, err := asn1.Marshal(attributes)
1982 if err != nil {
1983 return nil, err
1984 }
1985 rest, err := asn1.Unmarshal(b, &rawAttributes)
1986 if err != nil {
1987 return nil, err
1988 }
1989 if len(rest) != 0 {
1990 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1991 }
1992 return rawAttributes, nil
1993 }
1994
1995 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1996 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1997 var attributes []pkix.AttributeTypeAndValueSET
1998 for _, rawAttr := range rawAttributes {
1999 var attr pkix.AttributeTypeAndValueSET
2000 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2001 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2002 // (i.e.: challengePassword or unstructuredName).
2003 if err == nil && len(rest) == 0 {
2004 attributes = append(attributes, attr)
2005 }
2006 }
2007 return attributes
2008 }
2009
2010 // parseCSRExtensions parses the attributes from a CSR and extracts any
2011 // requested extensions.
2012 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2013 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2014 type pkcs10Attribute struct {
2015 Id asn1.ObjectIdentifier
2016 Values []asn1.RawValue `asn1:"set"`
2017 }
2018
2019 var ret []pkix.Extension
2020 requestedExts := make(map[string]bool)
2021 for _, rawAttr := range rawAttributes {
2022 var attr pkcs10Attribute
2023 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2024 // Ignore attributes that don't parse.
2025 continue
2026 }
2027
2028 if !attr.Id.Equal(oidExtensionRequest) {
2029 continue
2030 }
2031
2032 var extensions []pkix.Extension
2033 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2034 return nil, err
2035 }
2036 for _, ext := range extensions {
2037 oidStr := ext.Id.String()
2038 if requestedExts[oidStr] {
2039 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
2040 }
2041 requestedExts[oidStr] = true
2042 }
2043 ret = append(ret, extensions...)
2044 }
2045
2046 return ret, nil
2047 }
2048
2049 // CreateCertificateRequest creates a new certificate request based on a
2050 // template. The following members of template are used:
2051 //
2052 // - SignatureAlgorithm
2053 // - Subject
2054 // - DNSNames
2055 // - EmailAddresses
2056 // - IPAddresses
2057 // - URIs
2058 // - ExtraExtensions
2059 // - Attributes (deprecated)
2060 //
2061 // priv is the private key to sign the CSR with, and the corresponding public
2062 // key will be included in the CSR. It must implement crypto.Signer or
2063 // crypto.MessageSigner and its Public() method must return a *rsa.PublicKey or
2064 // a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey,
2065 // *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)
2066 //
2067 // The returned slice is the certificate request in DER encoding.
2068 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
2069 key, ok := priv.(crypto.Signer)
2070 if !ok {
2071 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2072 }
2073
2074 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
2075 if err != nil {
2076 return nil, err
2077 }
2078
2079 var publicKeyBytes []byte
2080 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2081 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2082 if err != nil {
2083 return nil, err
2084 }
2085
2086 extensions, err := buildCSRExtensions(template)
2087 if err != nil {
2088 return nil, err
2089 }
2090
2091 // Make a copy of template.Attributes because we may alter it below.
2092 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2093 for _, attr := range template.Attributes {
2094 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2095 copy(values, attr.Value)
2096 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2097 Type: attr.Type,
2098 Value: values,
2099 })
2100 }
2101
2102 extensionsAppended := false
2103 if len(extensions) > 0 {
2104 // Append the extensions to an existing attribute if possible.
2105 for _, atvSet := range attributes {
2106 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2107 continue
2108 }
2109
2110 // specifiedExtensions contains all the extensions that we
2111 // found specified via template.Attributes.
2112 specifiedExtensions := make(map[string]bool)
2113
2114 for _, atvs := range atvSet.Value {
2115 for _, atv := range atvs {
2116 specifiedExtensions[atv.Type.String()] = true
2117 }
2118 }
2119
2120 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2121 newValue = append(newValue, atvSet.Value[0]...)
2122
2123 for _, e := range extensions {
2124 if specifiedExtensions[e.Id.String()] {
2125 // Attributes already contained a value for
2126 // this extension and it takes priority.
2127 continue
2128 }
2129
2130 newValue = append(newValue, pkix.AttributeTypeAndValue{
2131 // There is no place for the critical
2132 // flag in an AttributeTypeAndValue.
2133 Type: e.Id,
2134 Value: e.Value,
2135 })
2136 }
2137
2138 atvSet.Value[0] = newValue
2139 extensionsAppended = true
2140 break
2141 }
2142 }
2143
2144 rawAttributes, err := newRawAttributes(attributes)
2145 if err != nil {
2146 return nil, err
2147 }
2148
2149 // If not included in attributes, add a new attribute for the
2150 // extensions.
2151 if len(extensions) > 0 && !extensionsAppended {
2152 attr := struct {
2153 Type asn1.ObjectIdentifier
2154 Value [][]pkix.Extension `asn1:"set"`
2155 }{
2156 Type: oidExtensionRequest,
2157 Value: [][]pkix.Extension{extensions},
2158 }
2159
2160 b, err := asn1.Marshal(attr)
2161 if err != nil {
2162 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2163 }
2164
2165 var rawValue asn1.RawValue
2166 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2167 return nil, err
2168 }
2169
2170 rawAttributes = append(rawAttributes, rawValue)
2171 }
2172
2173 asn1Subject := template.RawSubject
2174 if len(asn1Subject) == 0 {
2175 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2176 if err != nil {
2177 return nil, err
2178 }
2179 }
2180
2181 tbsCSR := tbsCertificateRequest{
2182 Version: 0, // PKCS #10, RFC 2986
2183 Subject: asn1.RawValue{FullBytes: asn1Subject},
2184 PublicKey: publicKeyInfo{
2185 Algorithm: publicKeyAlgorithm,
2186 PublicKey: asn1.BitString{
2187 Bytes: publicKeyBytes,
2188 BitLength: len(publicKeyBytes) * 8,
2189 },
2190 },
2191 RawAttributes: rawAttributes,
2192 }
2193
2194 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2195 if err != nil {
2196 return nil, err
2197 }
2198 tbsCSR.Raw = tbsCSRContents
2199
2200 signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
2201 if err != nil {
2202 return nil, err
2203 }
2204
2205 return asn1.Marshal(certificateRequest{
2206 TBSCSR: tbsCSR,
2207 SignatureAlgorithm: algorithmIdentifier,
2208 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2209 })
2210 }
2211
2212 // ParseCertificateRequest parses a single certificate request from the
2213 // given ASN.1 DER data.
2214 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2215 var csr certificateRequest
2216
2217 rest, err := asn1.Unmarshal(asn1Data, &csr)
2218 if err != nil {
2219 return nil, err
2220 } else if len(rest) != 0 {
2221 return nil, asn1.SyntaxError{Msg: "trailing data"}
2222 }
2223
2224 return parseCertificateRequest(&csr)
2225 }
2226
2227 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2228 out := &CertificateRequest{
2229 Raw: in.Raw,
2230 RawTBSCertificateRequest: in.TBSCSR.Raw,
2231 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2232 RawSubject: in.TBSCSR.Subject.FullBytes,
2233
2234 Signature: in.SignatureValue.RightAlign(),
2235 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2236
2237 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2238
2239 Version: in.TBSCSR.Version,
2240 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2241 }
2242
2243 var err error
2244 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2245 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2246 if err != nil {
2247 return nil, err
2248 }
2249 }
2250
2251 var subject pkix.RDNSequence
2252 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2253 return nil, err
2254 } else if len(rest) != 0 {
2255 return nil, errors.New("x509: trailing data after X.509 Subject")
2256 }
2257
2258 out.Subject.FillFromRDNSequence(&subject)
2259
2260 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2261 return nil, err
2262 }
2263
2264 for _, extension := range out.Extensions {
2265 switch {
2266 case extension.Id.Equal(oidExtensionSubjectAltName):
2267 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2268 if err != nil {
2269 return nil, err
2270 }
2271 }
2272 }
2273
2274 return out, nil
2275 }
2276
2277 // CheckSignature reports whether the signature on c is valid.
2278 func (c *CertificateRequest) CheckSignature() error {
2279 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2280 }
2281
2282 // RevocationListEntry represents an entry in the revokedCertificates
2283 // sequence of a CRL.
2284 type RevocationListEntry struct {
2285 // Raw contains the raw bytes of the revokedCertificates entry. It is set when
2286 // parsing a CRL; it is ignored when generating a CRL.
2287 Raw []byte
2288
2289 // SerialNumber represents the serial number of a revoked certificate. It is
2290 // both used when creating a CRL and populated when parsing a CRL. It must not
2291 // be nil.
2292 SerialNumber *big.Int
2293 // RevocationTime represents the time at which the certificate was revoked. It
2294 // is both used when creating a CRL and populated when parsing a CRL. It must
2295 // not be the zero time.
2296 RevocationTime time.Time
2297 // ReasonCode represents the reason for revocation, using the integer enum
2298 // values specified in RFC 5280 Section 5.3.1. When creating a CRL, the zero
2299 // value will result in the reasonCode extension being omitted. When parsing a
2300 // CRL, the zero value may represent either the reasonCode extension being
2301 // absent (which implies the default revocation reason of 0/Unspecified), or
2302 // it may represent the reasonCode extension being present and explicitly
2303 // containing a value of 0/Unspecified (which should not happen according to
2304 // the DER encoding rules, but can and does happen anyway).
2305 ReasonCode int
2306
2307 // Extensions contains raw X.509 extensions. When parsing CRL entries,
2308 // this can be used to extract non-critical extensions that are not
2309 // parsed by this package. When marshaling CRL entries, the Extensions
2310 // field is ignored, see ExtraExtensions.
2311 Extensions []pkix.Extension
2312 // ExtraExtensions contains extensions to be copied, raw, into any
2313 // marshaled CRL entries. Values override any extensions that would
2314 // otherwise be produced based on the other fields. The ExtraExtensions
2315 // field is not populated when parsing CRL entries, see Extensions.
2316 ExtraExtensions []pkix.Extension
2317 }
2318
2319 // RevocationList represents a [Certificate] Revocation List (CRL) as specified
2320 // by RFC 5280.
2321 type RevocationList struct {
2322 // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
2323 // signatureAlgorithm, and signatureValue.)
2324 Raw []byte
2325 // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
2326 // DER.
2327 RawTBSRevocationList []byte
2328 // RawIssuer contains the DER encoded Issuer.
2329 RawIssuer []byte
2330
2331 // Issuer contains the DN of the issuing certificate.
2332 Issuer pkix.Name
2333 // AuthorityKeyId is used to identify the public key associated with the
2334 // issuing certificate. It is populated from the authorityKeyIdentifier
2335 // extension when parsing a CRL. It is ignored when creating a CRL; the
2336 // extension is populated from the issuing certificate itself.
2337 AuthorityKeyId []byte
2338
2339 Signature []byte
2340 // SignatureAlgorithm is used to determine the signature algorithm to be
2341 // used when signing the CRL. If 0 the default algorithm for the signing
2342 // key will be used.
2343 SignatureAlgorithm SignatureAlgorithm
2344
2345 // RevokedCertificateEntries represents the revokedCertificates sequence in
2346 // the CRL. It is used when creating a CRL and also populated when parsing a
2347 // CRL. When creating a CRL, it may be empty or nil, in which case the
2348 // revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.
2349 RevokedCertificateEntries []RevocationListEntry
2350
2351 // RevokedCertificates is used to populate the revokedCertificates
2352 // sequence in the CRL if RevokedCertificateEntries is empty. It may be empty
2353 // or nil, in which case an empty CRL will be created.
2354 //
2355 // Deprecated: Use RevokedCertificateEntries instead.
2356 RevokedCertificates []pkix.RevokedCertificate
2357
2358 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2359 // which should be a monotonically increasing sequence number for a given
2360 // CRL scope and CRL issuer. It is also populated from the cRLNumber
2361 // extension when parsing a CRL.
2362 Number *big.Int
2363
2364 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2365 // indicates the issuance date of the CRL.
2366 ThisUpdate time.Time
2367 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2368 // indicates the date by which the next CRL will be issued. NextUpdate
2369 // must be greater than ThisUpdate.
2370 NextUpdate time.Time
2371
2372 // Extensions contains raw X.509 extensions. When creating a CRL,
2373 // the Extensions field is ignored, see ExtraExtensions.
2374 Extensions []pkix.Extension
2375
2376 // ExtraExtensions contains any additional extensions to add directly to
2377 // the CRL.
2378 ExtraExtensions []pkix.Extension
2379 }
2380
2381 // These structures reflect the ASN.1 structure of X.509 CRLs better than
2382 // the existing crypto/x509/pkix variants do. These mirror the existing
2383 // certificate structs in this file.
2384 //
2385 // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
2386 // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
2387 type certificateList struct {
2388 TBSCertList tbsCertificateList
2389 SignatureAlgorithm pkix.AlgorithmIdentifier
2390 SignatureValue asn1.BitString
2391 }
2392
2393 type tbsCertificateList struct {
2394 Raw asn1.RawContent
2395 Version int `asn1:"optional,default:0"`
2396 Signature pkix.AlgorithmIdentifier
2397 Issuer asn1.RawValue
2398 ThisUpdate time.Time
2399 NextUpdate time.Time `asn1:"optional"`
2400 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2401 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2402 }
2403
2404 // CreateRevocationList creates a new X.509 v2 [Certificate] Revocation List,
2405 // according to RFC 5280, based on template.
2406 //
2407 // The CRL is signed by priv which should be a crypto.Signer or
2408 // crypto.MessageSigner associated with the public key in the issuer
2409 // certificate.
2410 //
2411 // The issuer may not be nil, and the crlSign bit must be set in [KeyUsage] in
2412 // order to use it as a CRL issuer.
2413 //
2414 // The issuer distinguished name CRL field and authority key identifier
2415 // extension are populated using the issuer certificate. issuer must have
2416 // SubjectKeyId set.
2417 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2418 if template == nil {
2419 return nil, errors.New("x509: template can not be nil")
2420 }
2421 if issuer == nil {
2422 return nil, errors.New("x509: issuer can not be nil")
2423 }
2424 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2425 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2426 }
2427 if len(issuer.SubjectKeyId) == 0 {
2428 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2429 }
2430 if template.NextUpdate.Before(template.ThisUpdate) {
2431 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2432 }
2433 if template.Number == nil {
2434 return nil, errors.New("x509: template contains nil Number field")
2435 }
2436
2437 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
2438 if err != nil {
2439 return nil, err
2440 }
2441
2442 var revokedCerts []pkix.RevokedCertificate
2443 // Only process the deprecated RevokedCertificates field if it is populated
2444 // and the new RevokedCertificateEntries field is not populated.
2445 if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
2446 // Force revocation times to UTC per RFC 5280.
2447 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2448 for i, rc := range template.RevokedCertificates {
2449 rc.RevocationTime = rc.RevocationTime.UTC()
2450 revokedCerts[i] = rc
2451 }
2452 } else {
2453 // Convert the ReasonCode field to a proper extension, and force revocation
2454 // times to UTC per RFC 5280.
2455 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
2456 for i, rce := range template.RevokedCertificateEntries {
2457 if rce.SerialNumber == nil {
2458 return nil, errors.New("x509: template contains entry with nil SerialNumber field")
2459 }
2460 if rce.RevocationTime.IsZero() {
2461 return nil, errors.New("x509: template contains entry with zero RevocationTime field")
2462 }
2463
2464 rc := pkix.RevokedCertificate{
2465 SerialNumber: rce.SerialNumber,
2466 RevocationTime: rce.RevocationTime.UTC(),
2467 }
2468
2469 // Copy over any extra extensions, except for a Reason Code extension,
2470 // because we'll synthesize that ourselves to ensure it is correct.
2471 exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
2472 for _, ext := range rce.ExtraExtensions {
2473 if ext.Id.Equal(oidExtensionReasonCode) {
2474 return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
2475 }
2476 exts = append(exts, ext)
2477 }
2478
2479 // Only add a reasonCode extension if the reason is non-zero, as per
2480 // RFC 5280 Section 5.3.1.
2481 if rce.ReasonCode != 0 {
2482 reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
2483 if err != nil {
2484 return nil, err
2485 }
2486
2487 exts = append(exts, pkix.Extension{
2488 Id: oidExtensionReasonCode,
2489 Value: reasonBytes,
2490 })
2491 }
2492
2493 if len(exts) > 0 {
2494 rc.Extensions = exts
2495 }
2496 revokedCerts[i] = rc
2497 }
2498 }
2499
2500 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2501 if err != nil {
2502 return nil, err
2503 }
2504
2505 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2506 return nil, errors.New("x509: CRL number exceeds 20 octets")
2507 }
2508 crlNum, err := asn1.Marshal(template.Number)
2509 if err != nil {
2510 return nil, err
2511 }
2512
2513 // Correctly use the issuer's subject sequence if one is specified.
2514 issuerSubject, err := subjectBytes(issuer)
2515 if err != nil {
2516 return nil, err
2517 }
2518
2519 tbsCertList := tbsCertificateList{
2520 Version: 1, // v2
2521 Signature: algorithmIdentifier,
2522 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2523 ThisUpdate: template.ThisUpdate.UTC(),
2524 NextUpdate: template.NextUpdate.UTC(),
2525 Extensions: []pkix.Extension{
2526 {
2527 Id: oidExtensionAuthorityKeyId,
2528 Value: aki,
2529 },
2530 {
2531 Id: oidExtensionCRLNumber,
2532 Value: crlNum,
2533 },
2534 },
2535 }
2536 if len(revokedCerts) > 0 {
2537 tbsCertList.RevokedCertificates = revokedCerts
2538 }
2539
2540 if len(template.ExtraExtensions) > 0 {
2541 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2542 }
2543
2544 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2545 if err != nil {
2546 return nil, err
2547 }
2548
2549 // Optimization to only marshal this struct once, when signing and
2550 // then embedding in certificateList below.
2551 tbsCertList.Raw = tbsCertListContents
2552
2553 signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
2554 if err != nil {
2555 return nil, err
2556 }
2557
2558 return asn1.Marshal(certificateList{
2559 TBSCertList: tbsCertList,
2560 SignatureAlgorithm: algorithmIdentifier,
2561 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2562 })
2563 }
2564
2565 // CheckSignatureFrom verifies that the signature on rl is a valid signature
2566 // from issuer.
2567 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2568 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2569 parent.BasicConstraintsValid && !parent.IsCA {
2570 return ConstraintViolationError{}
2571 }
2572
2573 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2574 return ConstraintViolationError{}
2575 }
2576
2577 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2578 return ErrUnsupportedAlgorithm
2579 }
2580
2581 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)
2582 }