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 parses X.509-encoded keys and certificates. 6// 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. 10// 11// This is a fork of the Go library crypto/x509 package, primarily adapted for 12// use with Certificate Transparency. Main areas of difference are: 13// 14// - Life as a fork: 15// - Rename OS-specific cgo code so it doesn't clash with main Go library. 16// - Use local library imports (asn1, pkix) throughout. 17// - Add version-specific wrappers for Go version-incompatible code (in 18// ptr_*_windows.go). 19// - Laxer certificate parsing: 20// - Add options to disable various validation checks (times, EKUs etc). 21// - Use NonFatalErrors type for some errors and continue parsing; this 22// can be checked with IsFatal(err). 23// - Support for short bitlength ECDSA curves (in curves.go). 24// - Certificate Transparency specific function: 25// - Parsing and marshaling of SCTList extension. 26// - RemoveSCTList() function for rebuilding CT leaf entry. 27// - Pre-certificate processing (RemoveCTPoison(), BuildPrecertTBS(), 28// ParseTBSCertificate(), IsPrecertificate()). 29// - Revocation list processing: 30// - Detailed CRL parsing (in revoked.go) 31// - Detailed error recording mechanism (in error.go, errors.go) 32// - Factor out parseDistributionPoints() for reuse. 33// - Factor out and generalize GeneralNames parsing (in names.go) 34// - Fix CRL commenting. 35// - RPKI support: 36// - Support for SubjectInfoAccess extension 37// - Support for RFC3779 extensions (in rpki.go) 38// - RSAES-OAEP support: 39// - Support for parsing RSASES-OAEP public keys from certificates 40// - Ed25519 support: 41// - Support for parsing and marshaling Ed25519 keys 42// - General improvements: 43// - Export and use OID values throughout. 44// - Export OIDFromNamedCurve(). 45// - Export SignatureAlgorithmFromAI(). 46// - Add OID value to UnhandledCriticalExtension error. 47// - Minor typo/lint fixes. 48package x509 49 50import ( 51 "bytes" 52 "crypto" 53 "crypto/dsa" 54 "crypto/ecdsa" 55 "crypto/elliptic" 56 "crypto/rsa" 57 _ "crypto/sha1" 58 _ "crypto/sha256" 59 _ "crypto/sha512" 60 "encoding/pem" 61 "errors" 62 "fmt" 63 "io" 64 "math/big" 65 "net" 66 "net/url" 67 "strconv" 68 "strings" 69 "time" 70 "unicode/utf8" 71 72 "golang.org/x/crypto/cryptobyte" 73 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" 74 "golang.org/x/crypto/ed25519" 75 76 "github.com/google/certificate-transparency-go/asn1" 77 "github.com/google/certificate-transparency-go/tls" 78 "github.com/google/certificate-transparency-go/x509/pkix" 79) 80 81// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo 82// in RFC 3280. 83type pkixPublicKey struct { 84 Algo pkix.AlgorithmIdentifier 85 BitString asn1.BitString 86} 87 88// ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. 89// 90// It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or 91// ed25519.PublicKey. More types might be supported in the future. 92// 93// This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". 94func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { 95 var pki publicKeyInfo 96 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil { 97 return nil, err 98 } else if len(rest) != 0 { 99 return nil, errors.New("x509: trailing data after ASN.1 of public-key") 100 } 101 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) 102 if algo == UnknownPublicKeyAlgorithm { 103 return nil, errors.New("x509: unknown public key algorithm") 104 } 105 var nfe NonFatalErrors 106 pub, err = parsePublicKey(algo, &pki, &nfe) 107 if err != nil { 108 return pub, err 109 } 110 // Treat non-fatal errors as fatal for this entrypoint. 111 if len(nfe.Errors) > 0 { 112 return nil, nfe.Errors[0] 113 } 114 return pub, nil 115} 116 117func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { 118 switch pub := pub.(type) { 119 case *rsa.PublicKey: 120 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{ 121 N: pub.N, 122 E: pub.E, 123 }) 124 if err != nil { 125 return nil, pkix.AlgorithmIdentifier{}, err 126 } 127 publicKeyAlgorithm.Algorithm = OIDPublicKeyRSA 128 // This is a NULL parameters value which is required by 129 // RFC 3279, Section 2.3.1. 130 publicKeyAlgorithm.Parameters = asn1.NullRawValue 131 case *ecdsa.PublicKey: 132 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 133 oid, ok := OIDFromNamedCurve(pub.Curve) 134 if !ok { 135 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") 136 } 137 publicKeyAlgorithm.Algorithm = OIDPublicKeyECDSA 138 var paramBytes []byte 139 paramBytes, err = asn1.Marshal(oid) 140 if err != nil { 141 return 142 } 143 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 144 case ed25519.PublicKey: 145 publicKeyBytes = pub 146 publicKeyAlgorithm.Algorithm = OIDPublicKeyEd25519 147 default: 148 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub) 149 } 150 151 return publicKeyBytes, publicKeyAlgorithm, nil 152} 153 154// MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. 155// 156// The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey 157// and ed25519.PublicKey. Unsupported key types result in an error. 158// 159// This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". 160func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { 161 var publicKeyBytes []byte 162 var publicKeyAlgorithm pkix.AlgorithmIdentifier 163 var err error 164 165 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { 166 return nil, err 167 } 168 169 pkix := pkixPublicKey{ 170 Algo: publicKeyAlgorithm, 171 BitString: asn1.BitString{ 172 Bytes: publicKeyBytes, 173 BitLength: 8 * len(publicKeyBytes), 174 }, 175 } 176 177 ret, _ := asn1.Marshal(pkix) 178 return ret, nil 179} 180 181// These structures reflect the ASN.1 structure of X.509 certificates.: 182 183type certificate struct { 184 Raw asn1.RawContent 185 TBSCertificate tbsCertificate 186 SignatureAlgorithm pkix.AlgorithmIdentifier 187 SignatureValue asn1.BitString 188} 189 190type tbsCertificate struct { 191 Raw asn1.RawContent 192 Version int `asn1:"optional,explicit,default:0,tag:0"` 193 SerialNumber *big.Int 194 SignatureAlgorithm pkix.AlgorithmIdentifier 195 Issuer asn1.RawValue 196 Validity validity 197 Subject asn1.RawValue 198 PublicKey publicKeyInfo 199 UniqueId asn1.BitString `asn1:"optional,tag:1"` 200 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` 201 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` 202} 203 204// RFC 4055, 4.1 205// The current ASN.1 parser does not support non-integer defaults so 206// the 'default:' tags here do nothing. 207type rsaesoaepAlgorithmParameters struct { 208 HashFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:0,default:sha1Identifier"` 209 MaskgenFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:1,default:mgf1SHA1Identifier"` 210 PSourceFunc pkix.AlgorithmIdentifier `asn1:"optional,explicit,tag:2,default:pSpecifiedEmptyIdentifier"` 211} 212 213type dsaAlgorithmParameters struct { 214 P, Q, G *big.Int 215} 216 217type dsaSignature struct { 218 R, S *big.Int 219} 220 221type ecdsaSignature dsaSignature 222 223type validity struct { 224 NotBefore, NotAfter time.Time 225} 226 227type publicKeyInfo struct { 228 Raw asn1.RawContent 229 Algorithm pkix.AlgorithmIdentifier 230 PublicKey asn1.BitString 231} 232 233// RFC 5280, 4.2.1.1 234type authKeyId struct { 235 Id []byte `asn1:"optional,tag:0"` 236} 237 238// SignatureAlgorithm indicates the algorithm used to sign a certificate. 239type SignatureAlgorithm int 240 241// SignatureAlgorithm values: 242const ( 243 UnknownSignatureAlgorithm SignatureAlgorithm = iota 244 MD2WithRSA 245 MD5WithRSA 246 SHA1WithRSA 247 SHA256WithRSA 248 SHA384WithRSA 249 SHA512WithRSA 250 DSAWithSHA1 251 DSAWithSHA256 252 ECDSAWithSHA1 253 ECDSAWithSHA256 254 ECDSAWithSHA384 255 ECDSAWithSHA512 256 SHA256WithRSAPSS 257 SHA384WithRSAPSS 258 SHA512WithRSAPSS 259 PureEd25519 260) 261 262// RFC 4055, 6. Basic object identifiers 263var oidpSpecified = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 9} 264 265// These are the default parameters for an RSAES-OAEP pubkey. 266// The current ASN.1 parser does not support non-integer defaults so 267// these currently do nothing. 268var ( 269 sha1Identifier = pkix.AlgorithmIdentifier{ 270 Algorithm: oidSHA1, 271 Parameters: asn1.NullRawValue, 272 } 273 mgf1SHA1Identifier = pkix.AlgorithmIdentifier{ 274 Algorithm: oidMGF1, 275 // RFC 4055, 2.1 sha1Identifier 276 Parameters: asn1.RawValue{ 277 Class: asn1.ClassUniversal, 278 Tag: asn1.TagSequence, 279 IsCompound: false, 280 Bytes: []byte{6, 5, 43, 14, 3, 2, 26, 5, 0}, 281 FullBytes: []byte{16, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0}}, 282 } 283 pSpecifiedEmptyIdentifier = pkix.AlgorithmIdentifier{ 284 Algorithm: oidpSpecified, 285 // RFC 4055, 4.1 nullOctetString 286 Parameters: asn1.RawValue{ 287 Class: asn1.ClassUniversal, 288 Tag: asn1.TagOctetString, 289 IsCompound: false, 290 Bytes: []byte{}, 291 FullBytes: []byte{4, 0}}, 292 } 293) 294 295func (algo SignatureAlgorithm) isRSAPSS() bool { 296 switch algo { 297 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS: 298 return true 299 default: 300 return false 301 } 302} 303 304func (algo SignatureAlgorithm) String() string { 305 for _, details := range signatureAlgorithmDetails { 306 if details.algo == algo { 307 return details.name 308 } 309 } 310 return strconv.Itoa(int(algo)) 311} 312 313// PublicKeyAlgorithm indicates the algorithm used for a certificate's public key. 314type PublicKeyAlgorithm int 315 316// PublicKeyAlgorithm values: 317const ( 318 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota 319 RSA 320 DSA 321 ECDSA 322 Ed25519 323 RSAESOAEP 324) 325 326var publicKeyAlgoName = [...]string{ 327 RSA: "RSA", 328 DSA: "DSA", 329 ECDSA: "ECDSA", 330 Ed25519: "Ed25519", 331 RSAESOAEP: "RSAESOAEP", 332} 333 334func (algo PublicKeyAlgorithm) String() string { 335 if 0 < algo && int(algo) < len(publicKeyAlgoName) { 336 return publicKeyAlgoName[algo] 337 } 338 return strconv.Itoa(int(algo)) 339} 340 341// OIDs for signature algorithms 342// 343// pkcs-1 OBJECT IDENTIFIER ::= { 344// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } 345// 346// 347// RFC 3279 2.2.1 RSA Signature Algorithms 348// 349// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } 350// 351// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } 352// 353// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } 354// 355// dsaWithSha1 OBJECT IDENTIFIER ::= { 356// iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 357// 358// RFC 3279 2.2.3 ECDSA Signature Algorithm 359// 360// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { 361// iso(1) member-body(2) us(840) ansi-x962(10045) 362// signatures(4) ecdsa-with-SHA1(1)} 363// 364// 365// RFC 4055 5 PKCS #1 Version 1.5 366// 367// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } 368// 369// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } 370// 371// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } 372// 373// 374// RFC 5758 3.1 DSA Signature Algorithms 375// 376// dsaWithSha256 OBJECT IDENTIFIER ::= { 377// joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) 378// csor(3) algorithms(4) id-dsa-with-sha2(3) 2} 379// 380// RFC 5758 3.2 ECDSA Signature Algorithm 381// 382// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 383// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } 384// 385// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 386// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } 387// 388// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 389// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } 390// 391// 392// RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers 393// 394// id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 } 395 396var ( 397 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} 398 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} 399 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} 400 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} 401 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} 402 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} 403 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10} 404 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} 405 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2} 406 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} 407 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} 408 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} 409 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} 410 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112} 411 412 oidSHA1 = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26} 413 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1} 414 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2} 415 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3} 416 417 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8} 418 419 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA 420 // but it's specified by ISO. Microsoft's makecert.exe has been known 421 // to produce certificates with this OID. 422 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29} 423) 424 425var signatureAlgorithmDetails = []struct { 426 algo SignatureAlgorithm 427 name string 428 oid asn1.ObjectIdentifier 429 pubKeyAlgo PublicKeyAlgorithm 430 hash crypto.Hash 431}{ 432 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */}, 433 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5}, 434 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1}, 435 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1}, 436 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256}, 437 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384}, 438 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512}, 439 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256}, 440 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384}, 441 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512}, 442 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1}, 443 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256}, 444 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1}, 445 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256}, 446 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384}, 447 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512}, 448 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */}, 449} 450 451// pssParameters reflects the parameters in an AlgorithmIdentifier that 452// specifies RSA PSS. See RFC 3447, Appendix A.2.3. 453type pssParameters struct { 454 // The following three fields are not marked as 455 // optional because the default values specify SHA-1, 456 // which is no longer suitable for use in signatures. 457 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"` 458 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"` 459 SaltLength int `asn1:"explicit,tag:2"` 460 TrailerField int `asn1:"optional,explicit,tag:3,default:1"` 461} 462 463// rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters 464// in an AlgorithmIdentifier that specifies RSA PSS. 465func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue { 466 var hashOID asn1.ObjectIdentifier 467 468 switch hashFunc { 469 case crypto.SHA256: 470 hashOID = oidSHA256 471 case crypto.SHA384: 472 hashOID = oidSHA384 473 case crypto.SHA512: 474 hashOID = oidSHA512 475 } 476 477 params := pssParameters{ 478 Hash: pkix.AlgorithmIdentifier{ 479 Algorithm: hashOID, 480 Parameters: asn1.NullRawValue, 481 }, 482 MGF: pkix.AlgorithmIdentifier{ 483 Algorithm: oidMGF1, 484 }, 485 SaltLength: hashFunc.Size(), 486 TrailerField: 1, 487 } 488 489 mgf1Params := pkix.AlgorithmIdentifier{ 490 Algorithm: hashOID, 491 Parameters: asn1.NullRawValue, 492 } 493 494 var err error 495 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params) 496 if err != nil { 497 panic(err) 498 } 499 500 serialized, err := asn1.Marshal(params) 501 if err != nil { 502 panic(err) 503 } 504 505 return asn1.RawValue{FullBytes: serialized} 506} 507 508// SignatureAlgorithmFromAI converts an PKIX algorithm identifier to the 509// equivalent local constant. 510func SignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm { 511 if ai.Algorithm.Equal(oidSignatureEd25519) { 512 // RFC 8410, Section 3 513 // > For all of the OIDs, the parameters MUST be absent. 514 if len(ai.Parameters.FullBytes) != 0 { 515 return UnknownSignatureAlgorithm 516 } 517 } 518 519 if !ai.Algorithm.Equal(oidSignatureRSAPSS) { 520 for _, details := range signatureAlgorithmDetails { 521 if ai.Algorithm.Equal(details.oid) { 522 return details.algo 523 } 524 } 525 return UnknownSignatureAlgorithm 526 } 527 528 // RSA PSS is special because it encodes important parameters 529 // in the Parameters. 530 531 var params pssParameters 532 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil { 533 return UnknownSignatureAlgorithm 534 } 535 536 var mgf1HashFunc pkix.AlgorithmIdentifier 537 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil { 538 return UnknownSignatureAlgorithm 539 } 540 541 // PSS is greatly overburdened with options. This code forces them into 542 // three buckets by requiring that the MGF1 hash function always match the 543 // message hash function (as recommended in RFC 3447, Section 8.1), that the 544 // salt length matches the hash length, and that the trailer field has the 545 // default value. 546 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) || 547 !params.MGF.Algorithm.Equal(oidMGF1) || 548 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) || 549 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) || 550 params.TrailerField != 1 { 551 return UnknownSignatureAlgorithm 552 } 553 554 switch { 555 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32: 556 return SHA256WithRSAPSS 557 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48: 558 return SHA384WithRSAPSS 559 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64: 560 return SHA512WithRSAPSS 561 } 562 563 return UnknownSignatureAlgorithm 564} 565 566// RFC 3279, 2.3 Public Key Algorithms 567// 568// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 569// rsadsi(113549) pkcs(1) 1 } 570// 571// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } 572// 573// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 574// x9-57(10040) x9cm(4) 1 } 575// 576// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters 577// 578// id-ecPublicKey OBJECT IDENTIFIER ::= { 579// iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } 580var ( 581 OIDPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} 582 OIDPublicKeyRSAESOAEP = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 7} 583 OIDPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} 584 OIDPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} 585 OIDPublicKeyRSAObsolete = asn1.ObjectIdentifier{2, 5, 8, 1, 1} 586 OIDPublicKeyEd25519 = oidSignatureEd25519 587) 588 589func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { 590 switch { 591 case oid.Equal(OIDPublicKeyRSA): 592 return RSA 593 case oid.Equal(OIDPublicKeyDSA): 594 return DSA 595 case oid.Equal(OIDPublicKeyECDSA): 596 return ECDSA 597 case oid.Equal(OIDPublicKeyRSAESOAEP): 598 return RSAESOAEP 599 case oid.Equal(OIDPublicKeyEd25519): 600 return Ed25519 601 } 602 return UnknownPublicKeyAlgorithm 603} 604 605// RFC 5480, 2.1.1.1. Named Curve 606// 607// secp224r1 OBJECT IDENTIFIER ::= { 608// iso(1) identified-organization(3) certicom(132) curve(0) 33 } 609// 610// secp256r1 OBJECT IDENTIFIER ::= { 611// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) 612// prime(1) 7 } 613// 614// secp384r1 OBJECT IDENTIFIER ::= { 615// iso(1) identified-organization(3) certicom(132) curve(0) 34 } 616// 617// secp521r1 OBJECT IDENTIFIER ::= { 618// iso(1) identified-organization(3) certicom(132) curve(0) 35 } 619// 620// secp192r1 OBJECT IDENTIFIER ::= { 621// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) 622// prime(1) 1 } 623// 624// NB: secp256r1 is equivalent to prime256v1, 625// secp192r1 is equivalent to ansix9p192r and prime192v1 626var ( 627 OIDNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} 628 OIDNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} 629 OIDNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} 630 OIDNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} 631 OIDNamedCurveP192 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 1} 632) 633 634func namedCurveFromOID(oid asn1.ObjectIdentifier, nfe *NonFatalErrors) elliptic.Curve { 635 switch { 636 case oid.Equal(OIDNamedCurveP224): 637 return elliptic.P224() 638 case oid.Equal(OIDNamedCurveP256): 639 return elliptic.P256() 640 case oid.Equal(OIDNamedCurveP384): 641 return elliptic.P384() 642 case oid.Equal(OIDNamedCurveP521): 643 return elliptic.P521() 644 case oid.Equal(OIDNamedCurveP192): 645 nfe.AddError(errors.New("insecure curve (secp192r1) specified")) 646 return secp192r1() 647 } 648 return nil 649} 650 651// OIDFromNamedCurve returns the OID used to specify the use of the given 652// elliptic curve. 653func OIDFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { 654 switch curve { 655 case elliptic.P224(): 656 return OIDNamedCurveP224, true 657 case elliptic.P256(): 658 return OIDNamedCurveP256, true 659 case elliptic.P384(): 660 return OIDNamedCurveP384, true 661 case elliptic.P521(): 662 return OIDNamedCurveP521, true 663 case secp192r1(): 664 return OIDNamedCurveP192, true 665 } 666 667 return nil, false 668} 669 670// KeyUsage represents the set of actions that are valid for a given key. It's 671// a bitmap of the KeyUsage* constants. 672type KeyUsage int 673 674// KeyUsage values: 675const ( 676 KeyUsageDigitalSignature KeyUsage = 1 << iota 677 KeyUsageContentCommitment 678 KeyUsageKeyEncipherment 679 KeyUsageDataEncipherment 680 KeyUsageKeyAgreement 681 KeyUsageCertSign 682 KeyUsageCRLSign 683 KeyUsageEncipherOnly 684 KeyUsageDecipherOnly 685) 686 687// RFC 5280, 4.2.1.12 Extended Key Usage 688// 689// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } 690// 691// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } 692// 693// id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } 694// id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } 695// id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } 696// id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } 697// id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } 698// id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } 699var ( 700 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} 701 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} 702 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} 703 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} 704 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} 705 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} 706 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} 707 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} 708 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} 709 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} 710 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} 711 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} 712 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22} 713 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1} 714 // RFC 6962 s3.1 715 oidExtKeyUsageCertificateTransparency = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 4} 716) 717 718// ExtKeyUsage represents an extended set of actions that are valid for a given key. 719// Each of the ExtKeyUsage* constants define a unique action. 720type ExtKeyUsage int 721 722// ExtKeyUsage values: 723const ( 724 ExtKeyUsageAny ExtKeyUsage = iota 725 ExtKeyUsageServerAuth 726 ExtKeyUsageClientAuth 727 ExtKeyUsageCodeSigning 728 ExtKeyUsageEmailProtection 729 ExtKeyUsageIPSECEndSystem 730 ExtKeyUsageIPSECTunnel 731 ExtKeyUsageIPSECUser 732 ExtKeyUsageTimeStamping 733 ExtKeyUsageOCSPSigning 734 ExtKeyUsageMicrosoftServerGatedCrypto 735 ExtKeyUsageNetscapeServerGatedCrypto 736 ExtKeyUsageMicrosoftCommercialCodeSigning 737 ExtKeyUsageMicrosoftKernelCodeSigning 738 ExtKeyUsageCertificateTransparency 739) 740 741// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. 742var extKeyUsageOIDs = []struct { 743 extKeyUsage ExtKeyUsage 744 oid asn1.ObjectIdentifier 745}{ 746 {ExtKeyUsageAny, oidExtKeyUsageAny}, 747 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, 748 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, 749 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, 750 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, 751 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, 752 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, 753 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, 754 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, 755 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, 756 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, 757 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, 758 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning}, 759 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning}, 760 {ExtKeyUsageCertificateTransparency, oidExtKeyUsageCertificateTransparency}, 761} 762 763func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { 764 for _, pair := range extKeyUsageOIDs { 765 if oid.Equal(pair.oid) { 766 return pair.extKeyUsage, true 767 } 768 } 769 return 770} 771 772func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { 773 for _, pair := range extKeyUsageOIDs { 774 if eku == pair.extKeyUsage { 775 return pair.oid, true 776 } 777 } 778 return 779} 780 781// SerializedSCT represents a single TLS-encoded signed certificate timestamp, from RFC6962 s3.3. 782type SerializedSCT struct { 783 Val []byte `tls:"minlen:1,maxlen:65535"` 784} 785 786// SignedCertificateTimestampList is a list of signed certificate timestamps, from RFC6962 s3.3. 787type SignedCertificateTimestampList struct { 788 SCTList []SerializedSCT `tls:"minlen:1,maxlen:65335"` 789} 790 791// A Certificate represents an X.509 certificate. 792type Certificate struct { 793 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature). 794 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content. 795 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 796 RawSubject []byte // DER encoded Subject 797 RawIssuer []byte // DER encoded Issuer 798 799 Signature []byte 800 SignatureAlgorithm SignatureAlgorithm 801 802 PublicKeyAlgorithm PublicKeyAlgorithm 803 PublicKey interface{} 804 805 Version int 806 SerialNumber *big.Int 807 Issuer pkix.Name 808 Subject pkix.Name 809 NotBefore, NotAfter time.Time // Validity bounds. 810 KeyUsage KeyUsage 811 812 // Extensions contains raw X.509 extensions. When parsing certificates, 813 // this can be used to extract non-critical extensions that are not 814 // parsed by this package. When marshaling certificates, the Extensions 815 // field is ignored, see ExtraExtensions. 816 Extensions []pkix.Extension 817 818 // ExtraExtensions contains extensions to be copied, raw, into any 819 // marshaled certificates. Values override any extensions that would 820 // otherwise be produced based on the other fields. The ExtraExtensions 821 // field is not populated when parsing certificates, see Extensions. 822 ExtraExtensions []pkix.Extension 823 824 // UnhandledCriticalExtensions contains a list of extension IDs that 825 // were not (fully) processed when parsing. Verify will fail if this 826 // slice is non-empty, unless verification is delegated to an OS 827 // library which understands all the critical extensions. 828 // 829 // Users can access these extensions using Extensions and can remove 830 // elements from this slice if they believe that they have been 831 // handled. 832 UnhandledCriticalExtensions []asn1.ObjectIdentifier 833 834 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. 835 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. 836 837 // BasicConstraintsValid indicates whether IsCA, MaxPathLen, 838 // and MaxPathLenZero are valid. 839 BasicConstraintsValid bool 840 IsCA bool 841 842 // MaxPathLen and MaxPathLenZero indicate the presence and 843 // value of the BasicConstraints' "pathLenConstraint". 844 // 845 // When parsing a certificate, a positive non-zero MaxPathLen 846 // means that the field was specified, -1 means it was unset, 847 // and MaxPathLenZero being true mean that the field was 848 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false 849 // should be treated equivalent to -1 (unset). 850 // 851 // When generating a certificate, an unset pathLenConstraint 852 // can be requested with either MaxPathLen == -1 or using the 853 // zero value for both MaxPathLen and MaxPathLenZero. 854 MaxPathLen int 855 // MaxPathLenZero indicates that BasicConstraintsValid==true 856 // and MaxPathLen==0 should be interpreted as an actual 857 // maximum path length of zero. Otherwise, that combination is 858 // interpreted as MaxPathLen not being set. 859 MaxPathLenZero bool 860 861 SubjectKeyId []byte 862 AuthorityKeyId []byte 863 864 // RFC 5280, 4.2.2.1 (Authority Information Access) 865 OCSPServer []string 866 IssuingCertificateURL []string 867 868 // Subject Information Access 869 SubjectTimestamps []string 870 SubjectCARepositories []string 871 872 // Subject Alternate Name values. (Note that these values may not be valid 873 // if invalid values were contained within a parsed certificate. For 874 // example, an element of DNSNames may not be a valid DNS domain name.) 875 DNSNames []string 876 EmailAddresses []string 877 IPAddresses []net.IP 878 URIs []*url.URL 879 880 // Name constraints 881 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. 882 PermittedDNSDomains []string 883 ExcludedDNSDomains []string 884 PermittedIPRanges []*net.IPNet 885 ExcludedIPRanges []*net.IPNet 886 PermittedEmailAddresses []string 887 ExcludedEmailAddresses []string 888 PermittedURIDomains []string 889 ExcludedURIDomains []string 890 891 // CRL Distribution Points 892 CRLDistributionPoints []string 893 894 PolicyIdentifiers []asn1.ObjectIdentifier 895 896 RPKIAddressRanges []*IPAddressFamilyBlocks 897 RPKIASNumbers, RPKIRoutingDomainIDs *ASIdentifiers 898 899 // Certificate Transparency SCT extension contents; this is a TLS-encoded 900 // SignedCertificateTimestampList (RFC 6962 s3.3). 901 RawSCT []byte 902 SCTList SignedCertificateTimestampList 903} 904 905// ErrUnsupportedAlgorithm results from attempting to perform an operation that 906// involves algorithms that are not currently implemented. 907var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") 908 909// InsecureAlgorithmError results when the signature algorithm for a certificate 910// is known to be insecure. 911type InsecureAlgorithmError SignatureAlgorithm 912 913func (e InsecureAlgorithmError) Error() string { 914 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) 915} 916 917// ConstraintViolationError results when a requested usage is not permitted by 918// a certificate. For example: checking a signature when the public key isn't a 919// certificate signing key. 920type ConstraintViolationError struct{} 921 922func (ConstraintViolationError) Error() string { 923 return "x509: invalid signature: parent certificate cannot sign this kind of certificate" 924} 925 926// Equal indicates whether two Certificate objects are equal (by comparing their 927// DER-encoded values). 928func (c *Certificate) Equal(other *Certificate) bool { 929 if c == nil || other == nil { 930 return c == other 931 } 932 return bytes.Equal(c.Raw, other.Raw) 933} 934 935// IsPrecertificate checks whether the certificate is a precertificate, by 936// checking for the presence of the CT Poison extension. 937func (c *Certificate) IsPrecertificate() bool { 938 if c == nil { 939 return false 940 } 941 for _, ext := range c.Extensions { 942 if ext.Id.Equal(OIDExtensionCTPoison) { 943 return true 944 } 945 } 946 return false 947} 948 949func (c *Certificate) hasSANExtension() bool { 950 return oidInExtensions(OIDExtensionSubjectAltName, c.Extensions) 951} 952 953// Entrust have a broken root certificate (CN=Entrust.net Certification 954// Authority (2048)) which isn't marked as a CA certificate and is thus invalid 955// according to PKIX. 956// We recognise this certificate by its SubjectPublicKeyInfo and exempt it 957// from the Basic Constraints requirement. 958// See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 959// 960// TODO(agl): remove this hack once their reissued root is sufficiently 961// widespread. 962var entrustBrokenSPKI = []byte{ 963 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 964 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 965 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 966 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 967 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, 968 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, 969 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, 970 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, 971 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, 972 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, 973 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, 974 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, 975 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, 976 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, 977 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, 978 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, 979 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, 980 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, 981 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, 982 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, 983 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, 984 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, 985 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, 986 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, 987 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, 988 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, 989 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, 990 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, 991 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, 992 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, 993 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, 994 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, 995 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, 996 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, 997 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, 998 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, 999 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, 1000} 1001 1002// CheckSignatureFrom verifies that the signature on c is a valid signature 1003// from parent. 1004func (c *Certificate) CheckSignatureFrom(parent *Certificate) error { 1005 // RFC 5280, 4.2.1.9: 1006 // "If the basic constraints extension is not present in a version 3 1007 // certificate, or the extension is present but the cA boolean is not 1008 // asserted, then the certified public key MUST NOT be used to verify 1009 // certificate signatures." 1010 // (except for Entrust, see comment above entrustBrokenSPKI) 1011 if (parent.Version == 3 && !parent.BasicConstraintsValid || 1012 parent.BasicConstraintsValid && !parent.IsCA) && 1013 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { 1014 return ConstraintViolationError{} 1015 } 1016 1017 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { 1018 return ConstraintViolationError{} 1019 } 1020 1021 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 1022 return ErrUnsupportedAlgorithm 1023 } 1024 1025 // TODO(agl): don't ignore the path length constraint. 1026 1027 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) 1028} 1029 1030// CheckSignature verifies that signature is a valid signature over signed from 1031// c's public key. 1032func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error { 1033 return checkSignature(algo, signed, signature, c.PublicKey) 1034} 1035 1036func (c *Certificate) hasNameConstraints() bool { 1037 return oidInExtensions(OIDExtensionNameConstraints, c.Extensions) 1038} 1039 1040func (c *Certificate) getSANExtension() []byte { 1041 for _, e := range c.Extensions { 1042 if e.Id.Equal(OIDExtensionSubjectAltName) { 1043 return e.Value 1044 } 1045 } 1046 1047 return nil 1048} 1049 1050func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error { 1051 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey) 1052} 1053 1054// CheckSignature verifies that signature is a valid signature over signed from 1055// a crypto.PublicKey. 1056func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) { 1057 var hashType crypto.Hash 1058 var pubKeyAlgo PublicKeyAlgorithm 1059 1060 for _, details := range signatureAlgorithmDetails { 1061 if details.algo == algo { 1062 hashType = details.hash 1063 pubKeyAlgo = details.pubKeyAlgo 1064 } 1065 } 1066 1067 switch hashType { 1068 case crypto.Hash(0): 1069 if pubKeyAlgo != Ed25519 { 1070 return ErrUnsupportedAlgorithm 1071 } 1072 case crypto.MD5: 1073 return InsecureAlgorithmError(algo) 1074 default: 1075 if !hashType.Available() { 1076 return ErrUnsupportedAlgorithm 1077 } 1078 h := hashType.New() 1079 h.Write(signed) 1080 signed = h.Sum(nil) 1081 } 1082 1083 switch pub := publicKey.(type) { 1084 case *rsa.PublicKey: 1085 if pubKeyAlgo != RSA { 1086 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1087 } 1088 if algo.isRSAPSS() { 1089 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}) 1090 } else { 1091 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature) 1092 } 1093 case *dsa.PublicKey: 1094 if pubKeyAlgo != DSA { 1095 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1096 } 1097 dsaSig := new(dsaSignature) 1098 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil { 1099 return err 1100 } else if len(rest) != 0 { 1101 return errors.New("x509: trailing data after DSA signature") 1102 } 1103 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { 1104 return errors.New("x509: DSA signature contained zero or negative values") 1105 } 1106 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer 1107 // than the key length, but crypto/dsa doesn't do it automatically. 1108 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) { 1109 signed = signed[:maxHashLen] 1110 } 1111 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) { 1112 return errors.New("x509: DSA verification failure") 1113 } 1114 return 1115 case *ecdsa.PublicKey: 1116 if pubKeyAlgo != ECDSA { 1117 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1118 } 1119 ecdsaSig := new(ecdsaSignature) 1120 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { 1121 return err 1122 } else if len(rest) != 0 { 1123 return errors.New("x509: trailing data after ECDSA signature") 1124 } 1125 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { 1126 return errors.New("x509: ECDSA signature contained zero or negative values") 1127 } 1128 if !ecdsa.Verify(pub, signed, ecdsaSig.R, ecdsaSig.S) { 1129 return errors.New("x509: ECDSA verification failure") 1130 } 1131 return 1132 case ed25519.PublicKey: 1133 if pubKeyAlgo != Ed25519 { 1134 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub) 1135 } 1136 if !ed25519.Verify(pub, signed, signature) { 1137 return errors.New("x509: Ed25519 verification failure") 1138 } 1139 return 1140 } 1141 return ErrUnsupportedAlgorithm 1142} 1143 1144// CheckCRLSignature checks that the signature in crl is from c. 1145func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error { 1146 algo := SignatureAlgorithmFromAI(crl.SignatureAlgorithm) 1147 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) 1148} 1149 1150// UnhandledCriticalExtension results when the certificate contains an extension 1151// that is marked as critical but which is not handled by this library. 1152type UnhandledCriticalExtension struct { 1153 ID asn1.ObjectIdentifier 1154} 1155 1156func (h UnhandledCriticalExtension) Error() string { 1157 return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID) 1158} 1159 1160// removeExtension takes a DER-encoded TBSCertificate, removes the extension 1161// specified by oid (preserving the order of other extensions), and returns the 1162// result still as a DER-encoded TBSCertificate. This function will fail if 1163// there is not exactly 1 extension of the type specified by the oid present. 1164func removeExtension(tbsData []byte, oid asn1.ObjectIdentifier) ([]byte, error) { 1165 var tbs tbsCertificate 1166 rest, err := asn1.Unmarshal(tbsData, &tbs) 1167 if err != nil { 1168 return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err) 1169 } else if rLen := len(rest); rLen > 0 { 1170 return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen) 1171 } 1172 extAt := -1 1173 for i, ext := range tbs.Extensions { 1174 if ext.Id.Equal(oid) { 1175 if extAt != -1 { 1176 return nil, errors.New("multiple extensions of specified type present") 1177 } 1178 extAt = i 1179 } 1180 } 1181 if extAt == -1 { 1182 return nil, errors.New("no extension of specified type present") 1183 } 1184 tbs.Extensions = append(tbs.Extensions[:extAt], tbs.Extensions[extAt+1:]...) 1185 // Clear out the asn1.RawContent so the re-marshal operation sees the 1186 // updated structure (rather than just copying the out-of-date DER data). 1187 tbs.Raw = nil 1188 1189 data, err := asn1.Marshal(tbs) 1190 if err != nil { 1191 return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err) 1192 } 1193 return data, nil 1194} 1195 1196// RemoveSCTList takes a DER-encoded TBSCertificate and removes the CT SCT 1197// extension that contains the SCT list (preserving the order of other 1198// extensions), and returns the result still as a DER-encoded TBSCertificate. 1199// This function will fail if there is not exactly 1 CT SCT extension present. 1200func RemoveSCTList(tbsData []byte) ([]byte, error) { 1201 return removeExtension(tbsData, OIDExtensionCTSCT) 1202} 1203 1204// RemoveCTPoison takes a DER-encoded TBSCertificate and removes the CT poison 1205// extension (preserving the order of other extensions), and returns the result 1206// still as a DER-encoded TBSCertificate. This function will fail if there is 1207// not exactly 1 CT poison extension present. 1208func RemoveCTPoison(tbsData []byte) ([]byte, error) { 1209 return BuildPrecertTBS(tbsData, nil) 1210} 1211 1212// BuildPrecertTBS builds a Certificate Transparency pre-certificate (RFC 6962 1213// s3.1) from the given DER-encoded TBSCertificate, returning a DER-encoded 1214// TBSCertificate. 1215// 1216// This function removes the CT poison extension (there must be exactly 1 of 1217// these), preserving the order of other extensions. 1218// 1219// If preIssuer is provided, this should be a special intermediate certificate 1220// that was used to sign the precert (indicated by having the special 1221// CertificateTransparency extended key usage). In this case, the issuance 1222// information of the pre-cert is updated to reflect the next issuer in the 1223// chain, i.e. the issuer of this special intermediate: 1224// - The precert's Issuer is changed to the Issuer of the intermediate 1225// - The precert's AuthorityKeyId is changed to the AuthorityKeyId of the 1226// intermediate. 1227func BuildPrecertTBS(tbsData []byte, preIssuer *Certificate) ([]byte, error) { 1228 data, err := removeExtension(tbsData, OIDExtensionCTPoison) 1229 if err != nil { 1230 return nil, err 1231 } 1232 1233 var tbs tbsCertificate 1234 rest, err := asn1.Unmarshal(data, &tbs) 1235 if err != nil { 1236 return nil, fmt.Errorf("failed to parse TBSCertificate: %v", err) 1237 } else if rLen := len(rest); rLen > 0 { 1238 return nil, fmt.Errorf("trailing data (%d bytes) after TBSCertificate", rLen) 1239 } 1240 1241 if preIssuer != nil { 1242 // Update the precert's Issuer field. Use the RawIssuer rather than the 1243 // parsed Issuer to avoid any chance of ASN.1 differences (e.g. switching 1244 // from UTF8String to PrintableString). 1245 tbs.Issuer.FullBytes = preIssuer.RawIssuer 1246 1247 // Also need to update the cert's AuthorityKeyID extension 1248 // to that of the preIssuer. 1249 var issuerKeyID []byte 1250 for _, ext := range preIssuer.Extensions { 1251 if ext.Id.Equal(OIDExtensionAuthorityKeyId) { 1252 issuerKeyID = ext.Value 1253 break 1254 } 1255 } 1256 1257 // Check the preIssuer has the CT EKU. 1258 seenCTEKU := false 1259 for _, eku := range preIssuer.ExtKeyUsage { 1260 if eku == ExtKeyUsageCertificateTransparency { 1261 seenCTEKU = true 1262 break 1263 } 1264 } 1265 if !seenCTEKU { 1266 return nil, fmt.Errorf("issuer does not have CertificateTransparency extended key usage") 1267 } 1268 1269 keyAt := -1 1270 for i, ext := range tbs.Extensions { 1271 if ext.Id.Equal(OIDExtensionAuthorityKeyId) { 1272 keyAt = i 1273 break 1274 } 1275 } 1276 if keyAt >= 0 { 1277 // PreCert has an auth-key-id; replace it with the value from the preIssuer 1278 if issuerKeyID != nil { 1279 tbs.Extensions[keyAt].Value = issuerKeyID 1280 } else { 1281 tbs.Extensions = append(tbs.Extensions[:keyAt], tbs.Extensions[keyAt+1:]...) 1282 } 1283 } else if issuerKeyID != nil { 1284 // PreCert did not have an auth-key-id, but the preIssuer does, so add it at the end. 1285 authKeyIDExt := pkix.Extension{ 1286 Id: OIDExtensionAuthorityKeyId, 1287 Critical: false, 1288 Value: issuerKeyID, 1289 } 1290 tbs.Extensions = append(tbs.Extensions, authKeyIDExt) 1291 } 1292 1293 // Clear out the asn1.RawContent so the re-marshal operation sees the 1294 // updated structure (rather than just copying the out-of-date DER data). 1295 tbs.Raw = nil 1296 } 1297 1298 data, err = asn1.Marshal(tbs) 1299 if err != nil { 1300 return nil, fmt.Errorf("failed to re-marshal TBSCertificate: %v", err) 1301 } 1302 return data, nil 1303} 1304 1305type basicConstraints struct { 1306 IsCA bool `asn1:"optional"` 1307 MaxPathLen int `asn1:"optional,default:-1"` 1308} 1309 1310// RFC 5280, 4.2.1.4 1311type policyInformation struct { 1312 Policy asn1.ObjectIdentifier 1313 // policyQualifiers omitted 1314} 1315 1316const ( 1317 nameTypeEmail = 1 1318 nameTypeDNS = 2 1319 nameTypeURI = 6 1320 nameTypeIP = 7 1321) 1322 1323// RFC 5280, 4.2.2.1 1324type accessDescription struct { 1325 Method asn1.ObjectIdentifier 1326 Location asn1.RawValue 1327} 1328 1329// RFC 5280, 4.2.1.14 1330type distributionPoint struct { 1331 DistributionPoint distributionPointName `asn1:"optional,tag:0"` 1332 Reason asn1.BitString `asn1:"optional,tag:1"` 1333 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` 1334} 1335 1336type distributionPointName struct { 1337 FullName []asn1.RawValue `asn1:"optional,tag:0"` 1338 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` 1339} 1340 1341func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo, nfe *NonFatalErrors) (interface{}, error) { 1342 asn1Data := keyData.PublicKey.RightAlign() 1343 switch algo { 1344 case RSA, RSAESOAEP: 1345 // RSA public keys must have a NULL in the parameters. 1346 // See RFC 3279, Section 2.3.1. 1347 if algo == RSA && !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) { 1348 nfe.AddError(errors.New("x509: RSA key missing NULL parameters")) 1349 } 1350 if algo == RSAESOAEP { 1351 // We only parse the parameters to ensure it is a valid encoding, we throw out the actual values 1352 paramsData := keyData.Algorithm.Parameters.FullBytes 1353 params := new(rsaesoaepAlgorithmParameters) 1354 params.HashFunc = sha1Identifier 1355 params.MaskgenFunc = mgf1SHA1Identifier 1356 params.PSourceFunc = pSpecifiedEmptyIdentifier 1357 rest, err := asn1.Unmarshal(paramsData, params) 1358 if err != nil { 1359 return nil, err 1360 } 1361 if len(rest) != 0 { 1362 return nil, errors.New("x509: trailing data after RSAES-OAEP parameters") 1363 } 1364 } 1365 1366 p := new(pkcs1PublicKey) 1367 rest, err := asn1.Unmarshal(asn1Data, p) 1368 if err != nil { 1369 var laxErr error 1370 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, p, "lax") 1371 if laxErr != nil { 1372 return nil, laxErr 1373 } 1374 nfe.AddError(err) 1375 } 1376 if len(rest) != 0 { 1377 return nil, errors.New("x509: trailing data after RSA public key") 1378 } 1379 1380 if p.N.Sign() <= 0 { 1381 nfe.AddError(errors.New("x509: RSA modulus is not a positive number")) 1382 } 1383 if p.E <= 0 { 1384 return nil, errors.New("x509: RSA public exponent is not a positive number") 1385 } 1386 1387 // TODO(dkarch): Update to return the parameters once crypto/x509 has come up with permanent solution (https://github.com/golang/go/issues/30416) 1388 pub := &rsa.PublicKey{ 1389 E: p.E, 1390 N: p.N, 1391 } 1392 return pub, nil 1393 case DSA: 1394 var p *big.Int 1395 rest, err := asn1.Unmarshal(asn1Data, &p) 1396 if err != nil { 1397 var laxErr error 1398 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &p, "lax") 1399 if laxErr != nil { 1400 return nil, laxErr 1401 } 1402 nfe.AddError(err) 1403 } 1404 if len(rest) != 0 { 1405 return nil, errors.New("x509: trailing data after DSA public key") 1406 } 1407 paramsData := keyData.Algorithm.Parameters.FullBytes 1408 params := new(dsaAlgorithmParameters) 1409 rest, err = asn1.Unmarshal(paramsData, params) 1410 if err != nil { 1411 return nil, err 1412 } 1413 if len(rest) != 0 { 1414 return nil, errors.New("x509: trailing data after DSA parameters") 1415 } 1416 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { 1417 return nil, errors.New("x509: zero or negative DSA parameter") 1418 } 1419 pub := &dsa.PublicKey{ 1420 Parameters: dsa.Parameters{ 1421 P: params.P, 1422 Q: params.Q, 1423 G: params.G, 1424 }, 1425 Y: p, 1426 } 1427 return pub, nil 1428 case ECDSA: 1429 paramsData := keyData.Algorithm.Parameters.FullBytes 1430 namedCurveOID := new(asn1.ObjectIdentifier) 1431 rest, err := asn1.Unmarshal(paramsData, namedCurveOID) 1432 if err != nil { 1433 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve") 1434 } 1435 if len(rest) != 0 { 1436 return nil, errors.New("x509: trailing data after ECDSA parameters") 1437 } 1438 namedCurve := namedCurveFromOID(*namedCurveOID, nfe) 1439 if namedCurve == nil { 1440 return nil, fmt.Errorf("x509: unsupported elliptic curve %v", namedCurveOID) 1441 } 1442 x, y := elliptic.Unmarshal(namedCurve, asn1Data) 1443 if x == nil { 1444 return nil, errors.New("x509: failed to unmarshal elliptic curve point") 1445 } 1446 pub := &ecdsa.PublicKey{ 1447 Curve: namedCurve, 1448 X: x, 1449 Y: y, 1450 } 1451 return pub, nil 1452 case Ed25519: 1453 return ed25519.PublicKey(asn1Data), nil 1454 default: 1455 return nil, nil 1456 } 1457} 1458 1459// NonFatalErrors is an error type which can hold a number of other errors. 1460// It's used to collect a range of non-fatal errors which occur while parsing 1461// a certificate, that way we can still match on certs which technically are 1462// invalid. 1463type NonFatalErrors struct { 1464 Errors []error 1465} 1466 1467// AddError adds an error to the list of errors contained by NonFatalErrors. 1468func (e *NonFatalErrors) AddError(err error) { 1469 e.Errors = append(e.Errors, err) 1470} 1471 1472// Returns a string consisting of the values of Error() from all of the errors 1473// contained in |e| 1474func (e NonFatalErrors) Error() string { 1475 r := "NonFatalErrors: " 1476 for _, err := range e.Errors { 1477 r += err.Error() + "; " 1478 } 1479 return r 1480} 1481 1482// HasError returns true if |e| contains at least one error 1483func (e *NonFatalErrors) HasError() bool { 1484 if e == nil { 1485 return false 1486 } 1487 return len(e.Errors) > 0 1488} 1489 1490// Append combines the contents of two NonFatalErrors instances. 1491func (e *NonFatalErrors) Append(more *NonFatalErrors) *NonFatalErrors { 1492 if e == nil { 1493 return more 1494 } 1495 if more == nil { 1496 return e 1497 } 1498 combined := NonFatalErrors{Errors: make([]error, 0, len(e.Errors)+len(more.Errors))} 1499 combined.Errors = append(combined.Errors, e.Errors...) 1500 combined.Errors = append(combined.Errors, more.Errors...) 1501 return &combined 1502} 1503 1504// IsFatal indicates whether an error is fatal. 1505func IsFatal(err error) bool { 1506 if err == nil { 1507 return false 1508 } 1509 if _, ok := err.(NonFatalErrors); ok { 1510 return false 1511 } 1512 if errs, ok := err.(*Errors); ok { 1513 return errs.Fatal() 1514 } 1515 return true 1516} 1517 1518func parseDistributionPoints(data []byte, crldp *[]string) error { 1519 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 1520 // 1521 // DistributionPoint ::= SEQUENCE { 1522 // distributionPoint [0] DistributionPointName OPTIONAL, 1523 // reasons [1] ReasonFlags OPTIONAL, 1524 // cRLIssuer [2] GeneralNames OPTIONAL } 1525 // 1526 // DistributionPointName ::= CHOICE { 1527 // fullName [0] GeneralNames, 1528 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 1529 1530 var cdp []distributionPoint 1531 if rest, err := asn1.Unmarshal(data, &cdp); err != nil { 1532 return err 1533 } else if len(rest) != 0 { 1534 return errors.New("x509: trailing data after X.509 CRL distribution point") 1535 } 1536 1537 for _, dp := range cdp { 1538 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty. 1539 if len(dp.DistributionPoint.FullName) == 0 { 1540 continue 1541 } 1542 1543 for _, fullName := range dp.DistributionPoint.FullName { 1544 if fullName.Tag == 6 { 1545 *crldp = append(*crldp, string(fullName.Bytes)) 1546 } 1547 } 1548 } 1549 return nil 1550} 1551 1552func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error { 1553 // RFC 5280, 4.2.1.6 1554 1555 // SubjectAltName ::= GeneralNames 1556 // 1557 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 1558 // 1559 // GeneralName ::= CHOICE { 1560 // otherName [0] OtherName, 1561 // rfc822Name [1] IA5String, 1562 // dNSName [2] IA5String, 1563 // x400Address [3] ORAddress, 1564 // directoryName [4] Name, 1565 // ediPartyName [5] EDIPartyName, 1566 // uniformResourceIdentifier [6] IA5String, 1567 // iPAddress [7] OCTET STRING, 1568 // registeredID [8] OBJECT IDENTIFIER } 1569 var seq asn1.RawValue 1570 rest, err := asn1.Unmarshal(extension, &seq) 1571 if err != nil { 1572 return err 1573 } else if len(rest) != 0 { 1574 return errors.New("x509: trailing data after X.509 extension") 1575 } 1576 if !seq.IsCompound || seq.Tag != asn1.TagSequence || seq.Class != asn1.ClassUniversal { 1577 return asn1.StructuralError{Msg: "bad SAN sequence"} 1578 } 1579 1580 rest = seq.Bytes 1581 for len(rest) > 0 { 1582 var v asn1.RawValue 1583 rest, err = asn1.Unmarshal(rest, &v) 1584 if err != nil { 1585 return err 1586 } 1587 1588 if err := callback(v.Tag, v.Bytes); err != nil { 1589 return err 1590 } 1591 } 1592 1593 return nil 1594} 1595 1596func parseSANExtension(value []byte, nfe *NonFatalErrors) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) { 1597 err = forEachSAN(value, func(tag int, data []byte) error { 1598 switch tag { 1599 case nameTypeEmail: 1600 emailAddresses = append(emailAddresses, string(data)) 1601 case nameTypeDNS: 1602 dnsNames = append(dnsNames, string(data)) 1603 case nameTypeURI: 1604 uri, err := url.Parse(string(data)) 1605 if err != nil { 1606 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err) 1607 } 1608 if len(uri.Host) > 0 { 1609 if _, ok := domainToReverseLabels(uri.Host); !ok { 1610 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data)) 1611 } 1612 } 1613 uris = append(uris, uri) 1614 case nameTypeIP: 1615 switch len(data) { 1616 case net.IPv4len, net.IPv6len: 1617 ipAddresses = append(ipAddresses, data) 1618 default: 1619 nfe.AddError(errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))) 1620 } 1621 } 1622 1623 return nil 1624 }) 1625 1626 return 1627} 1628 1629// isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits. 1630func isValidIPMask(mask []byte) bool { 1631 seenZero := false 1632 1633 for _, b := range mask { 1634 if seenZero { 1635 if b != 0 { 1636 return false 1637 } 1638 1639 continue 1640 } 1641 1642 switch b { 1643 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe: 1644 seenZero = true 1645 case 0xff: 1646 default: 1647 return false 1648 } 1649 } 1650 1651 return true 1652} 1653 1654func parseNameConstraintsExtension(out *Certificate, e pkix.Extension, nfe *NonFatalErrors) (unhandled bool, err error) { 1655 // RFC 5280, 4.2.1.10 1656 1657 // NameConstraints ::= SEQUENCE { 1658 // permittedSubtrees [0] GeneralSubtrees OPTIONAL, 1659 // excludedSubtrees [1] GeneralSubtrees OPTIONAL } 1660 // 1661 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree 1662 // 1663 // GeneralSubtree ::= SEQUENCE { 1664 // base GeneralName, 1665 // minimum [0] BaseDistance DEFAULT 0, 1666 // maximum [1] BaseDistance OPTIONAL } 1667 // 1668 // BaseDistance ::= INTEGER (0..MAX) 1669 1670 outer := cryptobyte.String(e.Value) 1671 var toplevel, permitted, excluded cryptobyte.String 1672 var havePermitted, haveExcluded bool 1673 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) || 1674 !outer.Empty() || 1675 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) || 1676 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) || 1677 !toplevel.Empty() { 1678 return false, errors.New("x509: invalid NameConstraints extension") 1679 } 1680 1681 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 { 1682 // From RFC 5280, Section 4.2.1.10: 1683 // “either the permittedSubtrees field 1684 // or the excludedSubtrees MUST be 1685 // present” 1686 return false, errors.New("x509: empty name constraints extension") 1687 } 1688 1689 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) { 1690 for !subtrees.Empty() { 1691 var seq, value cryptobyte.String 1692 var tag cryptobyte_asn1.Tag 1693 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) || 1694 !seq.ReadAnyASN1(&value, &tag) { 1695 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension") 1696 } 1697 1698 var ( 1699 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific() 1700 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific() 1701 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific() 1702 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific() 1703 ) 1704 1705 switch tag { 1706 case dnsTag: 1707 domain := string(value) 1708 if err := isIA5String(domain); err != nil { 1709 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 1710 } 1711 1712 trimmedDomain := domain 1713 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' { 1714 // constraints can have a leading 1715 // period to exclude the domain 1716 // itself, but that's not valid in a 1717 // normal domain name. 1718 trimmedDomain = trimmedDomain[1:] 1719 } 1720 if _, ok := domainToReverseLabels(trimmedDomain); !ok { 1721 nfe.AddError(fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)) 1722 } 1723 dnsNames = append(dnsNames, domain) 1724 1725 case ipTag: 1726 l := len(value) 1727 var ip, mask []byte 1728 1729 switch l { 1730 case 8: 1731 ip = value[:4] 1732 mask = value[4:] 1733 1734 case 32: 1735 ip = value[:16] 1736 mask = value[16:] 1737 1738 default: 1739 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l) 1740 } 1741 1742 if !isValidIPMask(mask) { 1743 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask) 1744 } 1745 1746 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)}) 1747 1748 case emailTag: 1749 constraint := string(value) 1750 if err := isIA5String(constraint); err != nil { 1751 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 1752 } 1753 1754 // If the constraint contains an @ then 1755 // it specifies an exact mailbox name. 1756 if strings.Contains(constraint, "@") { 1757 if _, ok := parseRFC2821Mailbox(constraint); !ok { 1758 nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)) 1759 } 1760 } else { 1761 // Otherwise it's a domain name. 1762 domain := constraint 1763 if len(domain) > 0 && domain[0] == '.' { 1764 domain = domain[1:] 1765 } 1766 if _, ok := domainToReverseLabels(domain); !ok { 1767 nfe.AddError(fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)) 1768 } 1769 } 1770 emails = append(emails, constraint) 1771 1772 case uriTag: 1773 domain := string(value) 1774 if err := isIA5String(domain); err != nil { 1775 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 1776 } 1777 1778 if net.ParseIP(domain) != nil { 1779 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain) 1780 } 1781 1782 trimmedDomain := domain 1783 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' { 1784 // constraints can have a leading 1785 // period to exclude the domain itself, 1786 // but that's not valid in a normal 1787 // domain name. 1788 trimmedDomain = trimmedDomain[1:] 1789 } 1790 if _, ok := domainToReverseLabels(trimmedDomain); !ok { 1791 nfe.AddError(fmt.Errorf("x509: failed to parse URI constraint %q", domain)) 1792 } 1793 uriDomains = append(uriDomains, domain) 1794 1795 default: 1796 unhandled = true 1797 } 1798 } 1799 1800 return dnsNames, ips, emails, uriDomains, nil 1801 } 1802 1803 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil { 1804 return false, err 1805 } 1806 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil { 1807 return false, err 1808 } 1809 out.PermittedDNSDomainsCritical = e.Critical 1810 1811 return unhandled, nil 1812} 1813 1814func parseCertificate(in *certificate) (*Certificate, error) { 1815 var nfe NonFatalErrors 1816 1817 out := new(Certificate) 1818 out.Raw = in.Raw 1819 out.RawTBSCertificate = in.TBSCertificate.Raw 1820 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw 1821 out.RawSubject = in.TBSCertificate.Subject.FullBytes 1822 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes 1823 1824 out.Signature = in.SignatureValue.RightAlign() 1825 out.SignatureAlgorithm = SignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm) 1826 1827 out.PublicKeyAlgorithm = 1828 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) 1829 var err error 1830 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey, &nfe) 1831 if err != nil { 1832 return nil, err 1833 } 1834 1835 out.Version = in.TBSCertificate.Version + 1 1836 out.SerialNumber = in.TBSCertificate.SerialNumber 1837 1838 var issuer, subject pkix.RDNSequence 1839 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { 1840 var laxErr error 1841 rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Subject.FullBytes, &subject, "lax") 1842 if laxErr != nil { 1843 return nil, laxErr 1844 } 1845 nfe.AddError(err) 1846 } else if len(rest) != 0 { 1847 return nil, errors.New("x509: trailing data after X.509 subject") 1848 } 1849 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { 1850 var laxErr error 1851 rest, laxErr = asn1.UnmarshalWithParams(in.TBSCertificate.Issuer.FullBytes, &issuer, "lax") 1852 if laxErr != nil { 1853 return nil, laxErr 1854 } 1855 nfe.AddError(err) 1856 } else if len(rest) != 0 { 1857 return nil, errors.New("x509: trailing data after X.509 subject") 1858 } 1859 1860 out.Issuer.FillFromRDNSequence(&issuer) 1861 out.Subject.FillFromRDNSequence(&subject) 1862 1863 out.NotBefore = in.TBSCertificate.Validity.NotBefore 1864 out.NotAfter = in.TBSCertificate.Validity.NotAfter 1865 1866 for _, e := range in.TBSCertificate.Extensions { 1867 out.Extensions = append(out.Extensions, e) 1868 unhandled := false 1869 1870 if len(e.Id) == 4 && e.Id[0] == OIDExtensionArc[0] && e.Id[1] == OIDExtensionArc[1] && e.Id[2] == OIDExtensionArc[2] { 1871 switch e.Id[3] { 1872 case OIDExtensionKeyUsage[3]: 1873 // RFC 5280, 4.2.1.3 1874 var usageBits asn1.BitString 1875 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil { 1876 return nil, err 1877 } else if len(rest) != 0 { 1878 return nil, errors.New("x509: trailing data after X.509 KeyUsage") 1879 } 1880 1881 var usage int 1882 for i := 0; i < 9; i++ { 1883 if usageBits.At(i) != 0 { 1884 usage |= 1 << uint(i) 1885 } 1886 } 1887 out.KeyUsage = KeyUsage(usage) 1888 1889 case OIDExtensionBasicConstraints[3]: 1890 // RFC 5280, 4.2.1.9 1891 var constraints basicConstraints 1892 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil { 1893 return nil, err 1894 } else if len(rest) != 0 { 1895 return nil, errors.New("x509: trailing data after X.509 BasicConstraints") 1896 } 1897 1898 out.BasicConstraintsValid = true 1899 out.IsCA = constraints.IsCA 1900 out.MaxPathLen = constraints.MaxPathLen 1901 out.MaxPathLenZero = out.MaxPathLen == 0 1902 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285) 1903 1904 case OIDExtensionSubjectAltName[3]: 1905 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value, &nfe) 1906 if err != nil { 1907 return nil, err 1908 } 1909 1910 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 { 1911 // If we didn't parse anything then we do the critical check, below. 1912 unhandled = true 1913 } 1914 1915 case OIDExtensionNameConstraints[3]: 1916 unhandled, err = parseNameConstraintsExtension(out, e, &nfe) 1917 if err != nil { 1918 return nil, err 1919 } 1920 1921 case OIDExtensionCRLDistributionPoints[3]: 1922 // RFC 5280, 4.2.1.13 1923 if err := parseDistributionPoints(e.Value, &out.CRLDistributionPoints); err != nil { 1924 return nil, err 1925 } 1926 1927 case OIDExtensionAuthorityKeyId[3]: 1928 // RFC 5280, 4.2.1.1 1929 var a authKeyId 1930 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil { 1931 return nil, err 1932 } else if len(rest) != 0 { 1933 return nil, errors.New("x509: trailing data after X.509 authority key-id") 1934 } 1935 out.AuthorityKeyId = a.Id 1936 1937 case OIDExtensionExtendedKeyUsage[3]: 1938 // RFC 5280, 4.2.1.12. Extended Key Usage 1939 1940 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } 1941 // 1942 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId 1943 // 1944 // KeyPurposeId ::= OBJECT IDENTIFIER 1945 1946 var keyUsage []asn1.ObjectIdentifier 1947 if len(e.Value) == 0 { 1948 nfe.AddError(errors.New("x509: empty ExtendedKeyUsage")) 1949 } else { 1950 rest, err := asn1.Unmarshal(e.Value, &keyUsage) 1951 if err != nil { 1952 var laxErr error 1953 rest, laxErr = asn1.UnmarshalWithParams(e.Value, &keyUsage, "lax") 1954 if laxErr != nil { 1955 return nil, laxErr 1956 } 1957 nfe.AddError(err) 1958 } 1959 if len(rest) != 0 { 1960 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage") 1961 } 1962 } 1963 1964 for _, u := range keyUsage { 1965 if extKeyUsage, ok := extKeyUsageFromOID(u); ok { 1966 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) 1967 } else { 1968 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) 1969 } 1970 } 1971 1972 case OIDExtensionSubjectKeyId[3]: 1973 // RFC 5280, 4.2.1.2 1974 var keyid []byte 1975 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil { 1976 return nil, err 1977 } else if len(rest) != 0 { 1978 return nil, errors.New("x509: trailing data after X.509 key-id") 1979 } 1980 out.SubjectKeyId = keyid 1981 1982 case OIDExtensionCertificatePolicies[3]: 1983 // RFC 5280 4.2.1.4: Certificate Policies 1984 var policies []policyInformation 1985 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil { 1986 return nil, err 1987 } else if len(rest) != 0 { 1988 return nil, errors.New("x509: trailing data after X.509 certificate policies") 1989 } 1990 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) 1991 for i, policy := range policies { 1992 out.PolicyIdentifiers[i] = policy.Policy 1993 } 1994 1995 default: 1996 // Unknown extensions are recorded if critical. 1997 unhandled = true 1998 } 1999 } else if e.Id.Equal(OIDExtensionAuthorityInfoAccess) { 2000 // RFC 5280 4.2.2.1: Authority Information Access 2001 var aia []accessDescription 2002 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil { 2003 return nil, err 2004 } else if len(rest) != 0 { 2005 return nil, errors.New("x509: trailing data after X.509 authority information") 2006 } 2007 if len(aia) == 0 { 2008 nfe.AddError(errors.New("x509: empty AuthorityInfoAccess extension")) 2009 } 2010 2011 for _, v := range aia { 2012 // GeneralName: uniformResourceIdentifier [6] IA5String 2013 if v.Location.Tag != 6 { 2014 continue 2015 } 2016 if v.Method.Equal(OIDAuthorityInfoAccessOCSP) { 2017 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) 2018 } else if v.Method.Equal(OIDAuthorityInfoAccessIssuers) { 2019 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) 2020 } 2021 } 2022 } else if e.Id.Equal(OIDExtensionSubjectInfoAccess) { 2023 // RFC 5280 4.2.2.2: Subject Information Access 2024 var sia []accessDescription 2025 if rest, err := asn1.Unmarshal(e.Value, &sia); err != nil { 2026 return nil, err 2027 } else if len(rest) != 0 { 2028 return nil, errors.New("x509: trailing data after X.509 subject information") 2029 } 2030 if len(sia) == 0 { 2031 nfe.AddError(errors.New("x509: empty SubjectInfoAccess extension")) 2032 } 2033 2034 for _, v := range sia { 2035 // TODO(drysdale): cope with non-URI types of GeneralName 2036 // GeneralName: uniformResourceIdentifier [6] IA5String 2037 if v.Location.Tag != 6 { 2038 continue 2039 } 2040 if v.Method.Equal(OIDSubjectInfoAccessTimestamp) { 2041 out.SubjectTimestamps = append(out.SubjectTimestamps, string(v.Location.Bytes)) 2042 } else if v.Method.Equal(OIDSubjectInfoAccessCARepo) { 2043 out.SubjectCARepositories = append(out.SubjectCARepositories, string(v.Location.Bytes)) 2044 } 2045 } 2046 } else if e.Id.Equal(OIDExtensionIPPrefixList) { 2047 out.RPKIAddressRanges = parseRPKIAddrBlocks(e.Value, &nfe) 2048 } else if e.Id.Equal(OIDExtensionASList) { 2049 out.RPKIASNumbers, out.RPKIRoutingDomainIDs = parseRPKIASIdentifiers(e.Value, &nfe) 2050 } else if e.Id.Equal(OIDExtensionCTSCT) { 2051 if rest, err := asn1.Unmarshal(e.Value, &out.RawSCT); err != nil { 2052 nfe.AddError(fmt.Errorf("failed to asn1.Unmarshal SCT list extension: %v", err)) 2053 } else if len(rest) != 0 { 2054 nfe.AddError(errors.New("trailing data after ASN1-encoded SCT list")) 2055 } else { 2056 if rest, err := tls.Unmarshal(out.RawSCT, &out.SCTList); err != nil { 2057 nfe.AddError(fmt.Errorf("failed to tls.Unmarshal SCT list: %v", err)) 2058 } else if len(rest) != 0 { 2059 nfe.AddError(errors.New("trailing data after TLS-encoded SCT list")) 2060 } 2061 } 2062 } else { 2063 // Unknown extensions are recorded if critical. 2064 unhandled = true 2065 } 2066 2067 if e.Critical && unhandled { 2068 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id) 2069 } 2070 } 2071 if nfe.HasError() { 2072 return out, nfe 2073 } 2074 return out, nil 2075} 2076 2077// ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data. 2078// The parsed data is returned in a Certificate struct for ease of access. 2079func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) { 2080 var tbsCert tbsCertificate 2081 var nfe NonFatalErrors 2082 rest, err := asn1.Unmarshal(asn1Data, &tbsCert) 2083 if err != nil { 2084 var laxErr error 2085 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &tbsCert, "lax") 2086 if laxErr != nil { 2087 return nil, laxErr 2088 } 2089 nfe.AddError(err) 2090 } 2091 if len(rest) > 0 { 2092 return nil, asn1.SyntaxError{Msg: "trailing data"} 2093 } 2094 ret, err := parseCertificate(&certificate{ 2095 Raw: tbsCert.Raw, 2096 TBSCertificate: tbsCert}) 2097 if err != nil { 2098 errs, ok := err.(NonFatalErrors) 2099 if !ok { 2100 return nil, err 2101 } 2102 nfe.Errors = append(nfe.Errors, errs.Errors...) 2103 } 2104 if nfe.HasError() { 2105 return ret, nfe 2106 } 2107 return ret, nil 2108} 2109 2110// ParseCertificate parses a single certificate from the given ASN.1 DER data. 2111// This function can return both a Certificate and an error (in which case the 2112// error will be of type NonFatalErrors). 2113func ParseCertificate(asn1Data []byte) (*Certificate, error) { 2114 var cert certificate 2115 var nfe NonFatalErrors 2116 rest, err := asn1.Unmarshal(asn1Data, &cert) 2117 if err != nil { 2118 var laxErr error 2119 rest, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax") 2120 if laxErr != nil { 2121 return nil, laxErr 2122 } 2123 nfe.AddError(err) 2124 } 2125 if len(rest) > 0 { 2126 return nil, asn1.SyntaxError{Msg: "trailing data"} 2127 } 2128 ret, err := parseCertificate(&cert) 2129 if err != nil { 2130 errs, ok := err.(NonFatalErrors) 2131 if !ok { 2132 return nil, err 2133 } 2134 nfe.Errors = append(nfe.Errors, errs.Errors...) 2135 } 2136 if nfe.HasError() { 2137 return ret, nfe 2138 } 2139 return ret, nil 2140} 2141 2142// ParseCertificates parses one or more certificates from the given ASN.1 DER 2143// data. The certificates must be concatenated with no intermediate padding. 2144// This function can return both a slice of Certificate and an error (in which 2145// case the error will be of type NonFatalErrors). 2146func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { 2147 var v []*certificate 2148 var nfe NonFatalErrors 2149 2150 for len(asn1Data) > 0 { 2151 cert := new(certificate) 2152 var err error 2153 asn1Data, err = asn1.Unmarshal(asn1Data, cert) 2154 if err != nil { 2155 var laxErr error 2156 asn1Data, laxErr = asn1.UnmarshalWithParams(asn1Data, &cert, "lax") 2157 if laxErr != nil { 2158 return nil, laxErr 2159 } 2160 nfe.AddError(err) 2161 } 2162 v = append(v, cert) 2163 } 2164 2165 ret := make([]*Certificate, len(v)) 2166 for i, ci := range v { 2167 cert, err := parseCertificate(ci) 2168 if err != nil { 2169 errs, ok := err.(NonFatalErrors) 2170 if !ok { 2171 return nil, err 2172 } 2173 nfe.Errors = append(nfe.Errors, errs.Errors...) 2174 } 2175 ret[i] = cert 2176 } 2177 2178 if nfe.HasError() { 2179 return ret, nfe 2180 } 2181 return ret, nil 2182} 2183 2184func reverseBitsInAByte(in byte) byte { 2185 b1 := in>>4 | in<<4 2186 b2 := b1>>2&0x33 | b1<<2&0xcc 2187 b3 := b2>>1&0x55 | b2<<1&0xaa 2188 return b3 2189} 2190 2191// asn1BitLength returns the bit-length of bitString by considering the 2192// most-significant bit in a byte to be the "first" bit. This convention 2193// matches ASN.1, but differs from almost everything else. 2194func asn1BitLength(bitString []byte) int { 2195 bitLen := len(bitString) * 8 2196 2197 for i := range bitString { 2198 b := bitString[len(bitString)-i-1] 2199 2200 for bit := uint(0); bit < 8; bit++ { 2201 if (b>>bit)&1 == 1 { 2202 return bitLen 2203 } 2204 bitLen-- 2205 } 2206 } 2207 2208 return 0 2209} 2210 2211// OID values for standard extensions from RFC 5280. 2212var ( 2213 OIDExtensionArc = asn1.ObjectIdentifier{2, 5, 29} // id-ce RFC5280 s4.2.1 2214 OIDExtensionSubjectKeyId = asn1.ObjectIdentifier{2, 5, 29, 14} 2215 OIDExtensionKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 15} 2216 OIDExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37} 2217 OIDExtensionAuthorityKeyId = asn1.ObjectIdentifier{2, 5, 29, 35} 2218 OIDExtensionBasicConstraints = asn1.ObjectIdentifier{2, 5, 29, 19} 2219 OIDExtensionSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17} 2220 OIDExtensionCertificatePolicies = asn1.ObjectIdentifier{2, 5, 29, 32} 2221 OIDExtensionNameConstraints = asn1.ObjectIdentifier{2, 5, 29, 30} 2222 OIDExtensionCRLDistributionPoints = asn1.ObjectIdentifier{2, 5, 29, 31} 2223 OIDExtensionIssuerAltName = asn1.ObjectIdentifier{2, 5, 29, 18} 2224 OIDExtensionSubjectDirectoryAttributes = asn1.ObjectIdentifier{2, 5, 29, 9} 2225 OIDExtensionInhibitAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 54} 2226 OIDExtensionPolicyConstraints = asn1.ObjectIdentifier{2, 5, 29, 36} 2227 OIDExtensionPolicyMappings = asn1.ObjectIdentifier{2, 5, 29, 33} 2228 OIDExtensionFreshestCRL = asn1.ObjectIdentifier{2, 5, 29, 46} 2229 2230 OIDExtensionAuthorityInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1} 2231 OIDExtensionSubjectInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 11} 2232 2233 // OIDExtensionCTPoison is defined in RFC 6962 s3.1. 2234 OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3} 2235 // OIDExtensionCTSCT is defined in RFC 6962 s3.3. 2236 OIDExtensionCTSCT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2} 2237 // OIDExtensionIPPrefixList is defined in RFC 3779 s2. 2238 OIDExtensionIPPrefixList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 7} 2239 // OIDExtensionASList is defined in RFC 3779 s3. 2240 OIDExtensionASList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 8} 2241) 2242 2243var ( 2244 OIDAuthorityInfoAccessOCSP = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 2245 OIDAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 2246 OIDSubjectInfoAccessTimestamp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 3} 2247 OIDSubjectInfoAccessCARepo = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 5} 2248 OIDAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 32, 0} 2249) 2250 2251// oidInExtensions reports whether an extension with the given oid exists in 2252// extensions. 2253func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 2254 for _, e := range extensions { 2255 if e.Id.Equal(oid) { 2256 return true 2257 } 2258 } 2259 return false 2260} 2261 2262// marshalSANs marshals a list of addresses into a the contents of an X.509 2263// SubjectAlternativeName extension. 2264func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) { 2265 var rawValues []asn1.RawValue 2266 for _, name := range dnsNames { 2267 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: asn1.ClassContextSpecific, Bytes: []byte(name)}) 2268 } 2269 for _, email := range emailAddresses { 2270 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: asn1.ClassContextSpecific, Bytes: []byte(email)}) 2271 } 2272 for _, rawIP := range ipAddresses { 2273 // If possible, we always want to encode IPv4 addresses in 4 bytes. 2274 ip := rawIP.To4() 2275 if ip == nil { 2276 ip = rawIP 2277 } 2278 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: asn1.ClassContextSpecific, Bytes: ip}) 2279 } 2280 for _, uri := range uris { 2281 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: asn1.ClassContextSpecific, Bytes: []byte(uri.String())}) 2282 } 2283 return asn1.Marshal(rawValues) 2284} 2285 2286func isIA5String(s string) error { 2287 for _, r := range s { 2288 if r >= utf8.RuneSelf { 2289 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s) 2290 } 2291 } 2292 2293 return nil 2294} 2295 2296func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte) (ret []pkix.Extension, err error) { 2297 ret = make([]pkix.Extension, 12 /* maximum number of elements. */) 2298 n := 0 2299 2300 if template.KeyUsage != 0 && 2301 !oidInExtensions(OIDExtensionKeyUsage, template.ExtraExtensions) { 2302 ret[n].Id = OIDExtensionKeyUsage 2303 ret[n].Critical = true 2304 2305 var a [2]byte 2306 a[0] = reverseBitsInAByte(byte(template.KeyUsage)) 2307 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) 2308 2309 l := 1 2310 if a[1] != 0 { 2311 l = 2 2312 } 2313 2314 bitString := a[:l] 2315 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)}) 2316 if err != nil { 2317 return 2318 } 2319 n++ 2320 } 2321 2322 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 2323 !oidInExtensions(OIDExtensionExtendedKeyUsage, template.ExtraExtensions) { 2324 ret[n].Id = OIDExtensionExtendedKeyUsage 2325 2326 var oids []asn1.ObjectIdentifier 2327 for _, u := range template.ExtKeyUsage { 2328 if oid, ok := oidFromExtKeyUsage(u); ok { 2329 oids = append(oids, oid) 2330 } else { 2331 panic("internal error") 2332 } 2333 } 2334 2335 oids = append(oids, template.UnknownExtKeyUsage...) 2336 2337 ret[n].Value, err = asn1.Marshal(oids) 2338 if err != nil { 2339 return 2340 } 2341 n++ 2342 } 2343 2344 if template.BasicConstraintsValid && !oidInExtensions(OIDExtensionBasicConstraints, template.ExtraExtensions) { 2345 // Leaving MaxPathLen as zero indicates that no maximum path 2346 // length is desired, unless MaxPathLenZero is set. A value of 2347 // -1 causes encoding/asn1 to omit the value as desired. 2348 maxPathLen := template.MaxPathLen 2349 if maxPathLen == 0 && !template.MaxPathLenZero { 2350 maxPathLen = -1 2351 } 2352 ret[n].Id = OIDExtensionBasicConstraints 2353 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen}) 2354 ret[n].Critical = true 2355 if err != nil { 2356 return 2357 } 2358 n++ 2359 } 2360 2361 if len(template.SubjectKeyId) > 0 && !oidInExtensions(OIDExtensionSubjectKeyId, template.ExtraExtensions) { 2362 ret[n].Id = OIDExtensionSubjectKeyId 2363 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) 2364 if err != nil { 2365 return 2366 } 2367 n++ 2368 } 2369 2370 if len(authorityKeyId) > 0 && !oidInExtensions(OIDExtensionAuthorityKeyId, template.ExtraExtensions) { 2371 ret[n].Id = OIDExtensionAuthorityKeyId 2372 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId}) 2373 if err != nil { 2374 return 2375 } 2376 n++ 2377 } 2378 2379 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 2380 !oidInExtensions(OIDExtensionAuthorityInfoAccess, template.ExtraExtensions) { 2381 ret[n].Id = OIDExtensionAuthorityInfoAccess 2382 var aiaValues []accessDescription 2383 for _, name := range template.OCSPServer { 2384 aiaValues = append(aiaValues, accessDescription{ 2385 Method: OIDAuthorityInfoAccessOCSP, 2386 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)}, 2387 }) 2388 } 2389 for _, name := range template.IssuingCertificateURL { 2390 aiaValues = append(aiaValues, accessDescription{ 2391 Method: OIDAuthorityInfoAccessIssuers, 2392 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)}, 2393 }) 2394 } 2395 ret[n].Value, err = asn1.Marshal(aiaValues) 2396 if err != nil { 2397 return 2398 } 2399 n++ 2400 } 2401 2402 if len(template.SubjectTimestamps) > 0 || len(template.SubjectCARepositories) > 0 && 2403 !oidInExtensions(OIDExtensionSubjectInfoAccess, template.ExtraExtensions) { 2404 ret[n].Id = OIDExtensionSubjectInfoAccess 2405 var siaValues []accessDescription 2406 for _, ts := range template.SubjectTimestamps { 2407 siaValues = append(siaValues, accessDescription{ 2408 Method: OIDSubjectInfoAccessTimestamp, 2409 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(ts)}, 2410 }) 2411 } 2412 for _, repo := range template.SubjectCARepositories { 2413 siaValues = append(siaValues, accessDescription{ 2414 Method: OIDSubjectInfoAccessCARepo, 2415 Location: asn1.RawValue{Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(repo)}, 2416 }) 2417 } 2418 ret[n].Value, err = asn1.Marshal(siaValues) 2419 if err != nil { 2420 return 2421 } 2422 n++ 2423 } 2424 2425 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) && 2426 !oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) { 2427 ret[n].Id = OIDExtensionSubjectAltName 2428 // From RFC 5280, Section 4.2.1.6: 2429 // “If the subject field contains an empty sequence ... then 2430 // subjectAltName extension ... is marked as critical” 2431 ret[n].Critical = subjectIsEmpty 2432 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs) 2433 if err != nil { 2434 return 2435 } 2436 n++ 2437 } 2438 2439 if len(template.PolicyIdentifiers) > 0 && 2440 !oidInExtensions(OIDExtensionCertificatePolicies, template.ExtraExtensions) { 2441 ret[n].Id = OIDExtensionCertificatePolicies 2442 policies := make([]policyInformation, len(template.PolicyIdentifiers)) 2443 for i, policy := range template.PolicyIdentifiers { 2444 policies[i].Policy = policy 2445 } 2446 ret[n].Value, err = asn1.Marshal(policies) 2447 if err != nil { 2448 return 2449 } 2450 n++ 2451 } 2452 2453 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 || 2454 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 || 2455 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 || 2456 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) && 2457 !oidInExtensions(OIDExtensionNameConstraints, template.ExtraExtensions) { 2458 ret[n].Id = OIDExtensionNameConstraints 2459 ret[n].Critical = template.PermittedDNSDomainsCritical 2460 2461 ipAndMask := func(ipNet *net.IPNet) []byte { 2462 maskedIP := ipNet.IP.Mask(ipNet.Mask) 2463 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask)) 2464 ipAndMask = append(ipAndMask, maskedIP...) 2465 ipAndMask = append(ipAndMask, ipNet.Mask...) 2466 return ipAndMask 2467 } 2468 2469 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) { 2470 var b cryptobyte.Builder 2471 2472 for _, name := range dns { 2473 if err = isIA5String(name); err != nil { 2474 return nil, err 2475 } 2476 2477 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 2478 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) { 2479 b.AddBytes([]byte(name)) 2480 }) 2481 }) 2482 } 2483 2484 for _, ipNet := range ips { 2485 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 2486 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) { 2487 b.AddBytes(ipAndMask(ipNet)) 2488 }) 2489 }) 2490 } 2491 2492 for _, email := range emails { 2493 if err = isIA5String(email); err != nil { 2494 return nil, err 2495 } 2496 2497 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 2498 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) { 2499 b.AddBytes([]byte(email)) 2500 }) 2501 }) 2502 } 2503 2504 for _, uriDomain := range uriDomains { 2505 if err = isIA5String(uriDomain); err != nil { 2506 return nil, err 2507 } 2508 2509 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 2510 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) { 2511 b.AddBytes([]byte(uriDomain)) 2512 }) 2513 }) 2514 } 2515 2516 return b.Bytes() 2517 } 2518 2519 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains) 2520 if err != nil { 2521 return nil, err 2522 } 2523 2524 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains) 2525 if err != nil { 2526 return nil, err 2527 } 2528 2529 var b cryptobyte.Builder 2530 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 2531 if len(permitted) > 0 { 2532 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { 2533 b.AddBytes(permitted) 2534 }) 2535 } 2536 2537 if len(excluded) > 0 { 2538 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { 2539 b.AddBytes(excluded) 2540 }) 2541 } 2542 }) 2543 2544 ret[n].Value, err = b.Bytes() 2545 if err != nil { 2546 return nil, err 2547 } 2548 n++ 2549 } 2550 2551 if len(template.CRLDistributionPoints) > 0 && 2552 !oidInExtensions(OIDExtensionCRLDistributionPoints, template.ExtraExtensions) { 2553 ret[n].Id = OIDExtensionCRLDistributionPoints 2554 2555 var crlDp []distributionPoint 2556 for _, name := range template.CRLDistributionPoints { 2557 dp := distributionPoint{ 2558 DistributionPoint: distributionPointName{ 2559 FullName: []asn1.RawValue{ 2560 {Tag: 6, Class: asn1.ClassContextSpecific, Bytes: []byte(name)}, 2561 }, 2562 }, 2563 } 2564 crlDp = append(crlDp, dp) 2565 } 2566 2567 ret[n].Value, err = asn1.Marshal(crlDp) 2568 if err != nil { 2569 return 2570 } 2571 n++ 2572 } 2573 2574 if (len(template.RawSCT) > 0 || len(template.SCTList.SCTList) > 0) && !oidInExtensions(OIDExtensionCTSCT, template.ExtraExtensions) { 2575 rawSCT := template.RawSCT 2576 if len(template.SCTList.SCTList) > 0 { 2577 rawSCT, err = tls.Marshal(template.SCTList) 2578 if err != nil { 2579 return 2580 } 2581 } 2582 ret[n].Id = OIDExtensionCTSCT 2583 ret[n].Value, err = asn1.Marshal(rawSCT) 2584 if err != nil { 2585 return 2586 } 2587 n++ 2588 } 2589 2590 // Adding another extension here? Remember to update the maximum number 2591 // of elements in the make() at the top of the function and the list of 2592 // template fields used in CreateCertificate documentation. 2593 2594 return append(ret[:n], template.ExtraExtensions...), nil 2595} 2596 2597func subjectBytes(cert *Certificate) ([]byte, error) { 2598 if len(cert.RawSubject) > 0 { 2599 return cert.RawSubject, nil 2600 } 2601 2602 return asn1.Marshal(cert.Subject.ToRDNSequence()) 2603} 2604 2605// signingParamsForPublicKey returns the parameters to use for signing with 2606// priv. If requestedSigAlgo is not zero then it overrides the default 2607// signature algorithm. 2608func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { 2609 var pubType PublicKeyAlgorithm 2610 2611 switch pub := pub.(type) { 2612 case *rsa.PublicKey: 2613 pubType = RSA 2614 hashFunc = crypto.SHA256 2615 sigAlgo.Algorithm = oidSignatureSHA256WithRSA 2616 sigAlgo.Parameters = asn1.NullRawValue 2617 2618 case *ecdsa.PublicKey: 2619 pubType = ECDSA 2620 2621 switch pub.Curve { 2622 case elliptic.P224(), elliptic.P256(): 2623 hashFunc = crypto.SHA256 2624 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 2625 case elliptic.P384(): 2626 hashFunc = crypto.SHA384 2627 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 2628 case elliptic.P521(): 2629 hashFunc = crypto.SHA512 2630 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 2631 default: 2632 err = errors.New("x509: unknown elliptic curve") 2633 } 2634 2635 case ed25519.PublicKey: 2636 pubType = Ed25519 2637 sigAlgo.Algorithm = oidSignatureEd25519 2638 2639 default: 2640 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported") 2641 } 2642 2643 if err != nil { 2644 return 2645 } 2646 2647 if requestedSigAlgo == 0 { 2648 return 2649 } 2650 2651 found := false 2652 for _, details := range signatureAlgorithmDetails { 2653 if details.algo == requestedSigAlgo { 2654 if details.pubKeyAlgo != pubType { 2655 err = errors.New("x509: requested SignatureAlgorithm does not match private key type") 2656 return 2657 } 2658 sigAlgo.Algorithm, hashFunc = details.oid, details.hash 2659 if hashFunc == 0 && pubType != Ed25519 { 2660 err = errors.New("x509: cannot sign with hash function requested") 2661 return 2662 } 2663 if requestedSigAlgo.isRSAPSS() { 2664 sigAlgo.Parameters = rsaPSSParameters(hashFunc) 2665 } 2666 found = true 2667 break 2668 } 2669 } 2670 2671 if !found { 2672 err = errors.New("x509: unknown SignatureAlgorithm") 2673 } 2674 2675 return 2676} 2677 2678// emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is 2679// just an empty SEQUENCE. 2680var emptyASN1Subject = []byte{0x30, 0} 2681 2682// CreateCertificate creates a new X.509v3 certificate based on a template. 2683// The following members of template are used: 2684// - SerialNumber 2685// - Subject 2686// - NotBefore, NotAfter 2687// - SignatureAlgorithm 2688// - For extensions: 2689// - KeyUsage 2690// - ExtKeyUsage, UnknownExtKeyUsage 2691// - BasicConstraintsValid, IsCA, MaxPathLen, MaxPathLenZero 2692// - SubjectKeyId 2693// - AuthorityKeyId 2694// - OCSPServer, IssuingCertificateURL 2695// - SubjectTimestamps, SubjectCARepositories 2696// - DNSNames, EmailAddresses, IPAddresses, URIs 2697// - PolicyIdentifiers 2698// - ExcludedDNSDomains, ExcludedIPRanges, ExcludedEmailAddresses, ExcludedURIDomains, PermittedDNSDomainsCritical, 2699// PermittedDNSDomains, PermittedIPRanges, PermittedEmailAddresses, PermittedURIDomains 2700// - CRLDistributionPoints 2701// - RawSCT, SCTList 2702// - ExtraExtensions 2703// 2704// The certificate is signed by parent. If parent is equal to template then the 2705// certificate is self-signed. The parameter pub is the public key of the 2706// signee and priv is the private key of the signer. 2707// 2708// The returned slice is the certificate in DER encoding. 2709// 2710// The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and 2711// ed25519.PublicKey. pub must be a supported key type, and priv must be a 2712// crypto.Signer with a supported public key. 2713// 2714// The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, 2715// unless the resulting certificate is self-signed. Otherwise the value from 2716// template will be used. 2717func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) { 2718 key, ok := priv.(crypto.Signer) 2719 if !ok { 2720 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2721 } 2722 2723 if template.SerialNumber == nil { 2724 return nil, errors.New("x509: no SerialNumber given") 2725 } 2726 2727 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 2728 if err != nil { 2729 return nil, err 2730 } 2731 2732 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub) 2733 if err != nil { 2734 return nil, err 2735 } 2736 2737 asn1Issuer, err := subjectBytes(parent) 2738 if err != nil { 2739 return 2740 } 2741 2742 asn1Subject, err := subjectBytes(template) 2743 if err != nil { 2744 return 2745 } 2746 2747 authorityKeyId := template.AuthorityKeyId 2748 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 { 2749 authorityKeyId = parent.SubjectKeyId 2750 } 2751 2752 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId) 2753 if err != nil { 2754 return 2755 } 2756 2757 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 2758 c := tbsCertificate{ 2759 Version: 2, 2760 SerialNumber: template.SerialNumber, 2761 SignatureAlgorithm: signatureAlgorithm, 2762 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 2763 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 2764 Subject: asn1.RawValue{FullBytes: asn1Subject}, 2765 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 2766 Extensions: extensions, 2767 } 2768 2769 tbsCertContents, err := asn1.Marshal(c) 2770 if err != nil { 2771 return 2772 } 2773 c.Raw = tbsCertContents 2774 2775 signed := tbsCertContents 2776 if hashFunc != 0 { 2777 h := hashFunc.New() 2778 h.Write(signed) 2779 signed = h.Sum(nil) 2780 } 2781 2782 var signerOpts crypto.SignerOpts = hashFunc 2783 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() { 2784 signerOpts = &rsa.PSSOptions{ 2785 SaltLength: rsa.PSSSaltLengthEqualsHash, 2786 Hash: hashFunc, 2787 } 2788 } 2789 2790 var signature []byte 2791 signature, err = key.Sign(rand, signed, signerOpts) 2792 if err != nil { 2793 return 2794 } 2795 2796 return asn1.Marshal(certificate{ 2797 nil, 2798 c, 2799 signatureAlgorithm, 2800 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2801 }) 2802} 2803 2804// pemCRLPrefix is the magic string that indicates that we have a PEM encoded 2805// CRL. 2806var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 2807 2808// pemType is the type of a PEM encoded CRL. 2809var pemType = "X509 CRL" 2810 2811// ParseCRL parses a CRL from the given bytes. It's often the case that PEM 2812// encoded CRLs will appear where they should be DER encoded, so this function 2813// will transparently handle PEM encoding as long as there isn't any leading 2814// garbage. 2815func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) { 2816 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 2817 block, _ := pem.Decode(crlBytes) 2818 if block != nil && block.Type == pemType { 2819 crlBytes = block.Bytes 2820 } 2821 } 2822 return ParseDERCRL(crlBytes) 2823} 2824 2825// ParseDERCRL parses a DER encoded CRL from the given bytes. 2826func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { 2827 certList := new(pkix.CertificateList) 2828 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil { 2829 return nil, err 2830 } else if len(rest) != 0 { 2831 return nil, errors.New("x509: trailing data after CRL") 2832 } 2833 return certList, nil 2834} 2835 2836// CreateCRL returns a DER encoded CRL, signed by this Certificate, that 2837// contains the given list of revoked certificates. 2838func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 2839 key, ok := priv.(crypto.Signer) 2840 if !ok { 2841 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2842 } 2843 2844 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) 2845 if err != nil { 2846 return nil, err 2847 } 2848 2849 // Force revocation times to UTC per RFC 5280. 2850 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts)) 2851 for i, rc := range revokedCerts { 2852 rc.RevocationTime = rc.RevocationTime.UTC() 2853 revokedCertsUTC[i] = rc 2854 } 2855 2856 tbsCertList := pkix.TBSCertificateList{ 2857 Version: 1, 2858 Signature: signatureAlgorithm, 2859 Issuer: c.Subject.ToRDNSequence(), 2860 ThisUpdate: now.UTC(), 2861 NextUpdate: expiry.UTC(), 2862 RevokedCertificates: revokedCertsUTC, 2863 } 2864 2865 // Authority Key Id 2866 if len(c.SubjectKeyId) > 0 { 2867 var aki pkix.Extension 2868 aki.Id = OIDExtensionAuthorityKeyId 2869 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) 2870 if err != nil { 2871 return 2872 } 2873 tbsCertList.Extensions = append(tbsCertList.Extensions, aki) 2874 } 2875 2876 tbsCertListContents, err := asn1.Marshal(tbsCertList) 2877 if err != nil { 2878 return 2879 } 2880 2881 signed := tbsCertListContents 2882 if hashFunc != 0 { 2883 h := hashFunc.New() 2884 h.Write(signed) 2885 signed = h.Sum(nil) 2886 } 2887 2888 var signature []byte 2889 signature, err = key.Sign(rand, signed, hashFunc) 2890 if err != nil { 2891 return 2892 } 2893 2894 return asn1.Marshal(pkix.CertificateList{ 2895 TBSCertList: tbsCertList, 2896 SignatureAlgorithm: signatureAlgorithm, 2897 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2898 }) 2899} 2900 2901// CertificateRequest represents a PKCS #10, certificate signature request. 2902type CertificateRequest struct { 2903 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). 2904 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. 2905 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 2906 RawSubject []byte // DER encoded Subject. 2907 2908 Version int 2909 Signature []byte 2910 SignatureAlgorithm SignatureAlgorithm 2911 2912 PublicKeyAlgorithm PublicKeyAlgorithm 2913 PublicKey interface{} 2914 2915 Subject pkix.Name 2916 2917 // Attributes contains the CSR attributes that can parse as 2918 // pkix.AttributeTypeAndValueSET. 2919 // 2920 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and 2921 // generating the requestedExtensions attribute. 2922 Attributes []pkix.AttributeTypeAndValueSET 2923 2924 // Extensions contains all requested extensions, in raw form. When parsing 2925 // CSRs, this can be used to extract extensions that are not parsed by this 2926 // package. 2927 Extensions []pkix.Extension 2928 2929 // ExtraExtensions contains extensions to be copied, raw, into any CSR 2930 // marshaled by CreateCertificateRequest. Values override any extensions 2931 // that would otherwise be produced based on the other fields but are 2932 // overridden by any extensions specified in Attributes. 2933 // 2934 // The ExtraExtensions field is not populated by ParseCertificateRequest, 2935 // see Extensions instead. 2936 ExtraExtensions []pkix.Extension 2937 2938 // Subject Alternate Name values. 2939 DNSNames []string 2940 EmailAddresses []string 2941 IPAddresses []net.IP 2942 URIs []*url.URL 2943} 2944 2945// These structures reflect the ASN.1 structure of X.509 certificate 2946// signature requests (see RFC 2986): 2947 2948type tbsCertificateRequest struct { 2949 Raw asn1.RawContent 2950 Version int 2951 Subject asn1.RawValue 2952 PublicKey publicKeyInfo 2953 RawAttributes []asn1.RawValue `asn1:"tag:0"` 2954} 2955 2956type certificateRequest struct { 2957 Raw asn1.RawContent 2958 TBSCSR tbsCertificateRequest 2959 SignatureAlgorithm pkix.AlgorithmIdentifier 2960 SignatureValue asn1.BitString 2961} 2962 2963// oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested 2964// extensions in a CSR. 2965var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} 2966 2967// newRawAttributes converts AttributeTypeAndValueSETs from a template 2968// CertificateRequest's Attributes into tbsCertificateRequest RawAttributes. 2969func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { 2970 var rawAttributes []asn1.RawValue 2971 b, err := asn1.Marshal(attributes) 2972 if err != nil { 2973 return nil, err 2974 } 2975 rest, err := asn1.Unmarshal(b, &rawAttributes) 2976 if err != nil { 2977 return nil, err 2978 } 2979 if len(rest) != 0 { 2980 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes") 2981 } 2982 return rawAttributes, nil 2983} 2984 2985// parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs. 2986func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { 2987 var attributes []pkix.AttributeTypeAndValueSET 2988 for _, rawAttr := range rawAttributes { 2989 var attr pkix.AttributeTypeAndValueSET 2990 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) 2991 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET 2992 // (i.e.: challengePassword or unstructuredName). 2993 if err == nil && len(rest) == 0 { 2994 attributes = append(attributes, attr) 2995 } 2996 } 2997 return attributes 2998} 2999 3000// parseCSRExtensions parses the attributes from a CSR and extracts any 3001// requested extensions. 3002func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) { 3003 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1. 3004 type pkcs10Attribute struct { 3005 Id asn1.ObjectIdentifier 3006 Values []asn1.RawValue `asn1:"set"` 3007 } 3008 3009 var ret []pkix.Extension 3010 for _, rawAttr := range rawAttributes { 3011 var attr pkcs10Attribute 3012 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 { 3013 // Ignore attributes that don't parse. 3014 continue 3015 } 3016 3017 if !attr.Id.Equal(oidExtensionRequest) { 3018 continue 3019 } 3020 3021 var extensions []pkix.Extension 3022 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil { 3023 return nil, err 3024 } 3025 ret = append(ret, extensions...) 3026 } 3027 3028 return ret, nil 3029} 3030 3031// CreateCertificateRequest creates a new certificate request based on a 3032// template. The following members of template are used: 3033// 3034// - SignatureAlgorithm 3035// - Subject 3036// - DNSNames 3037// - EmailAddresses 3038// - IPAddresses 3039// - URIs 3040// - ExtraExtensions 3041// - Attributes (deprecated) 3042// 3043// priv is the private key to sign the CSR with, and the corresponding public 3044// key will be included in the CSR. It must implement crypto.Signer and its 3045// Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a 3046// ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or 3047// ed25519.PrivateKey satisfies this.) 3048// 3049// The returned slice is the certificate request in DER encoding. 3050func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { 3051 key, ok := priv.(crypto.Signer) 3052 if !ok { 3053 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 3054 } 3055 3056 var hashFunc crypto.Hash 3057 var sigAlgo pkix.AlgorithmIdentifier 3058 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 3059 if err != nil { 3060 return nil, err 3061 } 3062 3063 var publicKeyBytes []byte 3064 var publicKeyAlgorithm pkix.AlgorithmIdentifier 3065 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public()) 3066 if err != nil { 3067 return nil, err 3068 } 3069 3070 var extensions []pkix.Extension 3071 3072 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) && 3073 !oidInExtensions(OIDExtensionSubjectAltName, template.ExtraExtensions) { 3074 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs) 3075 if err != nil { 3076 return nil, err 3077 } 3078 3079 extensions = append(extensions, pkix.Extension{ 3080 Id: OIDExtensionSubjectAltName, 3081 Value: sanBytes, 3082 }) 3083 } 3084 3085 extensions = append(extensions, template.ExtraExtensions...) 3086 3087 // Make a copy of template.Attributes because we may alter it below. 3088 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes)) 3089 for _, attr := range template.Attributes { 3090 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value)) 3091 copy(values, attr.Value) 3092 attributes = append(attributes, pkix.AttributeTypeAndValueSET{ 3093 Type: attr.Type, 3094 Value: values, 3095 }) 3096 } 3097 3098 extensionsAppended := false 3099 if len(extensions) > 0 { 3100 // Append the extensions to an existing attribute if possible. 3101 for _, atvSet := range attributes { 3102 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { 3103 continue 3104 } 3105 3106 // specifiedExtensions contains all the extensions that we 3107 // found specified via template.Attributes. 3108 specifiedExtensions := make(map[string]bool) 3109 3110 for _, atvs := range atvSet.Value { 3111 for _, atv := range atvs { 3112 specifiedExtensions[atv.Type.String()] = true 3113 } 3114 } 3115 3116 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions)) 3117 newValue = append(newValue, atvSet.Value[0]...) 3118 3119 for _, e := range extensions { 3120 if specifiedExtensions[e.Id.String()] { 3121 // Attributes already contained a value for 3122 // this extension and it takes priority. 3123 continue 3124 } 3125 3126 newValue = append(newValue, pkix.AttributeTypeAndValue{ 3127 // There is no place for the critical 3128 // flag in an AttributeTypeAndValue. 3129 Type: e.Id, 3130 Value: e.Value, 3131 }) 3132 } 3133 3134 atvSet.Value[0] = newValue 3135 extensionsAppended = true 3136 break 3137 } 3138 } 3139 3140 rawAttributes, err := newRawAttributes(attributes) 3141 if err != nil { 3142 return 3143 } 3144 3145 // If not included in attributes, add a new attribute for the 3146 // extensions. 3147 if len(extensions) > 0 && !extensionsAppended { 3148 attr := struct { 3149 Type asn1.ObjectIdentifier 3150 Value [][]pkix.Extension `asn1:"set"` 3151 }{ 3152 Type: oidExtensionRequest, 3153 Value: [][]pkix.Extension{extensions}, 3154 } 3155 3156 b, err := asn1.Marshal(attr) 3157 if err != nil { 3158 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error()) 3159 } 3160 3161 var rawValue asn1.RawValue 3162 if _, err := asn1.Unmarshal(b, &rawValue); err != nil { 3163 return nil, err 3164 } 3165 3166 rawAttributes = append(rawAttributes, rawValue) 3167 } 3168 3169 asn1Subject := template.RawSubject 3170 if len(asn1Subject) == 0 { 3171 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) 3172 if err != nil { 3173 return nil, err 3174 } 3175 } 3176 3177 tbsCSR := tbsCertificateRequest{ 3178 Version: 0, // PKCS #10, RFC 2986 3179 Subject: asn1.RawValue{FullBytes: asn1Subject}, 3180 PublicKey: publicKeyInfo{ 3181 Algorithm: publicKeyAlgorithm, 3182 PublicKey: asn1.BitString{ 3183 Bytes: publicKeyBytes, 3184 BitLength: len(publicKeyBytes) * 8, 3185 }, 3186 }, 3187 RawAttributes: rawAttributes, 3188 } 3189 3190 tbsCSRContents, err := asn1.Marshal(tbsCSR) 3191 if err != nil { 3192 return 3193 } 3194 tbsCSR.Raw = tbsCSRContents 3195 3196 signed := tbsCSRContents 3197 if hashFunc != 0 { 3198 h := hashFunc.New() 3199 h.Write(signed) 3200 signed = h.Sum(nil) 3201 } 3202 3203 var signature []byte 3204 signature, err = key.Sign(rand, signed, hashFunc) 3205 if err != nil { 3206 return 3207 } 3208 3209 return asn1.Marshal(certificateRequest{ 3210 TBSCSR: tbsCSR, 3211 SignatureAlgorithm: sigAlgo, 3212 SignatureValue: asn1.BitString{ 3213 Bytes: signature, 3214 BitLength: len(signature) * 8, 3215 }, 3216 }) 3217} 3218 3219// ParseCertificateRequest parses a single certificate request from the 3220// given ASN.1 DER data. 3221func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { 3222 var csr certificateRequest 3223 3224 rest, err := asn1.Unmarshal(asn1Data, &csr) 3225 if err != nil { 3226 return nil, err 3227 } else if len(rest) != 0 { 3228 return nil, asn1.SyntaxError{Msg: "trailing data"} 3229 } 3230 3231 return parseCertificateRequest(&csr) 3232} 3233 3234func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { 3235 out := &CertificateRequest{ 3236 Raw: in.Raw, 3237 RawTBSCertificateRequest: in.TBSCSR.Raw, 3238 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, 3239 RawSubject: in.TBSCSR.Subject.FullBytes, 3240 3241 Signature: in.SignatureValue.RightAlign(), 3242 SignatureAlgorithm: SignatureAlgorithmFromAI(in.SignatureAlgorithm), 3243 3244 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), 3245 3246 Version: in.TBSCSR.Version, 3247 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes), 3248 } 3249 3250 var err error 3251 var nfe NonFatalErrors 3252 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey, &nfe) 3253 if err != nil { 3254 return nil, err 3255 } 3256 // Treat non-fatal errors as fatal here. 3257 if len(nfe.Errors) > 0 { 3258 return nil, nfe.Errors[0] 3259 } 3260 3261 var subject pkix.RDNSequence 3262 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { 3263 return nil, err 3264 } else if len(rest) != 0 { 3265 return nil, errors.New("x509: trailing data after X.509 Subject") 3266 } 3267 3268 out.Subject.FillFromRDNSequence(&subject) 3269 3270 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil { 3271 return nil, err 3272 } 3273 3274 for _, extension := range out.Extensions { 3275 if extension.Id.Equal(OIDExtensionSubjectAltName) { 3276 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value, &nfe) 3277 if err != nil { 3278 return nil, err 3279 } 3280 } 3281 } 3282 3283 return out, nil 3284} 3285 3286// CheckSignature reports whether the signature on c is valid. 3287func (c *CertificateRequest) CheckSignature() error { 3288 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey) 3289} 3290