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