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