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