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.
5 // Package x509 parses X.509-encoded keys and certificates.
7 // On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR
8 // can be used to override the system default locations for the SSL certificate
9 // file and SSL certificate files directory, respectively.
37 "golang.org/x/crypto/cryptobyte"
38 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
41 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
43 type pkixPublicKey struct {
44 Algo pkix.AlgorithmIdentifier
45 BitString asn1.BitString
48 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
50 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
51 // ed25519.PublicKey. More types might be supported in the future.
53 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
54 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
56 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
57 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
58 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
61 } else if len(rest) != 0 {
62 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
64 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
65 if algo == UnknownPublicKeyAlgorithm {
66 return nil, errors.New("x509: unknown public key algorithm")
68 return parsePublicKey(algo, &pki)
71 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
72 switch pub := pub.(type) {
74 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
79 return nil, pkix.AlgorithmIdentifier{}, err
81 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
82 // This is a NULL parameters value which is required by
83 // RFC 3279, Section 2.3.1.
84 publicKeyAlgorithm.Parameters = asn1.NullRawValue
85 case *ecdsa.PublicKey:
86 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
87 oid, ok := oidFromNamedCurve(pub.Curve)
89 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
91 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
93 paramBytes, err = asn1.Marshal(oid)
97 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
98 case ed25519.PublicKey:
100 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
102 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
105 return publicKeyBytes, publicKeyAlgorithm, nil
108 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
110 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
111 // and ed25519.PublicKey. Unsupported key types result in an error.
113 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
114 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
115 var publicKeyBytes []byte
116 var publicKeyAlgorithm pkix.AlgorithmIdentifier
119 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
123 pkix := pkixPublicKey{
124 Algo: publicKeyAlgorithm,
125 BitString: asn1.BitString{
126 Bytes: publicKeyBytes,
127 BitLength: 8 * len(publicKeyBytes),
131 ret, _ := asn1.Marshal(pkix)
135 // These structures reflect the ASN.1 structure of X.509 certificates.:
137 type certificate struct {
139 TBSCertificate tbsCertificate
140 SignatureAlgorithm pkix.AlgorithmIdentifier
141 SignatureValue asn1.BitString
144 type tbsCertificate struct {
146 Version int `asn1:"optional,explicit,default:0,tag:0"`
147 SerialNumber *big.Int
148 SignatureAlgorithm pkix.AlgorithmIdentifier
151 Subject asn1.RawValue
152 PublicKey publicKeyInfo
153 UniqueId asn1.BitString `asn1:"optional,tag:1"`
154 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
155 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
158 type dsaAlgorithmParameters struct {
162 type dsaSignature struct {
166 type ecdsaSignature dsaSignature
168 type validity struct {
169 NotBefore, NotAfter time.Time
172 type publicKeyInfo struct {
174 Algorithm pkix.AlgorithmIdentifier
175 PublicKey asn1.BitString
179 type authKeyId struct {
180 Id []byte `asn1:"optional,tag:0"`
183 type SignatureAlgorithm int
186 UnknownSignatureAlgorithm SignatureAlgorithm = iota
205 func (algo SignatureAlgorithm) isRSAPSS() bool {
207 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
214 func (algo SignatureAlgorithm) String() string {
215 for _, details := range signatureAlgorithmDetails {
216 if details.algo == algo {
220 return strconv.Itoa(int(algo))
223 type PublicKeyAlgorithm int
226 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
233 var publicKeyAlgoName = [...]string{
240 func (algo PublicKeyAlgorithm) String() string {
241 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
242 return publicKeyAlgoName[algo]
244 return strconv.Itoa(int(algo))
247 // OIDs for signature algorithms
249 // pkcs-1 OBJECT IDENTIFIER ::= {
250 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
253 // RFC 3279 2.2.1 RSA Signature Algorithms
255 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
257 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
259 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
261 // dsaWithSha1 OBJECT IDENTIFIER ::= {
262 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
264 // RFC 3279 2.2.3 ECDSA Signature Algorithm
266 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
267 // iso(1) member-body(2) us(840) ansi-x962(10045)
268 // signatures(4) ecdsa-with-SHA1(1)}
271 // RFC 4055 5 PKCS #1 Version 1.5
273 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
275 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
277 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
280 // RFC 5758 3.1 DSA Signature Algorithms
282 // dsaWithSha256 OBJECT IDENTIFIER ::= {
283 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
284 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
286 // RFC 5758 3.2 ECDSA Signature Algorithm
288 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
289 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
291 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
294 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
295 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
298 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
300 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
303 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
304 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
305 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
306 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
307 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
308 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
309 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
310 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
311 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
312 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
313 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
314 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
315 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
316 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
318 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
319 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
320 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
322 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
324 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
325 // but it's specified by ISO. Microsoft's makecert.exe has been known
326 // to produce certificates with this OID.
327 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
330 var signatureAlgorithmDetails = []struct {
331 algo SignatureAlgorithm
333 oid asn1.ObjectIdentifier
334 pubKeyAlgo PublicKeyAlgorithm
337 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
338 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
339 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
340 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
341 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
342 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
343 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
344 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
345 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
346 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
347 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
348 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
349 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
350 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
351 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
352 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
353 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
356 // pssParameters reflects the parameters in an AlgorithmIdentifier that
357 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
358 type pssParameters struct {
359 // The following three fields are not marked as
360 // optional because the default values specify SHA-1,
361 // which is no longer suitable for use in signatures.
362 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
363 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
364 SaltLength int `asn1:"explicit,tag:2"`
365 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
368 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
369 // in an AlgorithmIdentifier that specifies RSA PSS.
370 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
371 var hashOID asn1.ObjectIdentifier
382 params := pssParameters{
383 Hash: pkix.AlgorithmIdentifier{
385 Parameters: asn1.NullRawValue,
387 MGF: pkix.AlgorithmIdentifier{
390 SaltLength: hashFunc.Size(),
394 mgf1Params := pkix.AlgorithmIdentifier{
396 Parameters: asn1.NullRawValue,
400 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
405 serialized, err := asn1.Marshal(params)
410 return asn1.RawValue{FullBytes: serialized}
413 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
414 if ai.Algorithm.Equal(oidSignatureEd25519) {
415 // RFC 8410, Section 3
416 // > For all of the OIDs, the parameters MUST be absent.
417 if len(ai.Parameters.FullBytes) != 0 {
418 return UnknownSignatureAlgorithm
422 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
423 for _, details := range signatureAlgorithmDetails {
424 if ai.Algorithm.Equal(details.oid) {
428 return UnknownSignatureAlgorithm
431 // RSA PSS is special because it encodes important parameters
432 // in the Parameters.
434 var params pssParameters
435 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
436 return UnknownSignatureAlgorithm
439 var mgf1HashFunc pkix.AlgorithmIdentifier
440 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
441 return UnknownSignatureAlgorithm
444 // PSS is greatly overburdened with options. This code forces them into
445 // three buckets by requiring that the MGF1 hash function always match the
446 // message hash function (as recommended in RFC 3447, Section 8.1), that the
447 // salt length matches the hash length, and that the trailer field has the
449 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
450 !params.MGF.Algorithm.Equal(oidMGF1) ||
451 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
452 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
453 params.TrailerField != 1 {
454 return UnknownSignatureAlgorithm
458 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
459 return SHA256WithRSAPSS
460 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
461 return SHA384WithRSAPSS
462 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
463 return SHA512WithRSAPSS
466 return UnknownSignatureAlgorithm
469 // RFC 3279, 2.3 Public Key Algorithms
471 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
472 // rsadsi(113549) pkcs(1) 1 }
474 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
476 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
477 // x9-57(10040) x9cm(4) 1 }
479 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
481 // id-ecPublicKey OBJECT IDENTIFIER ::= {
482 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
484 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
485 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
486 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
487 oidPublicKeyEd25519 = oidSignatureEd25519
490 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
492 case oid.Equal(oidPublicKeyRSA):
494 case oid.Equal(oidPublicKeyDSA):
496 case oid.Equal(oidPublicKeyECDSA):
498 case oid.Equal(oidPublicKeyEd25519):
501 return UnknownPublicKeyAlgorithm
504 // RFC 5480, 2.1.1.1. Named Curve
506 // secp224r1 OBJECT IDENTIFIER ::= {
507 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
509 // secp256r1 OBJECT IDENTIFIER ::= {
510 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
513 // secp384r1 OBJECT IDENTIFIER ::= {
514 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
516 // secp521r1 OBJECT IDENTIFIER ::= {
517 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
519 // NB: secp256r1 is equivalent to prime256v1
521 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
522 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
523 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
524 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
527 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
529 case oid.Equal(oidNamedCurveP224):
530 return elliptic.P224()
531 case oid.Equal(oidNamedCurveP256):
532 return elliptic.P256()
533 case oid.Equal(oidNamedCurveP384):
534 return elliptic.P384()
535 case oid.Equal(oidNamedCurveP521):
536 return elliptic.P521()
541 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
543 case elliptic.P224():
544 return oidNamedCurveP224, true
545 case elliptic.P256():
546 return oidNamedCurveP256, true
547 case elliptic.P384():
548 return oidNamedCurveP384, true
549 case elliptic.P521():
550 return oidNamedCurveP521, true
556 // KeyUsage represents the set of actions that are valid for a given key. It's
557 // a bitmap of the KeyUsage* constants.
561 KeyUsageDigitalSignature KeyUsage = 1 << iota
562 KeyUsageContentCommitment
563 KeyUsageKeyEncipherment
564 KeyUsageDataEncipherment
572 // RFC 5280, 4.2.1.12 Extended Key Usage
574 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
576 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
578 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
579 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
580 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
581 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
582 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
583 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
585 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
586 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
587 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
588 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
589 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
590 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
591 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
592 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
593 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
594 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
595 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
596 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
597 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
598 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
601 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
602 // Each of the ExtKeyUsage* constants define a unique action.
606 ExtKeyUsageAny ExtKeyUsage = iota
607 ExtKeyUsageServerAuth
608 ExtKeyUsageClientAuth
609 ExtKeyUsageCodeSigning
610 ExtKeyUsageEmailProtection
611 ExtKeyUsageIPSECEndSystem
612 ExtKeyUsageIPSECTunnel
614 ExtKeyUsageTimeStamping
615 ExtKeyUsageOCSPSigning
616 ExtKeyUsageMicrosoftServerGatedCrypto
617 ExtKeyUsageNetscapeServerGatedCrypto
618 ExtKeyUsageMicrosoftCommercialCodeSigning
619 ExtKeyUsageMicrosoftKernelCodeSigning
622 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
623 var extKeyUsageOIDs = []struct {
624 extKeyUsage ExtKeyUsage
625 oid asn1.ObjectIdentifier
627 {ExtKeyUsageAny, oidExtKeyUsageAny},
628 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
629 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
630 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
631 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
632 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
633 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
634 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
635 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
636 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
637 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
638 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
639 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
640 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
643 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
644 for _, pair := range extKeyUsageOIDs {
645 if oid.Equal(pair.oid) {
646 return pair.extKeyUsage, true
652 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
653 for _, pair := range extKeyUsageOIDs {
654 if eku == pair.extKeyUsage {
655 return pair.oid, true
661 // A Certificate represents an X.509 certificate.
662 type Certificate struct {
663 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
664 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
665 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
666 RawSubject []byte // DER encoded Subject
667 RawIssuer []byte // DER encoded Issuer
670 SignatureAlgorithm SignatureAlgorithm
672 PublicKeyAlgorithm PublicKeyAlgorithm
673 PublicKey interface{}
676 SerialNumber *big.Int
679 NotBefore, NotAfter time.Time // Validity bounds.
682 // Extensions contains raw X.509 extensions. When parsing certificates,
683 // this can be used to extract non-critical extensions that are not
684 // parsed by this package. When marshaling certificates, the Extensions
685 // field is ignored, see ExtraExtensions.
686 Extensions []pkix.Extension
688 // ExtraExtensions contains extensions to be copied, raw, into any
689 // marshaled certificates. Values override any extensions that would
690 // otherwise be produced based on the other fields. The ExtraExtensions
691 // field is not populated when parsing certificates, see Extensions.
692 ExtraExtensions []pkix.Extension
694 // UnhandledCriticalExtensions contains a list of extension IDs that
695 // were not (fully) processed when parsing. Verify will fail if this
696 // slice is non-empty, unless verification is delegated to an OS
697 // library which understands all the critical extensions.
699 // Users can access these extensions using Extensions and can remove
700 // elements from this slice if they believe that they have been
702 UnhandledCriticalExtensions []asn1.ObjectIdentifier
704 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
705 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
707 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
708 // and MaxPathLenZero are valid.
709 BasicConstraintsValid bool
712 // MaxPathLen and MaxPathLenZero indicate the presence and
713 // value of the BasicConstraints' "pathLenConstraint".
715 // When parsing a certificate, a positive non-zero MaxPathLen
716 // means that the field was specified, -1 means it was unset,
717 // and MaxPathLenZero being true mean that the field was
718 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
719 // should be treated equivalent to -1 (unset).
721 // When generating a certificate, an unset pathLenConstraint
722 // can be requested with either MaxPathLen == -1 or using the
723 // zero value for both MaxPathLen and MaxPathLenZero.
725 // MaxPathLenZero indicates that BasicConstraintsValid==true
726 // and MaxPathLen==0 should be interpreted as an actual
727 // maximum path length of zero. Otherwise, that combination is
728 // interpreted as MaxPathLen not being set.
732 AuthorityKeyId []byte
734 // RFC 5280, 4.2.2.1 (Authority Information Access)
736 IssuingCertificateURL []string
738 // Subject Alternate Name values. (Note that these values may not be valid
739 // if invalid values were contained within a parsed certificate. For
740 // example, an element of DNSNames may not be a valid DNS domain name.)
742 EmailAddresses []string
747 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
748 PermittedDNSDomains []string
749 ExcludedDNSDomains []string
750 PermittedIPRanges []*net.IPNet
751 ExcludedIPRanges []*net.IPNet
752 PermittedEmailAddresses []string
753 ExcludedEmailAddresses []string
754 PermittedURIDomains []string
755 ExcludedURIDomains []string
757 // CRL Distribution Points
758 CRLDistributionPoints []string
760 PolicyIdentifiers []asn1.ObjectIdentifier
763 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
764 // involves algorithms that are not currently implemented.
765 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
767 // An InsecureAlgorithmError
768 type InsecureAlgorithmError SignatureAlgorithm
770 func (e InsecureAlgorithmError) Error() string {
771 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
774 // ConstraintViolationError results when a requested usage is not permitted by
775 // a certificate. For example: checking a signature when the public key isn't a
776 // certificate signing key.
777 type ConstraintViolationError struct{}
779 func (ConstraintViolationError) Error() string {
780 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
783 func (c *Certificate) Equal(other *Certificate) bool {
784 if c == nil || other == nil {
787 return bytes.Equal(c.Raw, other.Raw)
790 func (c *Certificate) hasSANExtension() bool {
791 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
794 // CheckSignatureFrom verifies that the signature on c is a valid signature
796 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
797 // RFC 5280, 4.2.1.9:
798 // "If the basic constraints extension is not present in a version 3
799 // certificate, or the extension is present but the cA boolean is not
800 // asserted, then the certified public key MUST NOT be used to verify
801 // certificate signatures."
802 if parent.Version == 3 && !parent.BasicConstraintsValid ||
803 parent.BasicConstraintsValid && !parent.IsCA {
804 return ConstraintViolationError{}
807 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
808 return ConstraintViolationError{}
811 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
812 return ErrUnsupportedAlgorithm
815 // TODO(agl): don't ignore the path length constraint.
817 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
820 // CheckSignature verifies that signature is a valid signature over signed from
822 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
823 return checkSignature(algo, signed, signature, c.PublicKey)
826 func (c *Certificate) hasNameConstraints() bool {
827 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
830 func (c *Certificate) getSANExtension() []byte {
831 for _, e := range c.Extensions {
832 if e.Id.Equal(oidExtensionSubjectAltName) {
839 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
840 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
843 // CheckSignature verifies that signature is a valid signature over signed from
844 // a crypto.PublicKey.
845 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
846 var hashType crypto.Hash
847 var pubKeyAlgo PublicKeyAlgorithm
849 for _, details := range signatureAlgorithmDetails {
850 if details.algo == algo {
851 hashType = details.hash
852 pubKeyAlgo = details.pubKeyAlgo
858 if pubKeyAlgo != Ed25519 {
859 return ErrUnsupportedAlgorithm
862 return InsecureAlgorithmError(algo)
864 if !hashType.Available() {
865 return ErrUnsupportedAlgorithm
872 switch pub := publicKey.(type) {
874 if pubKeyAlgo != RSA {
875 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
878 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
880 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
883 if pubKeyAlgo != DSA {
884 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
886 dsaSig := new(dsaSignature)
887 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
889 } else if len(rest) != 0 {
890 return errors.New("x509: trailing data after DSA signature")
892 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
893 return errors.New("x509: DSA signature contained zero or negative values")
895 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
896 // than the key length, but crypto/dsa doesn't do it automatically.
897 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
898 signed = signed[:maxHashLen]
900 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
901 return errors.New("x509: DSA verification failure")
904 case *ecdsa.PublicKey:
905 if pubKeyAlgo != ECDSA {
906 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
908 ecdsaSig := new(ecdsaSignature)
909 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
911 } else if len(rest) != 0 {
912 return errors.New("x509: trailing data after ECDSA signature")
914 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
915 return errors.New("x509: ECDSA signature contained zero or negative values")
917 if !ecdsa.Verify(pub, signed, ecdsaSig.R, ecdsaSig.S) {
918 return errors.New("x509: ECDSA verification failure")
921 case ed25519.PublicKey:
922 if pubKeyAlgo != Ed25519 {
923 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
925 if !ed25519.Verify(pub, signed, signature) {
926 return errors.New("x509: Ed25519 verification failure")
930 return ErrUnsupportedAlgorithm
933 // CheckCRLSignature checks that the signature in crl is from c.
934 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
935 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
936 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
939 type UnhandledCriticalExtension struct{}
941 func (h UnhandledCriticalExtension) Error() string {
942 return "x509: unhandled critical extension"
945 type basicConstraints struct {
946 IsCA bool `asn1:"optional"`
947 MaxPathLen int `asn1:"optional,default:-1"`
951 type policyInformation struct {
952 Policy asn1.ObjectIdentifier
953 // policyQualifiers omitted
964 type authorityInfoAccess struct {
965 Method asn1.ObjectIdentifier
966 Location asn1.RawValue
969 // RFC 5280, 4.2.1.14
970 type distributionPoint struct {
971 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
972 Reason asn1.BitString `asn1:"optional,tag:1"`
973 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
976 type distributionPointName struct {
977 FullName []asn1.RawValue `asn1:"optional,tag:0"`
978 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
981 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
982 asn1Data := keyData.PublicKey.RightAlign()
985 // RSA public keys must have a NULL in the parameters.
986 // See RFC 3279, Section 2.3.1.
987 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
988 return nil, errors.New("x509: RSA key missing NULL parameters")
991 p := new(pkcs1PublicKey)
992 rest, err := asn1.Unmarshal(asn1Data, p)
997 return nil, errors.New("x509: trailing data after RSA public key")
1000 if p.N.Sign() <= 0 {
1001 return nil, errors.New("x509: RSA modulus is not a positive number")
1004 return nil, errors.New("x509: RSA public exponent is not a positive number")
1007 pub := &rsa.PublicKey{
1014 rest, err := asn1.Unmarshal(asn1Data, &p)
1019 return nil, errors.New("x509: trailing data after DSA public key")
1021 paramsData := keyData.Algorithm.Parameters.FullBytes
1022 params := new(dsaAlgorithmParameters)
1023 rest, err = asn1.Unmarshal(paramsData, params)
1028 return nil, errors.New("x509: trailing data after DSA parameters")
1030 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1031 return nil, errors.New("x509: zero or negative DSA parameter")
1033 pub := &dsa.PublicKey{
1034 Parameters: dsa.Parameters{
1043 paramsData := keyData.Algorithm.Parameters.FullBytes
1044 namedCurveOID := new(asn1.ObjectIdentifier)
1045 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1047 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1050 return nil, errors.New("x509: trailing data after ECDSA parameters")
1052 namedCurve := namedCurveFromOID(*namedCurveOID)
1053 if namedCurve == nil {
1054 return nil, errors.New("x509: unsupported elliptic curve")
1056 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1058 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1060 pub := &ecdsa.PublicKey{
1067 // RFC 8410, Section 3
1068 // > For all of the OIDs, the parameters MUST be absent.
1069 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1070 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1072 if len(asn1Data) != ed25519.PublicKeySize {
1073 return nil, errors.New("x509: wrong Ed25519 public key size")
1075 pub := make([]byte, ed25519.PublicKeySize)
1077 return ed25519.PublicKey(pub), nil
1083 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1084 // RFC 5280, 4.2.1.6
1086 // SubjectAltName ::= GeneralNames
1088 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1090 // GeneralName ::= CHOICE {
1091 // otherName [0] OtherName,
1092 // rfc822Name [1] IA5String,
1093 // dNSName [2] IA5String,
1094 // x400Address [3] ORAddress,
1095 // directoryName [4] Name,
1096 // ediPartyName [5] EDIPartyName,
1097 // uniformResourceIdentifier [6] IA5String,
1098 // iPAddress [7] OCTET STRING,
1099 // registeredID [8] OBJECT IDENTIFIER }
1100 var seq asn1.RawValue
1101 rest, err := asn1.Unmarshal(extension, &seq)
1104 } else if len(rest) != 0 {
1105 return errors.New("x509: trailing data after X.509 extension")
1107 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1108 return asn1.StructuralError{Msg: "bad SAN sequence"}
1114 rest, err = asn1.Unmarshal(rest, &v)
1119 if err := callback(v.Tag, v.Bytes); err != nil {
1127 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1128 err = forEachSAN(value, func(tag int, data []byte) error {
1131 emailAddresses = append(emailAddresses, string(data))
1133 dnsNames = append(dnsNames, string(data))
1135 uri, err := url.Parse(string(data))
1137 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1139 if len(uri.Host) > 0 {
1140 if _, ok := domainToReverseLabels(uri.Host); !ok {
1141 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1144 uris = append(uris, uri)
1147 case net.IPv4len, net.IPv6len:
1148 ipAddresses = append(ipAddresses, data)
1150 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1160 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1161 func isValidIPMask(mask []byte) bool {
1164 for _, b := range mask {
1174 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1185 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1186 // RFC 5280, 4.2.1.10
1188 // NameConstraints ::= SEQUENCE {
1189 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1190 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1192 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1194 // GeneralSubtree ::= SEQUENCE {
1195 // base GeneralName,
1196 // minimum [0] BaseDistance DEFAULT 0,
1197 // maximum [1] BaseDistance OPTIONAL }
1199 // BaseDistance ::= INTEGER (0..MAX)
1201 outer := cryptobyte.String(e.Value)
1202 var toplevel, permitted, excluded cryptobyte.String
1203 var havePermitted, haveExcluded bool
1204 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1206 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1207 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1209 return false, errors.New("x509: invalid NameConstraints extension")
1212 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1213 // From RFC 5280, Section 4.2.1.10:
1214 // “either the permittedSubtrees field
1215 // or the excludedSubtrees MUST be
1217 return false, errors.New("x509: empty name constraints extension")
1220 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1221 for !subtrees.Empty() {
1222 var seq, value cryptobyte.String
1223 var tag cryptobyte_asn1.Tag
1224 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1225 !seq.ReadAnyASN1(&value, &tag) {
1226 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1230 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1231 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1232 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1233 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1238 domain := string(value)
1239 if err := isIA5String(domain); err != nil {
1240 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1243 trimmedDomain := domain
1244 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1245 // constraints can have a leading
1246 // period to exclude the domain
1247 // itself, but that's not valid in a
1248 // normal domain name.
1249 trimmedDomain = trimmedDomain[1:]
1251 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1252 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1254 dnsNames = append(dnsNames, domain)
1270 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1273 if !isValidIPMask(mask) {
1274 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1277 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1280 constraint := string(value)
1281 if err := isIA5String(constraint); err != nil {
1282 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1285 // If the constraint contains an @ then
1286 // it specifies an exact mailbox name.
1287 if strings.Contains(constraint, "@") {
1288 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1289 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1292 // Otherwise it's a domain name.
1293 domain := constraint
1294 if len(domain) > 0 && domain[0] == '.' {
1297 if _, ok := domainToReverseLabels(domain); !ok {
1298 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1301 emails = append(emails, constraint)
1304 domain := string(value)
1305 if err := isIA5String(domain); err != nil {
1306 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1309 if net.ParseIP(domain) != nil {
1310 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1313 trimmedDomain := domain
1314 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1315 // constraints can have a leading
1316 // period to exclude the domain itself,
1317 // but that's not valid in a normal
1319 trimmedDomain = trimmedDomain[1:]
1321 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1322 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1324 uriDomains = append(uriDomains, domain)
1331 return dnsNames, ips, emails, uriDomains, nil
1334 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1337 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1340 out.PermittedDNSDomainsCritical = e.Critical
1342 return unhandled, nil
1345 func parseCertificate(in *certificate) (*Certificate, error) {
1346 out := new(Certificate)
1348 out.RawTBSCertificate = in.TBSCertificate.Raw
1349 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1350 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1351 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1353 out.Signature = in.SignatureValue.RightAlign()
1354 out.SignatureAlgorithm =
1355 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1357 out.PublicKeyAlgorithm =
1358 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1360 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1365 out.Version = in.TBSCertificate.Version + 1
1366 out.SerialNumber = in.TBSCertificate.SerialNumber
1368 var issuer, subject pkix.RDNSequence
1369 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1371 } else if len(rest) != 0 {
1372 return nil, errors.New("x509: trailing data after X.509 subject")
1374 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1376 } else if len(rest) != 0 {
1377 return nil, errors.New("x509: trailing data after X.509 issuer")
1380 out.Issuer.FillFromRDNSequence(&issuer)
1381 out.Subject.FillFromRDNSequence(&subject)
1383 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1384 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1386 for _, e := range in.TBSCertificate.Extensions {
1387 out.Extensions = append(out.Extensions, e)
1390 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1393 // RFC 5280, 4.2.1.3
1394 var usageBits asn1.BitString
1395 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1397 } else if len(rest) != 0 {
1398 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1402 for i := 0; i < 9; i++ {
1403 if usageBits.At(i) != 0 {
1404 usage |= 1 << uint(i)
1407 out.KeyUsage = KeyUsage(usage)
1410 // RFC 5280, 4.2.1.9
1411 var constraints basicConstraints
1412 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1414 } else if len(rest) != 0 {
1415 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1418 out.BasicConstraintsValid = true
1419 out.IsCA = constraints.IsCA
1420 out.MaxPathLen = constraints.MaxPathLen
1421 out.MaxPathLenZero = out.MaxPathLen == 0
1422 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1424 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1429 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1430 // If we didn't parse anything then we do the critical check, below.
1435 unhandled, err = parseNameConstraintsExtension(out, e)
1441 // RFC 5280, 4.2.1.13
1443 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1445 // DistributionPoint ::= SEQUENCE {
1446 // distributionPoint [0] DistributionPointName OPTIONAL,
1447 // reasons [1] ReasonFlags OPTIONAL,
1448 // cRLIssuer [2] GeneralNames OPTIONAL }
1450 // DistributionPointName ::= CHOICE {
1451 // fullName [0] GeneralNames,
1452 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1454 var cdp []distributionPoint
1455 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1457 } else if len(rest) != 0 {
1458 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1461 for _, dp := range cdp {
1462 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1463 if len(dp.DistributionPoint.FullName) == 0 {
1467 for _, fullName := range dp.DistributionPoint.FullName {
1468 if fullName.Tag == 6 {
1469 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1475 // RFC 5280, 4.2.1.1
1477 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1479 } else if len(rest) != 0 {
1480 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1482 out.AuthorityKeyId = a.Id
1485 // RFC 5280, 4.2.1.12. Extended Key Usage
1487 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1489 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1491 // KeyPurposeId ::= OBJECT IDENTIFIER
1493 var keyUsage []asn1.ObjectIdentifier
1494 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1496 } else if len(rest) != 0 {
1497 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1500 for _, u := range keyUsage {
1501 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1502 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1504 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1509 // RFC 5280, 4.2.1.2
1511 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1513 } else if len(rest) != 0 {
1514 return nil, errors.New("x509: trailing data after X.509 key-id")
1516 out.SubjectKeyId = keyid
1519 // RFC 5280 4.2.1.4: Certificate Policies
1520 var policies []policyInformation
1521 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1523 } else if len(rest) != 0 {
1524 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1526 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1527 for i, policy := range policies {
1528 out.PolicyIdentifiers[i] = policy.Policy
1532 // Unknown extensions are recorded if critical.
1535 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1536 // RFC 5280 4.2.2.1: Authority Information Access
1537 var aia []authorityInfoAccess
1538 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1540 } else if len(rest) != 0 {
1541 return nil, errors.New("x509: trailing data after X.509 authority information")
1544 for _, v := range aia {
1545 // GeneralName: uniformResourceIdentifier [6] IA5String
1546 if v.Location.Tag != 6 {
1549 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1550 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1551 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1552 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1556 // Unknown extensions are recorded if critical.
1560 if e.Critical && unhandled {
1561 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1568 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1569 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1570 var cert certificate
1571 rest, err := asn1.Unmarshal(asn1Data, &cert)
1576 return nil, asn1.SyntaxError{Msg: "trailing data"}
1579 return parseCertificate(&cert)
1582 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1583 // data. The certificates must be concatenated with no intermediate padding.
1584 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1585 var v []*certificate
1587 for len(asn1Data) > 0 {
1588 cert := new(certificate)
1590 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1597 ret := make([]*Certificate, len(v))
1598 for i, ci := range v {
1599 cert, err := parseCertificate(ci)
1609 func reverseBitsInAByte(in byte) byte {
1611 b2 := b1>>2&0x33 | b1<<2&0xcc
1612 b3 := b2>>1&0x55 | b2<<1&0xaa
1616 // asn1BitLength returns the bit-length of bitString by considering the
1617 // most-significant bit in a byte to be the "first" bit. This convention
1618 // matches ASN.1, but differs from almost everything else.
1619 func asn1BitLength(bitString []byte) int {
1620 bitLen := len(bitString) * 8
1622 for i := range bitString {
1623 b := bitString[len(bitString)-i-1]
1625 for bit := uint(0); bit < 8; bit++ {
1626 if (b>>bit)&1 == 1 {
1637 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1638 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1639 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1640 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1641 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1642 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1643 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1644 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1645 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1646 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1650 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1651 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1654 // oidNotInExtensions reports whether an extension with the given oid exists in
1656 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1657 for _, e := range extensions {
1658 if e.Id.Equal(oid) {
1665 // marshalSANs marshals a list of addresses into a the contents of an X.509
1666 // SubjectAlternativeName extension.
1667 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1668 var rawValues []asn1.RawValue
1669 for _, name := range dnsNames {
1670 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1672 for _, email := range emailAddresses {
1673 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1675 for _, rawIP := range ipAddresses {
1676 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1681 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1683 for _, uri := range uris {
1684 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
1686 return asn1.Marshal(rawValues)
1689 func isIA5String(s string) error {
1690 for _, r := range s {
1691 if r >= utf8.RuneSelf {
1692 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1699 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte) (ret []pkix.Extension, err error) {
1700 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1703 if template.KeyUsage != 0 &&
1704 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1705 ret[n].Id = oidExtensionKeyUsage
1706 ret[n].Critical = true
1709 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1710 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1718 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1725 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1726 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1727 ret[n].Id = oidExtensionExtendedKeyUsage
1729 var oids []asn1.ObjectIdentifier
1730 for _, u := range template.ExtKeyUsage {
1731 if oid, ok := oidFromExtKeyUsage(u); ok {
1732 oids = append(oids, oid)
1734 panic("internal error")
1738 oids = append(oids, template.UnknownExtKeyUsage...)
1740 ret[n].Value, err = asn1.Marshal(oids)
1747 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1748 // Leaving MaxPathLen as zero indicates that no maximum path
1749 // length is desired, unless MaxPathLenZero is set. A value of
1750 // -1 causes encoding/asn1 to omit the value as desired.
1751 maxPathLen := template.MaxPathLen
1752 if maxPathLen == 0 && !template.MaxPathLenZero {
1755 ret[n].Id = oidExtensionBasicConstraints
1756 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1757 ret[n].Critical = true
1764 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1765 ret[n].Id = oidExtensionSubjectKeyId
1766 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1773 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1774 ret[n].Id = oidExtensionAuthorityKeyId
1775 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1782 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1783 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1784 ret[n].Id = oidExtensionAuthorityInfoAccess
1785 var aiaValues []authorityInfoAccess
1786 for _, name := range template.OCSPServer {
1787 aiaValues = append(aiaValues, authorityInfoAccess{
1788 Method: oidAuthorityInfoAccessOcsp,
1789 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1792 for _, name := range template.IssuingCertificateURL {
1793 aiaValues = append(aiaValues, authorityInfoAccess{
1794 Method: oidAuthorityInfoAccessIssuers,
1795 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1798 ret[n].Value, err = asn1.Marshal(aiaValues)
1805 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1806 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1807 ret[n].Id = oidExtensionSubjectAltName
1808 // From RFC 5280, Section 4.2.1.6:
1809 // “If the subject field contains an empty sequence ... then
1810 // subjectAltName extension ... is marked as critical”
1811 ret[n].Critical = subjectIsEmpty
1812 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1819 if len(template.PolicyIdentifiers) > 0 &&
1820 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1821 ret[n].Id = oidExtensionCertificatePolicies
1822 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1823 for i, policy := range template.PolicyIdentifiers {
1824 policies[i].Policy = policy
1826 ret[n].Value, err = asn1.Marshal(policies)
1833 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1834 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1835 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1836 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1837 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1838 ret[n].Id = oidExtensionNameConstraints
1839 ret[n].Critical = template.PermittedDNSDomainsCritical
1841 ipAndMask := func(ipNet *net.IPNet) []byte {
1842 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1843 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1844 ipAndMask = append(ipAndMask, maskedIP...)
1845 ipAndMask = append(ipAndMask, ipNet.Mask...)
1849 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1850 var b cryptobyte.Builder
1852 for _, name := range dns {
1853 if err = isIA5String(name); err != nil {
1857 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1858 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1859 b.AddBytes([]byte(name))
1864 for _, ipNet := range ips {
1865 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1866 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1867 b.AddBytes(ipAndMask(ipNet))
1872 for _, email := range emails {
1873 if err = isIA5String(email); err != nil {
1877 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1878 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1879 b.AddBytes([]byte(email))
1884 for _, uriDomain := range uriDomains {
1885 if err = isIA5String(uriDomain); err != nil {
1889 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1890 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1891 b.AddBytes([]byte(uriDomain))
1899 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1904 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1909 var b cryptobyte.Builder
1910 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1911 if len(permitted) > 0 {
1912 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1913 b.AddBytes(permitted)
1917 if len(excluded) > 0 {
1918 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1919 b.AddBytes(excluded)
1924 ret[n].Value, err = b.Bytes()
1931 if len(template.CRLDistributionPoints) > 0 &&
1932 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1933 ret[n].Id = oidExtensionCRLDistributionPoints
1935 var crlDp []distributionPoint
1936 for _, name := range template.CRLDistributionPoints {
1937 dp := distributionPoint{
1938 DistributionPoint: distributionPointName{
1939 FullName: []asn1.RawValue{
1940 {Tag: 6, Class: 2, Bytes: []byte(name)},
1944 crlDp = append(crlDp, dp)
1947 ret[n].Value, err = asn1.Marshal(crlDp)
1954 // Adding another extension here? Remember to update the maximum number
1955 // of elements in the make() at the top of the function and the list of
1956 // template fields used in CreateCertificate documentation.
1958 return append(ret[:n], template.ExtraExtensions...), nil
1961 func subjectBytes(cert *Certificate) ([]byte, error) {
1962 if len(cert.RawSubject) > 0 {
1963 return cert.RawSubject, nil
1966 return asn1.Marshal(cert.Subject.ToRDNSequence())
1969 // signingParamsForPublicKey returns the parameters to use for signing with
1970 // priv. If requestedSigAlgo is not zero then it overrides the default
1971 // signature algorithm.
1972 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1973 var pubType PublicKeyAlgorithm
1975 switch pub := pub.(type) {
1976 case *rsa.PublicKey:
1978 hashFunc = crypto.SHA256
1979 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1980 sigAlgo.Parameters = asn1.NullRawValue
1982 case *ecdsa.PublicKey:
1986 case elliptic.P224(), elliptic.P256():
1987 hashFunc = crypto.SHA256
1988 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1989 case elliptic.P384():
1990 hashFunc = crypto.SHA384
1991 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1992 case elliptic.P521():
1993 hashFunc = crypto.SHA512
1994 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1996 err = errors.New("x509: unknown elliptic curve")
1999 case ed25519.PublicKey:
2001 sigAlgo.Algorithm = oidSignatureEd25519
2004 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
2011 if requestedSigAlgo == 0 {
2016 for _, details := range signatureAlgorithmDetails {
2017 if details.algo == requestedSigAlgo {
2018 if details.pubKeyAlgo != pubType {
2019 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2022 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2023 if hashFunc == 0 && pubType != Ed25519 {
2024 err = errors.New("x509: cannot sign with hash function requested")
2027 if requestedSigAlgo.isRSAPSS() {
2028 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2036 err = errors.New("x509: unknown SignatureAlgorithm")
2042 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2043 // just an empty SEQUENCE.
2044 var emptyASN1Subject = []byte{0x30, 0}
2046 // CreateCertificate creates a new X.509v3 certificate based on a template.
2047 // The following members of template are used:
2050 // - BasicConstraintsValid
2051 // - CRLDistributionPoints
2054 // - ExcludedDNSDomains
2055 // - ExcludedEmailAddresses
2056 // - ExcludedIPRanges
2057 // - ExcludedURIDomains
2059 // - ExtraExtensions
2062 // - IssuingCertificateURL
2069 // - PermittedDNSDomains
2070 // - PermittedDNSDomainsCritical
2071 // - PermittedEmailAddresses
2072 // - PermittedIPRanges
2073 // - PermittedURIDomains
2074 // - PolicyIdentifiers
2076 // - SignatureAlgorithm
2080 // - UnknownExtKeyUsage
2082 // The certificate is signed by parent. If parent is equal to template then the
2083 // certificate is self-signed. The parameter pub is the public key of the
2084 // signee and priv is the private key of the signer.
2086 // The returned slice is the certificate in DER encoding.
2088 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2089 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2090 // crypto.Signer with a supported public key.
2092 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2093 // unless the resulting certificate is self-signed. Otherwise the value from
2094 // template will be used.
2095 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2096 key, ok := priv.(crypto.Signer)
2098 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2101 if template.SerialNumber == nil {
2102 return nil, errors.New("x509: no SerialNumber given")
2105 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2110 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2115 asn1Issuer, err := subjectBytes(parent)
2120 asn1Subject, err := subjectBytes(template)
2125 authorityKeyId := template.AuthorityKeyId
2126 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2127 authorityKeyId = parent.SubjectKeyId
2130 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId)
2135 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2136 c := tbsCertificate{
2138 SerialNumber: template.SerialNumber,
2139 SignatureAlgorithm: signatureAlgorithm,
2140 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2141 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2142 Subject: asn1.RawValue{FullBytes: asn1Subject},
2143 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2144 Extensions: extensions,
2147 tbsCertContents, err := asn1.Marshal(c)
2151 c.Raw = tbsCertContents
2153 signed := tbsCertContents
2160 var signerOpts crypto.SignerOpts = hashFunc
2161 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2162 signerOpts = &rsa.PSSOptions{
2163 SaltLength: rsa.PSSSaltLengthEqualsHash,
2168 var signature []byte
2169 signature, err = key.Sign(rand, signed, signerOpts)
2174 return asn1.Marshal(certificate{
2178 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2182 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2184 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2186 // pemType is the type of a PEM encoded CRL.
2187 var pemType = "X509 CRL"
2189 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2190 // encoded CRLs will appear where they should be DER encoded, so this function
2191 // will transparently handle PEM encoding as long as there isn't any leading
2193 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2194 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2195 block, _ := pem.Decode(crlBytes)
2196 if block != nil && block.Type == pemType {
2197 crlBytes = block.Bytes
2200 return ParseDERCRL(crlBytes)
2203 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2204 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2205 certList := new(pkix.CertificateList)
2206 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2208 } else if len(rest) != 0 {
2209 return nil, errors.New("x509: trailing data after CRL")
2211 return certList, nil
2214 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2215 // contains the given list of revoked certificates.
2216 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2217 key, ok := priv.(crypto.Signer)
2219 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2222 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2227 // Force revocation times to UTC per RFC 5280.
2228 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2229 for i, rc := range revokedCerts {
2230 rc.RevocationTime = rc.RevocationTime.UTC()
2231 revokedCertsUTC[i] = rc
2234 tbsCertList := pkix.TBSCertificateList{
2236 Signature: signatureAlgorithm,
2237 Issuer: c.Subject.ToRDNSequence(),
2238 ThisUpdate: now.UTC(),
2239 NextUpdate: expiry.UTC(),
2240 RevokedCertificates: revokedCertsUTC,
2244 if len(c.SubjectKeyId) > 0 {
2245 var aki pkix.Extension
2246 aki.Id = oidExtensionAuthorityKeyId
2247 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2251 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2254 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2259 signed := tbsCertListContents
2266 var signature []byte
2267 signature, err = key.Sign(rand, signed, hashFunc)
2272 return asn1.Marshal(pkix.CertificateList{
2273 TBSCertList: tbsCertList,
2274 SignatureAlgorithm: signatureAlgorithm,
2275 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2279 // CertificateRequest represents a PKCS #10, certificate signature request.
2280 type CertificateRequest struct {
2281 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2282 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2283 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2284 RawSubject []byte // DER encoded Subject.
2288 SignatureAlgorithm SignatureAlgorithm
2290 PublicKeyAlgorithm PublicKeyAlgorithm
2291 PublicKey interface{}
2295 // Attributes contains the CSR attributes that can parse as
2296 // pkix.AttributeTypeAndValueSET.
2298 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2299 // generating the requestedExtensions attribute.
2300 Attributes []pkix.AttributeTypeAndValueSET
2302 // Extensions contains all requested extensions, in raw form. When parsing
2303 // CSRs, this can be used to extract extensions that are not parsed by this
2305 Extensions []pkix.Extension
2307 // ExtraExtensions contains extensions to be copied, raw, into any CSR
2308 // marshaled by CreateCertificateRequest. Values override any extensions
2309 // that would otherwise be produced based on the other fields but are
2310 // overridden by any extensions specified in Attributes.
2312 // The ExtraExtensions field is not populated by ParseCertificateRequest,
2313 // see Extensions instead.
2314 ExtraExtensions []pkix.Extension
2316 // Subject Alternate Name values.
2318 EmailAddresses []string
2319 IPAddresses []net.IP
2323 // These structures reflect the ASN.1 structure of X.509 certificate
2324 // signature requests (see RFC 2986):
2326 type tbsCertificateRequest struct {
2329 Subject asn1.RawValue
2330 PublicKey publicKeyInfo
2331 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2334 type certificateRequest struct {
2336 TBSCSR tbsCertificateRequest
2337 SignatureAlgorithm pkix.AlgorithmIdentifier
2338 SignatureValue asn1.BitString
2341 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2342 // extensions in a CSR.
2343 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2345 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2346 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2347 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2348 var rawAttributes []asn1.RawValue
2349 b, err := asn1.Marshal(attributes)
2353 rest, err := asn1.Unmarshal(b, &rawAttributes)
2358 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2360 return rawAttributes, nil
2363 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2364 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2365 var attributes []pkix.AttributeTypeAndValueSET
2366 for _, rawAttr := range rawAttributes {
2367 var attr pkix.AttributeTypeAndValueSET
2368 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2369 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2370 // (i.e.: challengePassword or unstructuredName).
2371 if err == nil && len(rest) == 0 {
2372 attributes = append(attributes, attr)
2378 // parseCSRExtensions parses the attributes from a CSR and extracts any
2379 // requested extensions.
2380 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2381 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2382 type pkcs10Attribute struct {
2383 Id asn1.ObjectIdentifier
2384 Values []asn1.RawValue `asn1:"set"`
2387 var ret []pkix.Extension
2388 for _, rawAttr := range rawAttributes {
2389 var attr pkcs10Attribute
2390 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2391 // Ignore attributes that don't parse.
2395 if !attr.Id.Equal(oidExtensionRequest) {
2399 var extensions []pkix.Extension
2400 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2403 ret = append(ret, extensions...)
2409 // CreateCertificateRequest creates a new certificate request based on a
2410 // template. The following members of template are used:
2412 // - SignatureAlgorithm
2418 // - ExtraExtensions
2419 // - Attributes (deprecated)
2421 // priv is the private key to sign the CSR with, and the corresponding public
2422 // key will be included in the CSR. It must implement crypto.Signer and its
2423 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2424 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2425 // ed25519.PrivateKey satisfies this.)
2427 // The returned slice is the certificate request in DER encoding.
2428 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2429 key, ok := priv.(crypto.Signer)
2431 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2434 var hashFunc crypto.Hash
2435 var sigAlgo pkix.AlgorithmIdentifier
2436 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2441 var publicKeyBytes []byte
2442 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2443 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2448 var extensions []pkix.Extension
2450 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2451 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2452 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2457 extensions = append(extensions, pkix.Extension{
2458 Id: oidExtensionSubjectAltName,
2463 extensions = append(extensions, template.ExtraExtensions...)
2465 // Make a copy of template.Attributes because we may alter it below.
2466 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2467 for _, attr := range template.Attributes {
2468 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2469 copy(values, attr.Value)
2470 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2476 extensionsAppended := false
2477 if len(extensions) > 0 {
2478 // Append the extensions to an existing attribute if possible.
2479 for _, atvSet := range attributes {
2480 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2484 // specifiedExtensions contains all the extensions that we
2485 // found specified via template.Attributes.
2486 specifiedExtensions := make(map[string]bool)
2488 for _, atvs := range atvSet.Value {
2489 for _, atv := range atvs {
2490 specifiedExtensions[atv.Type.String()] = true
2494 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2495 newValue = append(newValue, atvSet.Value[0]...)
2497 for _, e := range extensions {
2498 if specifiedExtensions[e.Id.String()] {
2499 // Attributes already contained a value for
2500 // this extension and it takes priority.
2504 newValue = append(newValue, pkix.AttributeTypeAndValue{
2505 // There is no place for the critical
2506 // flag in an AttributeTypeAndValue.
2512 atvSet.Value[0] = newValue
2513 extensionsAppended = true
2518 rawAttributes, err := newRawAttributes(attributes)
2523 // If not included in attributes, add a new attribute for the
2525 if len(extensions) > 0 && !extensionsAppended {
2527 Type asn1.ObjectIdentifier
2528 Value [][]pkix.Extension `asn1:"set"`
2530 Type: oidExtensionRequest,
2531 Value: [][]pkix.Extension{extensions},
2534 b, err := asn1.Marshal(attr)
2536 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2539 var rawValue asn1.RawValue
2540 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2544 rawAttributes = append(rawAttributes, rawValue)
2547 asn1Subject := template.RawSubject
2548 if len(asn1Subject) == 0 {
2549 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2555 tbsCSR := tbsCertificateRequest{
2556 Version: 0, // PKCS #10, RFC 2986
2557 Subject: asn1.RawValue{FullBytes: asn1Subject},
2558 PublicKey: publicKeyInfo{
2559 Algorithm: publicKeyAlgorithm,
2560 PublicKey: asn1.BitString{
2561 Bytes: publicKeyBytes,
2562 BitLength: len(publicKeyBytes) * 8,
2565 RawAttributes: rawAttributes,
2568 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2572 tbsCSR.Raw = tbsCSRContents
2574 signed := tbsCSRContents
2581 var signature []byte
2582 signature, err = key.Sign(rand, signed, hashFunc)
2587 return asn1.Marshal(certificateRequest{
2589 SignatureAlgorithm: sigAlgo,
2590 SignatureValue: asn1.BitString{
2592 BitLength: len(signature) * 8,
2597 // ParseCertificateRequest parses a single certificate request from the
2598 // given ASN.1 DER data.
2599 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2600 var csr certificateRequest
2602 rest, err := asn1.Unmarshal(asn1Data, &csr)
2605 } else if len(rest) != 0 {
2606 return nil, asn1.SyntaxError{Msg: "trailing data"}
2609 return parseCertificateRequest(&csr)
2612 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2613 out := &CertificateRequest{
2615 RawTBSCertificateRequest: in.TBSCSR.Raw,
2616 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2617 RawSubject: in.TBSCSR.Subject.FullBytes,
2619 Signature: in.SignatureValue.RightAlign(),
2620 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2622 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2624 Version: in.TBSCSR.Version,
2625 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2629 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2634 var subject pkix.RDNSequence
2635 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2637 } else if len(rest) != 0 {
2638 return nil, errors.New("x509: trailing data after X.509 Subject")
2641 out.Subject.FillFromRDNSequence(&subject)
2643 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2647 for _, extension := range out.Extensions {
2648 if extension.Id.Equal(oidExtensionSubjectAltName) {
2649 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2659 // CheckSignature reports whether the signature on c is valid.
2660 func (c *CertificateRequest) CheckSignature() error {
2661 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)