github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/ct/x509/x509.go (about) 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 // START CT CHANGES 8 // This is a fork of the go library crypto/x509 package, it's more relaxed 9 // about certificates that it'll accept, and exports the TBSCertificate 10 // structure. 11 // END CT CHANGES 12 package x509 13 14 import ( 15 "bytes" 16 "crypto" 17 "crypto/ecdsa" 18 "crypto/elliptic" 19 "crypto/rsa" 20 "crypto/sha1" 21 22 "github.com/zmap/zcrypto/dsa" 23 24 // START CT CHANGES 25 "github.com/zmap/zcrypto/ct/asn1" 26 "github.com/zmap/zcrypto/ct/x509/pkix" 27 28 // END CT CHANGES 29 "encoding/pem" 30 "errors" 31 32 // START CT CHANGES 33 "fmt" 34 // END CT CHANGES 35 "io" 36 "math/big" 37 "net" 38 "time" 39 ) 40 41 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo 42 // in RFC 3280. 43 type pkixPublicKey struct { 44 Algo pkix.AlgorithmIdentifier 45 BitString asn1.BitString 46 } 47 48 // ParsePKIXPublicKey parses a DER encoded public key. These values are 49 // typically found in PEM blocks with "BEGIN PUBLIC KEY". 50 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { 51 var pki publicKeyInfo 52 if _, err = asn1.Unmarshal(derBytes, &pki); err != nil { 53 return 54 } 55 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) 56 if algo == UnknownPublicKeyAlgorithm { 57 return nil, errors.New("x509: unknown public key algorithm") 58 } 59 return parsePublicKey(algo, &pki) 60 } 61 62 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { 63 switch pub := pub.(type) { 64 case *rsa.PublicKey: 65 publicKeyBytes, err = asn1.Marshal(rsaPublicKey{ 66 N: pub.N, 67 E: pub.E, 68 }) 69 if err != nil { 70 return 71 } 72 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA 73 // This is a NULL parameters value which is technically 74 // superfluous, but most other code includes it and, by 75 // doing this, we match their public key hashes. 76 publicKeyAlgorithm.Parameters = asn1.RawValue{ 77 Tag: 5, 78 } 79 case *ecdsa.PublicKey: 80 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 81 oid, ok := oidFromNamedCurve(pub.Curve) 82 if !ok { 83 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") 84 } 85 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA 86 var paramBytes []byte 87 paramBytes, err = asn1.Marshal(oid) 88 if err != nil { 89 return 90 } 91 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 92 default: 93 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported") 94 } 95 96 return publicKeyBytes, publicKeyAlgorithm, nil 97 } 98 99 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. 100 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { 101 var publicKeyBytes []byte 102 var publicKeyAlgorithm pkix.AlgorithmIdentifier 103 var err error 104 105 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { 106 return nil, err 107 } 108 109 pkix := pkixPublicKey{ 110 Algo: publicKeyAlgorithm, 111 BitString: asn1.BitString{ 112 Bytes: publicKeyBytes, 113 BitLength: 8 * len(publicKeyBytes), 114 }, 115 } 116 117 ret, _ := asn1.Marshal(pkix) 118 return ret, nil 119 } 120 121 // These structures reflect the ASN.1 structure of X.509 certificates.: 122 123 type certificate struct { 124 Raw asn1.RawContent 125 TBSCertificate tbsCertificate 126 SignatureAlgorithm pkix.AlgorithmIdentifier 127 SignatureValue asn1.BitString 128 } 129 130 type tbsCertificate struct { 131 Raw asn1.RawContent 132 Version int `asn1:"optional,explicit,default:1,tag:0"` 133 SerialNumber *big.Int 134 SignatureAlgorithm pkix.AlgorithmIdentifier 135 Issuer asn1.RawValue 136 Validity validity 137 Subject asn1.RawValue 138 PublicKey publicKeyInfo 139 UniqueId asn1.BitString `asn1:"optional,tag:1"` 140 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` 141 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` 142 } 143 144 type dsaAlgorithmParameters struct { 145 P, Q, G *big.Int 146 } 147 148 type dsaSignature struct { 149 R, S *big.Int 150 } 151 152 type ecdsaSignature dsaSignature 153 154 type validity struct { 155 NotBefore, NotAfter time.Time 156 } 157 158 type publicKeyInfo struct { 159 Raw asn1.RawContent 160 Algorithm pkix.AlgorithmIdentifier 161 PublicKey asn1.BitString 162 } 163 164 // RFC 5280, 4.2.1.1 165 type authKeyId struct { 166 Id []byte `asn1:"optional,tag:0"` 167 } 168 169 type SignatureAlgorithm int 170 171 const ( 172 UnknownSignatureAlgorithm SignatureAlgorithm = iota 173 MD2WithRSA 174 MD5WithRSA 175 SHA1WithRSA 176 SHA256WithRSA 177 SHA384WithRSA 178 SHA512WithRSA 179 DSAWithSHA1 180 DSAWithSHA256 181 ECDSAWithSHA1 182 ECDSAWithSHA256 183 ECDSAWithSHA384 184 ECDSAWithSHA512 185 ) 186 187 type PublicKeyAlgorithm int 188 189 const ( 190 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota 191 RSA 192 DSA 193 ECDSA 194 ) 195 196 // OIDs for signature algorithms 197 // 198 // pkcs-1 OBJECT IDENTIFIER ::= { 199 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } 200 // 201 // 202 // RFC 3279 2.2.1 RSA Signature Algorithms 203 // 204 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } 205 // 206 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } 207 // 208 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } 209 // 210 // dsaWithSha1 OBJECT IDENTIFIER ::= { 211 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 212 // 213 // RFC 3279 2.2.3 ECDSA Signature Algorithm 214 // 215 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { 216 // iso(1) member-body(2) us(840) ansi-x962(10045) 217 // signatures(4) ecdsa-with-SHA1(1)} 218 // 219 // 220 // RFC 4055 5 PKCS #1 Version 1.5 221 // 222 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } 223 // 224 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } 225 // 226 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } 227 // 228 // 229 // RFC 5758 3.1 DSA Signature Algorithms 230 // 231 // dsaWithSha256 OBJECT IDENTIFIER ::= { 232 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) 233 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2} 234 // 235 // RFC 5758 3.2 ECDSA Signature Algorithm 236 // 237 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 238 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } 239 // 240 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 241 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } 242 // 243 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 244 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } 245 246 var ( 247 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} 248 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} 249 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} 250 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} 251 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} 252 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} 253 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} 254 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2} 255 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} 256 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} 257 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} 258 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} 259 260 oidExtensionCTPrecertificatePoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3} 261 ) 262 263 func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm { 264 switch { 265 case oid.Equal(oidSignatureMD2WithRSA): 266 return MD2WithRSA 267 case oid.Equal(oidSignatureMD5WithRSA): 268 return MD5WithRSA 269 case oid.Equal(oidSignatureSHA1WithRSA): 270 return SHA1WithRSA 271 case oid.Equal(oidSignatureSHA256WithRSA): 272 return SHA256WithRSA 273 case oid.Equal(oidSignatureSHA384WithRSA): 274 return SHA384WithRSA 275 case oid.Equal(oidSignatureSHA512WithRSA): 276 return SHA512WithRSA 277 case oid.Equal(oidSignatureDSAWithSHA1): 278 return DSAWithSHA1 279 case oid.Equal(oidSignatureDSAWithSHA256): 280 return DSAWithSHA256 281 case oid.Equal(oidSignatureECDSAWithSHA1): 282 return ECDSAWithSHA1 283 case oid.Equal(oidSignatureECDSAWithSHA256): 284 return ECDSAWithSHA256 285 case oid.Equal(oidSignatureECDSAWithSHA384): 286 return ECDSAWithSHA384 287 case oid.Equal(oidSignatureECDSAWithSHA512): 288 return ECDSAWithSHA512 289 } 290 return UnknownSignatureAlgorithm 291 } 292 293 // RFC 3279, 2.3 Public Key Algorithms 294 // 295 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 296 // 297 // rsadsi(113549) pkcs(1) 1 } 298 // 299 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } 300 // 301 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 302 // 303 // x9-57(10040) x9cm(4) 1 } 304 // 305 // # RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters 306 // 307 // id-ecPublicKey OBJECT IDENTIFIER ::= { 308 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } 309 var ( 310 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} 311 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} 312 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} 313 ) 314 315 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { 316 switch { 317 case oid.Equal(oidPublicKeyRSA): 318 return RSA 319 case oid.Equal(oidPublicKeyDSA): 320 return DSA 321 case oid.Equal(oidPublicKeyECDSA): 322 return ECDSA 323 } 324 return UnknownPublicKeyAlgorithm 325 } 326 327 // RFC 5480, 2.1.1.1. Named Curve 328 // 329 // secp224r1 OBJECT IDENTIFIER ::= { 330 // iso(1) identified-organization(3) certicom(132) curve(0) 33 } 331 // 332 // secp256r1 OBJECT IDENTIFIER ::= { 333 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) 334 // prime(1) 7 } 335 // 336 // secp384r1 OBJECT IDENTIFIER ::= { 337 // iso(1) identified-organization(3) certicom(132) curve(0) 34 } 338 // 339 // secp521r1 OBJECT IDENTIFIER ::= { 340 // iso(1) identified-organization(3) certicom(132) curve(0) 35 } 341 // 342 // NB: secp256r1 is equivalent to prime256v1 343 var ( 344 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} 345 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} 346 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} 347 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} 348 ) 349 350 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { 351 switch { 352 case oid.Equal(oidNamedCurveP224): 353 return elliptic.P224() 354 case oid.Equal(oidNamedCurveP256): 355 return elliptic.P256() 356 case oid.Equal(oidNamedCurveP384): 357 return elliptic.P384() 358 case oid.Equal(oidNamedCurveP521): 359 return elliptic.P521() 360 } 361 return nil 362 } 363 364 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { 365 switch curve { 366 case elliptic.P224(): 367 return oidNamedCurveP224, true 368 case elliptic.P256(): 369 return oidNamedCurveP256, true 370 case elliptic.P384(): 371 return oidNamedCurveP384, true 372 case elliptic.P521(): 373 return oidNamedCurveP521, true 374 } 375 376 return nil, false 377 } 378 379 // KeyUsage represents the set of actions that are valid for a given key. It's 380 // a bitmap of the KeyUsage* constants. 381 type KeyUsage int 382 383 const ( 384 KeyUsageDigitalSignature KeyUsage = 1 << iota 385 KeyUsageContentCommitment 386 KeyUsageKeyEncipherment 387 KeyUsageDataEncipherment 388 KeyUsageKeyAgreement 389 KeyUsageCertSign 390 KeyUsageCRLSign 391 KeyUsageEncipherOnly 392 KeyUsageDecipherOnly 393 ) 394 395 // RFC 5280, 4.2.1.12 Extended Key Usage 396 // 397 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } 398 // 399 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } 400 // 401 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } 402 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } 403 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } 404 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } 405 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } 406 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } 407 var ( 408 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} 409 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} 410 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} 411 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} 412 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} 413 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} 414 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} 415 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} 416 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} 417 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} 418 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} 419 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} 420 ) 421 422 // ExtKeyUsage represents an extended set of actions that are valid for a given key. 423 // Each of the ExtKeyUsage* constants define a unique action. 424 type ExtKeyUsage int 425 426 const ( 427 ExtKeyUsageAny ExtKeyUsage = iota 428 ExtKeyUsageServerAuth 429 ExtKeyUsageClientAuth 430 ExtKeyUsageCodeSigning 431 ExtKeyUsageEmailProtection 432 ExtKeyUsageIPSECEndSystem 433 ExtKeyUsageIPSECTunnel 434 ExtKeyUsageIPSECUser 435 ExtKeyUsageTimeStamping 436 ExtKeyUsageOCSPSigning 437 ExtKeyUsageMicrosoftServerGatedCrypto 438 ExtKeyUsageNetscapeServerGatedCrypto 439 ) 440 441 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. 442 var extKeyUsageOIDs = []struct { 443 extKeyUsage ExtKeyUsage 444 oid asn1.ObjectIdentifier 445 }{ 446 {ExtKeyUsageAny, oidExtKeyUsageAny}, 447 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, 448 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, 449 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, 450 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, 451 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, 452 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, 453 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, 454 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, 455 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, 456 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, 457 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, 458 } 459 460 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { 461 for _, pair := range extKeyUsageOIDs { 462 if oid.Equal(pair.oid) { 463 return pair.extKeyUsage, true 464 } 465 } 466 return 467 } 468 469 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { 470 for _, pair := range extKeyUsageOIDs { 471 if eku == pair.extKeyUsage { 472 return pair.oid, true 473 } 474 } 475 return 476 } 477 478 // A Certificate represents an X.509 certificate. 479 type Certificate struct { 480 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature). 481 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content. 482 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 483 RawSubject []byte // DER encoded Subject 484 RawIssuer []byte // DER encoded Issuer 485 486 Signature []byte 487 SignatureAlgorithm SignatureAlgorithm 488 489 PublicKeyAlgorithm PublicKeyAlgorithm 490 PublicKey interface{} 491 492 Version int 493 SerialNumber *big.Int 494 Issuer pkix.Name 495 Subject pkix.Name 496 NotBefore, NotAfter time.Time // Validity bounds. 497 KeyUsage KeyUsage 498 499 // Extensions contains raw X.509 extensions. When parsing certificates, 500 // this can be used to extract non-critical extensions that are not 501 // parsed by this package. When marshaling certificates, the Extensions 502 // field is ignored, see ExtraExtensions. 503 Extensions []pkix.Extension 504 505 // ExtraExtensions contains extensions to be copied, raw, into any 506 // marshaled certificates. Values override any extensions that would 507 // otherwise be produced based on the other fields. The ExtraExtensions 508 // field is not populated when parsing certificates, see Extensions. 509 ExtraExtensions []pkix.Extension 510 511 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. 512 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. 513 514 BasicConstraintsValid bool // if true then the next two fields are valid. 515 IsCA bool 516 MaxPathLen int 517 518 SubjectKeyId []byte 519 AuthorityKeyId []byte 520 521 // RFC 5280, 4.2.2.1 (Authority Information Access) 522 OCSPServer []string 523 IssuingCertificateURL []string 524 525 // Subject Alternate Name values 526 DNSNames []string 527 EmailAddresses []string 528 IPAddresses []net.IP 529 530 // Name constraints 531 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. 532 PermittedDNSDomains []string 533 534 // CRL Distribution Points 535 CRLDistributionPoints []string 536 537 IsPrecert bool 538 PolicyIdentifiers []asn1.ObjectIdentifier 539 } 540 541 // ErrUnsupportedAlgorithm results from attempting to perform an operation that 542 // involves algorithms that are not currently implemented. 543 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") 544 545 // ConstraintViolationError results when a requested usage is not permitted by 546 // a certificate. For example: checking a signature when the public key isn't a 547 // certificate signing key. 548 type ConstraintViolationError struct{} 549 550 func (ConstraintViolationError) Error() string { 551 return "x509: invalid signature: parent certificate cannot sign this kind of certificate" 552 } 553 554 func (c *Certificate) Equal(other *Certificate) bool { 555 return bytes.Equal(c.Raw, other.Raw) 556 } 557 558 // Entrust have a broken root certificate (CN=Entrust.net Certification 559 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid 560 // according to PKIX. 561 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it 562 // from the Basic Constraints requirement. 563 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 564 // 565 // TODO(agl): remove this hack once their reissued root is sufficiently 566 // widespread. 567 var entrustBrokenSPKI = []byte{ 568 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 569 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 570 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 571 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 572 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, 573 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, 574 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, 575 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, 576 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, 577 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, 578 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, 579 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, 580 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, 581 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, 582 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, 583 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, 584 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, 585 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, 586 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, 587 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, 588 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, 589 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, 590 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, 591 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, 592 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, 593 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, 594 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, 595 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, 596 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, 597 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, 598 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, 599 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, 600 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, 601 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, 602 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, 603 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, 604 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, 605 } 606 607 // CheckSignatureFrom verifies that the signature on c is a valid signature 608 // from parent. 609 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) { 610 // RFC 5280, 4.2.1.9: 611 // "If the basic constraints extension is not present in a version 3 612 // certificate, or the extension is present but the cA boolean is not 613 // asserted, then the certified public key MUST NOT be used to verify 614 // certificate signatures." 615 // (except for Entrust, see comment above entrustBrokenSPKI) 616 if (parent.Version == 3 && !parent.BasicConstraintsValid || 617 parent.BasicConstraintsValid && !parent.IsCA) && 618 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { 619 return ConstraintViolationError{} 620 } 621 622 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { 623 return ConstraintViolationError{} 624 } 625 626 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 627 return ErrUnsupportedAlgorithm 628 } 629 630 // TODO(agl): don't ignore the path length constraint. 631 632 if parent.Subject.String() != c.Issuer.String() { 633 return errors.New(fmt.Sprintf("Mis-match issuer/subject (%s!=%s)", parent.Subject.String(), c.Issuer.String())) 634 } 635 636 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) 637 } 638 639 // CheckSignature verifies that signature is a valid signature over signed from 640 // c's public key. 641 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) { 642 var hashType crypto.Hash 643 644 switch algo { 645 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1: 646 hashType = crypto.SHA1 647 case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256: 648 hashType = crypto.SHA256 649 case SHA384WithRSA, ECDSAWithSHA384: 650 hashType = crypto.SHA384 651 case SHA512WithRSA, ECDSAWithSHA512: 652 hashType = crypto.SHA512 653 default: 654 return ErrUnsupportedAlgorithm 655 } 656 657 if !hashType.Available() { 658 return ErrUnsupportedAlgorithm 659 } 660 h := hashType.New() 661 662 h.Write(signed) 663 digest := h.Sum(nil) 664 665 switch pub := c.PublicKey.(type) { 666 case *rsa.PublicKey: 667 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) 668 case *dsa.PublicKey: 669 dsaSig := new(dsaSignature) 670 if _, err := asn1.Unmarshal(signature, dsaSig); err != nil { 671 return err 672 } 673 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { 674 return errors.New("x509: DSA signature contained zero or negative values") 675 } 676 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { 677 return errors.New("x509: DSA verification failure") 678 } 679 return 680 case *ecdsa.PublicKey: 681 ecdsaSig := new(ecdsaSignature) 682 if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { 683 return err 684 } 685 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { 686 return errors.New("x509: ECDSA signature contained zero or negative values") 687 } 688 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { 689 return errors.New("x509: ECDSA verification failure") 690 } 691 return 692 } 693 return ErrUnsupportedAlgorithm 694 } 695 696 // CheckCRLSignature checks that the signature in crl is from c. 697 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) { 698 algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm) 699 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) 700 } 701 702 // START CT CHANGES 703 type UnhandledCriticalExtension struct { 704 ID asn1.ObjectIdentifier 705 } 706 707 func (h UnhandledCriticalExtension) Error() string { 708 return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID) 709 } 710 711 // END CT CHANGES 712 713 type basicConstraints struct { 714 IsCA bool `asn1:"optional"` 715 MaxPathLen int `asn1:"optional,default:-1"` 716 } 717 718 // RFC 5280 4.2.1.4 719 type policyInformation struct { 720 Policy asn1.ObjectIdentifier 721 // policyQualifiers omitted 722 } 723 724 // RFC 5280, 4.2.1.10 725 type nameConstraints struct { 726 Permitted []generalSubtree `asn1:"optional,tag:0"` 727 Excluded []generalSubtree `asn1:"optional,tag:1"` 728 } 729 730 type generalSubtree struct { 731 Name string `asn1:"tag:2,optional,ia5"` 732 } 733 734 // RFC 5280, 4.2.2.1 735 type authorityInfoAccess struct { 736 Method asn1.ObjectIdentifier 737 Location asn1.RawValue 738 } 739 740 // RFC 5280, 4.2.1.14 741 type distributionPoint struct { 742 DistributionPoint distributionPointName `asn1:"optional,tag:0"` 743 Reason asn1.BitString `asn1:"optional,tag:1"` 744 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` 745 } 746 747 type distributionPointName struct { 748 FullName asn1.RawValue `asn1:"optional,tag:0"` 749 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` 750 } 751 752 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { 753 asn1Data := keyData.PublicKey.RightAlign() 754 switch algo { 755 case RSA: 756 p := new(rsaPublicKey) 757 _, err := asn1.Unmarshal(asn1Data, p) 758 if err != nil { 759 return nil, err 760 } 761 762 if p.N.Sign() <= 0 { 763 return nil, errors.New("x509: RSA modulus is not a positive number") 764 } 765 if p.E <= 0 { 766 return nil, errors.New("x509: RSA public exponent is not a positive number") 767 } 768 769 pub := &rsa.PublicKey{ 770 E: p.E, 771 N: p.N, 772 } 773 return pub, nil 774 case DSA: 775 var p *big.Int 776 _, err := asn1.Unmarshal(asn1Data, &p) 777 if err != nil { 778 return nil, err 779 } 780 paramsData := keyData.Algorithm.Parameters.FullBytes 781 params := new(dsaAlgorithmParameters) 782 _, err = asn1.Unmarshal(paramsData, params) 783 if err != nil { 784 return nil, err 785 } 786 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { 787 return nil, errors.New("x509: zero or negative DSA parameter") 788 } 789 pub := &dsa.PublicKey{ 790 Parameters: dsa.Parameters{ 791 P: params.P, 792 Q: params.Q, 793 G: params.G, 794 }, 795 Y: p, 796 } 797 return pub, nil 798 case ECDSA: 799 paramsData := keyData.Algorithm.Parameters.FullBytes 800 namedCurveOID := new(asn1.ObjectIdentifier) 801 _, err := asn1.Unmarshal(paramsData, namedCurveOID) 802 if err != nil { 803 return nil, err 804 } 805 namedCurve := namedCurveFromOID(*namedCurveOID) 806 if namedCurve == nil { 807 return nil, errors.New("x509: unsupported elliptic curve") 808 } 809 x, y := elliptic.Unmarshal(namedCurve, asn1Data) 810 if x == nil { 811 return nil, errors.New("x509: failed to unmarshal elliptic curve point") 812 } 813 pub := &ecdsa.PublicKey{ 814 Curve: namedCurve, 815 X: x, 816 Y: y, 817 } 818 return pub, nil 819 default: 820 return nil, nil 821 } 822 } 823 824 // START CT CHANGES 825 826 // NonFatalErrors is an error type which can hold a number of other errors. 827 // It's used to collect a range of non-fatal errors which occur while parsing 828 // a certificate, that way we can still match on certs which technically are 829 // invalid. 830 type NonFatalErrors struct { 831 Errors []error 832 } 833 834 // Adds an error to the list of errors contained by NonFatalErrors. 835 func (e *NonFatalErrors) AddError(err error) { 836 e.Errors = append(e.Errors, err) 837 } 838 839 // Returns a string consisting of the values of Error() from all of the errors 840 // contained in |e| 841 func (e NonFatalErrors) Error() string { 842 r := "NonFatalErrors: " 843 for _, err := range e.Errors { 844 r += err.Error() + "; " 845 } 846 return r 847 } 848 849 // Returns true if |e| contains at least one error 850 func (e *NonFatalErrors) HasError() bool { 851 return len(e.Errors) > 0 852 } 853 854 // END CT CHANGES 855 856 func parseCertificate(in *certificate) (*Certificate, error) { 857 // START CT CHANGES 858 var nfe NonFatalErrors 859 // END CT CHANGES 860 861 out := new(Certificate) 862 out.Raw = in.Raw 863 out.RawTBSCertificate = in.TBSCertificate.Raw 864 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw 865 out.RawSubject = in.TBSCertificate.Subject.FullBytes 866 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes 867 868 out.Signature = in.SignatureValue.RightAlign() 869 out.SignatureAlgorithm = 870 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm) 871 872 out.PublicKeyAlgorithm = 873 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) 874 var err error 875 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey) 876 if err != nil { 877 return nil, err 878 } 879 880 if in.TBSCertificate.SerialNumber.Sign() < 0 { 881 // START CT CHANGES 882 nfe.AddError(errors.New("x509: negative serial number")) 883 // END CT CHANGES 884 } 885 886 out.Version = in.TBSCertificate.Version + 1 887 out.SerialNumber = in.TBSCertificate.SerialNumber 888 889 var issuer, subject pkix.RDNSequence 890 if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { 891 return nil, err 892 } 893 if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { 894 return nil, err 895 } 896 897 out.Issuer.FillFromRDNSequence(&issuer) 898 out.Subject.FillFromRDNSequence(&subject) 899 900 out.NotBefore = in.TBSCertificate.Validity.NotBefore 901 out.NotAfter = in.TBSCertificate.Validity.NotAfter 902 903 for _, e := range in.TBSCertificate.Extensions { 904 out.Extensions = append(out.Extensions, e) 905 906 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { 907 switch e.Id[3] { 908 case 15: 909 // RFC 5280, 4.2.1.3 910 var usageBits asn1.BitString 911 _, err := asn1.Unmarshal(e.Value, &usageBits) 912 913 if err == nil { 914 var usage int 915 for i := 0; i < 9; i++ { 916 if usageBits.At(i) != 0 { 917 usage |= 1 << uint(i) 918 } 919 } 920 out.KeyUsage = KeyUsage(usage) 921 continue 922 } 923 case 19: 924 // RFC 5280, 4.2.1.9 925 var constraints basicConstraints 926 _, err := asn1.Unmarshal(e.Value, &constraints) 927 928 if err == nil { 929 out.BasicConstraintsValid = true 930 out.IsCA = constraints.IsCA 931 out.MaxPathLen = constraints.MaxPathLen 932 continue 933 } 934 case 17: 935 // RFC 5280, 4.2.1.6 936 937 // SubjectAltName ::= GeneralNames 938 // 939 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 940 // 941 // GeneralName ::= CHOICE { 942 // otherName [0] OtherName, 943 // rfc822Name [1] IA5String, 944 // dNSName [2] IA5String, 945 // x400Address [3] ORAddress, 946 // directoryName [4] Name, 947 // ediPartyName [5] EDIPartyName, 948 // uniformResourceIdentifier [6] IA5String, 949 // iPAddress [7] OCTET STRING, 950 // registeredID [8] OBJECT IDENTIFIER } 951 var seq asn1.RawValue 952 _, err := asn1.Unmarshal(e.Value, &seq) 953 if err != nil { 954 return nil, err 955 } 956 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { 957 return nil, asn1.StructuralError{Msg: "bad SAN sequence"} 958 } 959 960 parsedName := false 961 962 rest := seq.Bytes 963 for len(rest) > 0 { 964 var v asn1.RawValue 965 rest, err = asn1.Unmarshal(rest, &v) 966 if err != nil { 967 return nil, err 968 } 969 switch v.Tag { 970 case 1: 971 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes)) 972 parsedName = true 973 case 2: 974 out.DNSNames = append(out.DNSNames, string(v.Bytes)) 975 parsedName = true 976 case 7: 977 switch len(v.Bytes) { 978 case net.IPv4len, net.IPv6len: 979 out.IPAddresses = append(out.IPAddresses, v.Bytes) 980 default: 981 // START CT CHANGES 982 nfe.AddError(fmt.Errorf("x509: certificate contained IP address of length %d : %v", len(v.Bytes), v.Bytes)) 983 // END CT CHANGES 984 } 985 } 986 } 987 988 if parsedName { 989 continue 990 } 991 // If we didn't parse any of the names then we 992 // fall through to the critical check below. 993 994 case 30: 995 // RFC 5280, 4.2.1.10 996 997 // NameConstraints ::= SEQUENCE { 998 // permittedSubtrees [0] GeneralSubtrees OPTIONAL, 999 // excludedSubtrees [1] GeneralSubtrees OPTIONAL } 1000 // 1001 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree 1002 // 1003 // GeneralSubtree ::= SEQUENCE { 1004 // base GeneralName, 1005 // minimum [0] BaseDistance DEFAULT 0, 1006 // maximum [1] BaseDistance OPTIONAL } 1007 // 1008 // BaseDistance ::= INTEGER (0..MAX) 1009 1010 var constraints nameConstraints 1011 _, err := asn1.Unmarshal(e.Value, &constraints) 1012 if err != nil { 1013 return nil, err 1014 } 1015 1016 if len(constraints.Excluded) > 0 && e.Critical { 1017 // START CT CHANGES 1018 nfe.AddError(UnhandledCriticalExtension{e.Id}) 1019 // END CT CHANGES 1020 } 1021 1022 for _, subtree := range constraints.Permitted { 1023 if len(subtree.Name) == 0 { 1024 if e.Critical { 1025 // START CT CHANGES 1026 nfe.AddError(UnhandledCriticalExtension{e.Id}) 1027 // END CT CHANGES 1028 } 1029 continue 1030 } 1031 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name) 1032 } 1033 continue 1034 1035 case 31: 1036 // RFC 5280, 4.2.1.14 1037 1038 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 1039 // 1040 // DistributionPoint ::= SEQUENCE { 1041 // distributionPoint [0] DistributionPointName OPTIONAL, 1042 // reasons [1] ReasonFlags OPTIONAL, 1043 // cRLIssuer [2] GeneralNames OPTIONAL } 1044 // 1045 // DistributionPointName ::= CHOICE { 1046 // fullName [0] GeneralNames, 1047 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 1048 1049 var cdp []distributionPoint 1050 _, err := asn1.Unmarshal(e.Value, &cdp) 1051 if err != nil { 1052 return nil, err 1053 } 1054 1055 for _, dp := range cdp { 1056 var n asn1.RawValue 1057 dpName := dp.DistributionPoint.FullName.Bytes 1058 // FullName is a GeneralNames, which is a SEQUENCE OF 1059 // GeneralName, which in turn is a CHOICE. 1060 // Per https://www.ietf.org/rfc/rfc5280.txt, multiple names 1061 // for a single DistributionPoint give different pointers to 1062 // the same CRL. 1063 for len(dpName) > 0 { 1064 dpName, err = asn1.Unmarshal(dpName, &n) 1065 if err != nil { 1066 return nil, err 1067 } 1068 if n.Tag == 6 { 1069 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) 1070 } 1071 } 1072 } 1073 continue 1074 1075 case 35: 1076 // RFC 5280, 4.2.1.1 1077 var a authKeyId 1078 _, err = asn1.Unmarshal(e.Value, &a) 1079 if err != nil { 1080 return nil, err 1081 } 1082 out.AuthorityKeyId = a.Id 1083 continue 1084 1085 case 37: 1086 // RFC 5280, 4.2.1.12. Extended Key Usage 1087 1088 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } 1089 // 1090 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId 1091 // 1092 // KeyPurposeId ::= OBJECT IDENTIFIER 1093 1094 var keyUsage []asn1.ObjectIdentifier 1095 _, err = asn1.Unmarshal(e.Value, &keyUsage) 1096 if err != nil { 1097 return nil, err 1098 } 1099 1100 for _, u := range keyUsage { 1101 if extKeyUsage, ok := extKeyUsageFromOID(u); ok { 1102 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) 1103 } else { 1104 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) 1105 } 1106 } 1107 1108 continue 1109 1110 case 14: 1111 // RFC 5280, 4.2.1.2 1112 var keyid []byte 1113 _, err = asn1.Unmarshal(e.Value, &keyid) 1114 if err != nil { 1115 return nil, err 1116 } 1117 out.SubjectKeyId = keyid 1118 continue 1119 1120 case 32: 1121 // RFC 5280 4.2.1.4: Certificate Policies 1122 var policies []policyInformation 1123 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { 1124 return nil, err 1125 } 1126 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) 1127 for i, policy := range policies { 1128 out.PolicyIdentifiers[i] = policy.Policy 1129 } 1130 } 1131 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { 1132 // RFC 5280 4.2.2.1: Authority Information Access 1133 var aia []authorityInfoAccess 1134 if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { 1135 return nil, err 1136 } 1137 1138 for _, v := range aia { 1139 // GeneralName: uniformResourceIdentifier [6] IA5String 1140 if v.Location.Tag != 6 { 1141 continue 1142 } 1143 if v.Method.Equal(oidAuthorityInfoAccessOcsp) { 1144 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) 1145 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { 1146 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) 1147 } 1148 } 1149 } else if e.Id.Equal(oidExtensionCTPrecertificatePoison) { 1150 if len(e.Value) >= 2 && e.Value[0] == 5 && e.Value[1] == 0 { 1151 out.IsPrecert = true 1152 continue 1153 } else { 1154 return nil, UnhandledCriticalExtension{} 1155 } 1156 } 1157 1158 if e.Critical { 1159 // START CT CHANGES 1160 nfe.AddError(UnhandledCriticalExtension{e.Id}) 1161 // END CT CHANGES 1162 } 1163 } 1164 // START CT CHANGES 1165 if nfe.HasError() { 1166 return out, nfe 1167 } 1168 // END CT CHANGES 1169 return out, nil 1170 } 1171 1172 // START CT CHANGES 1173 1174 // ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data. 1175 // The parsed data is returned in a Certificate struct for ease of access. 1176 func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) { 1177 var tbsCert tbsCertificate 1178 rest, err := asn1.Unmarshal(asn1Data, &tbsCert) 1179 if err != nil { 1180 return nil, err 1181 } 1182 if len(rest) > 0 { 1183 return nil, asn1.SyntaxError{Msg: "trailing data"} 1184 } 1185 return parseCertificate(&certificate{ 1186 Raw: tbsCert.Raw, 1187 TBSCertificate: tbsCert}) 1188 } 1189 1190 // END CT CHANGES 1191 1192 // ParseCertificate parses a single certificate from the given ASN.1 DER data. 1193 func ParseCertificate(asn1Data []byte) (*Certificate, error) { 1194 var cert certificate 1195 rest, err := asn1.Unmarshal(asn1Data, &cert) 1196 if err != nil { 1197 return nil, err 1198 } 1199 if len(rest) > 0 { 1200 return nil, asn1.SyntaxError{Msg: "trailing data"} 1201 } 1202 1203 return parseCertificate(&cert) 1204 } 1205 1206 // ParseCertificates parses one or more certificates from the given ASN.1 DER 1207 // data. The certificates must be concatenated with no intermediate padding. 1208 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { 1209 var v []*certificate 1210 1211 for len(asn1Data) > 0 { 1212 cert := new(certificate) 1213 var err error 1214 asn1Data, err = asn1.Unmarshal(asn1Data, cert) 1215 if err != nil { 1216 return nil, err 1217 } 1218 v = append(v, cert) 1219 } 1220 1221 ret := make([]*Certificate, len(v)) 1222 for i, ci := range v { 1223 cert, err := parseCertificate(ci) 1224 if err != nil { 1225 return nil, err 1226 } 1227 ret[i] = cert 1228 } 1229 1230 return ret, nil 1231 } 1232 1233 func reverseBitsInAByte(in byte) byte { 1234 b1 := in>>4 | in<<4 1235 b2 := b1>>2&0x33 | b1<<2&0xcc 1236 b3 := b2>>1&0x55 | b2<<1&0xaa 1237 return b3 1238 } 1239 1240 var ( 1241 oidExtensionSubjectKeyId = []int{2, 5, 29, 14} 1242 oidExtensionKeyUsage = []int{2, 5, 29, 15} 1243 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} 1244 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} 1245 oidExtensionBasicConstraints = []int{2, 5, 29, 19} 1246 oidExtensionSubjectAltName = []int{2, 5, 29, 17} 1247 oidExtensionCertificatePolicies = []int{2, 5, 29, 32} 1248 oidExtensionNameConstraints = []int{2, 5, 29, 30} 1249 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} 1250 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} 1251 ) 1252 1253 var ( 1254 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 1255 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 1256 ) 1257 1258 // oidNotInExtensions returns whether an extension with the given oid exists in 1259 // extensions. 1260 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 1261 for _, e := range extensions { 1262 if e.Id.Equal(oid) { 1263 return true 1264 } 1265 } 1266 return false 1267 } 1268 1269 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) { 1270 ret = make([]pkix.Extension, 10 /* maximum number of elements. */) 1271 n := 0 1272 1273 if template.KeyUsage != 0 && 1274 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { 1275 ret[n].Id = oidExtensionKeyUsage 1276 ret[n].Critical = true 1277 1278 var a [2]byte 1279 a[0] = reverseBitsInAByte(byte(template.KeyUsage)) 1280 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) 1281 1282 l := 1 1283 if a[1] != 0 { 1284 l = 2 1285 } 1286 1287 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8}) 1288 if err != nil { 1289 return 1290 } 1291 n++ 1292 } 1293 1294 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 1295 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { 1296 ret[n].Id = oidExtensionExtendedKeyUsage 1297 1298 var oids []asn1.ObjectIdentifier 1299 for _, u := range template.ExtKeyUsage { 1300 if oid, ok := oidFromExtKeyUsage(u); ok { 1301 oids = append(oids, oid) 1302 } else { 1303 panic("internal error") 1304 } 1305 } 1306 1307 oids = append(oids, template.UnknownExtKeyUsage...) 1308 1309 ret[n].Value, err = asn1.Marshal(oids) 1310 if err != nil { 1311 return 1312 } 1313 n++ 1314 } 1315 1316 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { 1317 ret[n].Id = oidExtensionBasicConstraints 1318 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen}) 1319 ret[n].Critical = true 1320 if err != nil { 1321 return 1322 } 1323 n++ 1324 } 1325 1326 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { 1327 ret[n].Id = oidExtensionSubjectKeyId 1328 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) 1329 if err != nil { 1330 return 1331 } 1332 n++ 1333 } 1334 1335 if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { 1336 ret[n].Id = oidExtensionAuthorityKeyId 1337 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) 1338 if err != nil { 1339 return 1340 } 1341 n++ 1342 } 1343 1344 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 1345 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { 1346 ret[n].Id = oidExtensionAuthorityInfoAccess 1347 var aiaValues []authorityInfoAccess 1348 for _, name := range template.OCSPServer { 1349 aiaValues = append(aiaValues, authorityInfoAccess{ 1350 Method: oidAuthorityInfoAccessOcsp, 1351 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1352 }) 1353 } 1354 for _, name := range template.IssuingCertificateURL { 1355 aiaValues = append(aiaValues, authorityInfoAccess{ 1356 Method: oidAuthorityInfoAccessIssuers, 1357 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1358 }) 1359 } 1360 ret[n].Value, err = asn1.Marshal(aiaValues) 1361 if err != nil { 1362 return 1363 } 1364 n++ 1365 } 1366 1367 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 1368 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1369 ret[n].Id = oidExtensionSubjectAltName 1370 var rawValues []asn1.RawValue 1371 for _, name := range template.DNSNames { 1372 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) 1373 } 1374 for _, email := range template.EmailAddresses { 1375 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) 1376 } 1377 for _, rawIP := range template.IPAddresses { 1378 // If possible, we always want to encode IPv4 addresses in 4 bytes. 1379 ip := rawIP.To4() 1380 if ip == nil { 1381 ip = rawIP 1382 } 1383 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) 1384 } 1385 ret[n].Value, err = asn1.Marshal(rawValues) 1386 if err != nil { 1387 return 1388 } 1389 n++ 1390 } 1391 1392 if len(template.PolicyIdentifiers) > 0 && 1393 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { 1394 ret[n].Id = oidExtensionCertificatePolicies 1395 policies := make([]policyInformation, len(template.PolicyIdentifiers)) 1396 for i, policy := range template.PolicyIdentifiers { 1397 policies[i].Policy = policy 1398 } 1399 ret[n].Value, err = asn1.Marshal(policies) 1400 if err != nil { 1401 return 1402 } 1403 n++ 1404 } 1405 1406 if len(template.PermittedDNSDomains) > 0 && 1407 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { 1408 ret[n].Id = oidExtensionNameConstraints 1409 ret[n].Critical = template.PermittedDNSDomainsCritical 1410 1411 var out nameConstraints 1412 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains)) 1413 for i, permitted := range template.PermittedDNSDomains { 1414 out.Permitted[i] = generalSubtree{Name: permitted} 1415 } 1416 ret[n].Value, err = asn1.Marshal(out) 1417 if err != nil { 1418 return 1419 } 1420 n++ 1421 } 1422 1423 if len(template.CRLDistributionPoints) > 0 && 1424 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { 1425 ret[n].Id = oidExtensionCRLDistributionPoints 1426 1427 var crlDp []distributionPoint 1428 for _, name := range template.CRLDistributionPoints { 1429 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) 1430 1431 dp := distributionPoint{ 1432 DistributionPoint: distributionPointName{ 1433 FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName}, 1434 }, 1435 } 1436 crlDp = append(crlDp, dp) 1437 } 1438 1439 ret[n].Value, err = asn1.Marshal(crlDp) 1440 if err != nil { 1441 return 1442 } 1443 n++ 1444 } 1445 1446 // Adding another extension here? Remember to update the maximum number 1447 // of elements in the make() at the top of the function. 1448 1449 return append(ret[:n], template.ExtraExtensions...), nil 1450 } 1451 1452 func subjectBytes(cert *Certificate) ([]byte, error) { 1453 if len(cert.RawSubject) > 0 { 1454 return cert.RawSubject, nil 1455 } 1456 1457 return asn1.Marshal(cert.Subject.ToRDNSequence()) 1458 } 1459 1460 // CreateCertificate creates a new certificate based on a template. The 1461 // following members of template are used: SerialNumber, Subject, NotBefore, 1462 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, 1463 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, 1464 // PermittedDNSDomains. 1465 // 1466 // The certificate is signed by parent. If parent is equal to template then the 1467 // certificate is self-signed. The parameter pub is the public key of the 1468 // signee and priv is the private key of the signer. 1469 // 1470 // The returned slice is the certificate in DER encoding. 1471 // 1472 // The only supported key types are RSA and ECDSA (*rsa.PublicKey or 1473 // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv). 1474 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) { 1475 var publicKeyBytes []byte 1476 var publicKeyAlgorithm pkix.AlgorithmIdentifier 1477 1478 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { 1479 return nil, err 1480 } 1481 1482 var signatureAlgorithm pkix.AlgorithmIdentifier 1483 var hashFunc crypto.Hash 1484 1485 switch priv := priv.(type) { 1486 case *rsa.PrivateKey: 1487 signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA 1488 hashFunc = crypto.SHA1 1489 case *ecdsa.PrivateKey: 1490 switch priv.Curve { 1491 case elliptic.P224(), elliptic.P256(): 1492 hashFunc = crypto.SHA256 1493 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256 1494 case elliptic.P384(): 1495 hashFunc = crypto.SHA384 1496 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384 1497 case elliptic.P521(): 1498 hashFunc = crypto.SHA512 1499 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512 1500 default: 1501 return nil, errors.New("x509: unknown elliptic curve") 1502 } 1503 default: 1504 return nil, errors.New("x509: only RSA and ECDSA private keys supported") 1505 } 1506 1507 if err != nil { 1508 return 1509 } 1510 1511 if len(parent.SubjectKeyId) > 0 { 1512 template.AuthorityKeyId = parent.SubjectKeyId 1513 } 1514 1515 extensions, err := buildExtensions(template) 1516 if err != nil { 1517 return 1518 } 1519 1520 asn1Issuer, err := subjectBytes(parent) 1521 if err != nil { 1522 return 1523 } 1524 1525 asn1Subject, err := subjectBytes(template) 1526 if err != nil { 1527 return 1528 } 1529 1530 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 1531 c := tbsCertificate{ 1532 Version: 2, 1533 SerialNumber: template.SerialNumber, 1534 SignatureAlgorithm: signatureAlgorithm, 1535 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 1536 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 1537 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1538 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 1539 Extensions: extensions, 1540 } 1541 1542 tbsCertContents, err := asn1.Marshal(c) 1543 if err != nil { 1544 return 1545 } 1546 1547 c.Raw = tbsCertContents 1548 1549 h := hashFunc.New() 1550 h.Write(tbsCertContents) 1551 digest := h.Sum(nil) 1552 1553 var signature []byte 1554 1555 switch priv := priv.(type) { 1556 case *rsa.PrivateKey: 1557 signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) 1558 case *ecdsa.PrivateKey: 1559 var r, s *big.Int 1560 if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { 1561 signature, err = asn1.Marshal(ecdsaSignature{r, s}) 1562 } 1563 default: 1564 panic("internal error") 1565 } 1566 1567 if err != nil { 1568 return 1569 } 1570 1571 cert, err = asn1.Marshal(certificate{ 1572 nil, 1573 c, 1574 signatureAlgorithm, 1575 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1576 }) 1577 return 1578 } 1579 1580 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded 1581 // CRL. 1582 var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 1583 1584 // pemType is the type of a PEM encoded CRL. 1585 var pemType = "X509 CRL" 1586 1587 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM 1588 // encoded CRLs will appear where they should be DER encoded, so this function 1589 // will transparently handle PEM encoding as long as there isn't any leading 1590 // garbage. 1591 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) { 1592 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 1593 block, _ := pem.Decode(crlBytes) 1594 if block != nil && block.Type == pemType { 1595 crlBytes = block.Bytes 1596 } 1597 } 1598 return ParseDERCRL(crlBytes) 1599 } 1600 1601 // ParseDERCRL parses a DER encoded CRL from the given bytes. 1602 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) { 1603 certList = new(pkix.CertificateList) 1604 _, err = asn1.Unmarshal(derBytes, certList) 1605 if err != nil { 1606 certList = nil 1607 } 1608 return 1609 } 1610 1611 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that 1612 // contains the given list of revoked certificates. 1613 // 1614 // The only supported key type is RSA (*rsa.PrivateKey for priv). 1615 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 1616 rsaPriv, ok := priv.(*rsa.PrivateKey) 1617 if !ok { 1618 return nil, errors.New("x509: non-RSA private keys not supported") 1619 } 1620 tbsCertList := pkix.TBSCertificateList{ 1621 Version: 2, 1622 Signature: pkix.AlgorithmIdentifier{ 1623 Algorithm: oidSignatureSHA1WithRSA, 1624 }, 1625 Issuer: c.Subject.ToRDNSequence(), 1626 ThisUpdate: now.UTC(), 1627 NextUpdate: expiry.UTC(), 1628 RevokedCertificates: revokedCerts, 1629 } 1630 1631 tbsCertListContents, err := asn1.Marshal(tbsCertList) 1632 if err != nil { 1633 return 1634 } 1635 1636 h := sha1.New() 1637 h.Write(tbsCertListContents) 1638 digest := h.Sum(nil) 1639 1640 signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest) 1641 if err != nil { 1642 return 1643 } 1644 1645 return asn1.Marshal(pkix.CertificateList{ 1646 TBSCertList: tbsCertList, 1647 SignatureAlgorithm: pkix.AlgorithmIdentifier{ 1648 Algorithm: oidSignatureSHA1WithRSA, 1649 }, 1650 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1651 }) 1652 }