rsc.io/go@v0.0.0-20150416155037-e040fd465409/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 failIfCritical := false 895 896 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { 897 switch e.Id[3] { 898 case 15: 899 // RFC 5280, 4.2.1.3 900 var usageBits asn1.BitString 901 if _, err := asn1.Unmarshal(e.Value, &usageBits); err != nil { 902 return nil, err 903 } 904 905 var usage int 906 for i := 0; i < 9; i++ { 907 if usageBits.At(i) != 0 { 908 usage |= 1 << uint(i) 909 } 910 } 911 out.KeyUsage = KeyUsage(usage) 912 913 case 19: 914 // RFC 5280, 4.2.1.9 915 var constraints basicConstraints 916 if _, err := asn1.Unmarshal(e.Value, &constraints); err != nil { 917 return nil, err 918 } 919 920 out.BasicConstraintsValid = true 921 out.IsCA = constraints.IsCA 922 out.MaxPathLen = constraints.MaxPathLen 923 out.MaxPathLenZero = out.MaxPathLen == 0 924 925 case 17: 926 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value) 927 if err != nil { 928 return nil, err 929 } 930 931 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 { 932 // If we didn't parse anything then we do the critical check, below. 933 failIfCritical = true 934 } 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 if _, err := asn1.Unmarshal(e.Value, &constraints); err != nil { 954 return nil, err 955 } 956 957 if len(constraints.Excluded) > 0 && e.Critical { 958 return out, UnhandledCriticalExtension{} 959 } 960 961 for _, subtree := range constraints.Permitted { 962 if len(subtree.Name) == 0 { 963 if e.Critical { 964 return out, UnhandledCriticalExtension{} 965 } 966 continue 967 } 968 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name) 969 } 970 971 case 31: 972 // RFC 5280, 4.2.1.14 973 974 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 975 // 976 // DistributionPoint ::= SEQUENCE { 977 // distributionPoint [0] DistributionPointName OPTIONAL, 978 // reasons [1] ReasonFlags OPTIONAL, 979 // cRLIssuer [2] GeneralNames OPTIONAL } 980 // 981 // DistributionPointName ::= CHOICE { 982 // fullName [0] GeneralNames, 983 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 984 985 var cdp []distributionPoint 986 if _, err := asn1.Unmarshal(e.Value, &cdp); err != nil { 987 return nil, err 988 } 989 990 for _, dp := range cdp { 991 var n asn1.RawValue 992 if _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n); err != nil { 993 return nil, err 994 } 995 996 if n.Tag == 6 { 997 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) 998 } 999 } 1000 1001 case 35: 1002 // RFC 5280, 4.2.1.1 1003 var a authKeyId 1004 if _, err = asn1.Unmarshal(e.Value, &a); err != nil { 1005 return nil, err 1006 } 1007 out.AuthorityKeyId = a.Id 1008 1009 case 37: 1010 // RFC 5280, 4.2.1.12. Extended Key Usage 1011 1012 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } 1013 // 1014 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId 1015 // 1016 // KeyPurposeId ::= OBJECT IDENTIFIER 1017 1018 var keyUsage []asn1.ObjectIdentifier 1019 if _, err = asn1.Unmarshal(e.Value, &keyUsage); err != nil { 1020 return nil, err 1021 } 1022 1023 for _, u := range keyUsage { 1024 if extKeyUsage, ok := extKeyUsageFromOID(u); ok { 1025 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) 1026 } else { 1027 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) 1028 } 1029 } 1030 1031 case 14: 1032 // RFC 5280, 4.2.1.2 1033 var keyid []byte 1034 if _, err = asn1.Unmarshal(e.Value, &keyid); err != nil { 1035 return nil, err 1036 } 1037 out.SubjectKeyId = keyid 1038 1039 case 32: 1040 // RFC 5280 4.2.1.4: Certificate Policies 1041 var policies []policyInformation 1042 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { 1043 return nil, err 1044 } 1045 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) 1046 for i, policy := range policies { 1047 out.PolicyIdentifiers[i] = policy.Policy 1048 } 1049 1050 default: 1051 // Unknown extensions cause an error if marked as critical. 1052 failIfCritical = true 1053 } 1054 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { 1055 // RFC 5280 4.2.2.1: Authority Information Access 1056 var aia []authorityInfoAccess 1057 if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { 1058 return nil, err 1059 } 1060 1061 for _, v := range aia { 1062 // GeneralName: uniformResourceIdentifier [6] IA5String 1063 if v.Location.Tag != 6 { 1064 continue 1065 } 1066 if v.Method.Equal(oidAuthorityInfoAccessOcsp) { 1067 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) 1068 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { 1069 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) 1070 } 1071 } 1072 } else { 1073 // Unknown extensions cause an error if marked as critical. 1074 failIfCritical = true 1075 } 1076 1077 if e.Critical && failIfCritical { 1078 return out, UnhandledCriticalExtension{} 1079 } 1080 } 1081 1082 return out, nil 1083 } 1084 1085 // ParseCertificate parses a single certificate from the given ASN.1 DER data. 1086 func ParseCertificate(asn1Data []byte) (*Certificate, error) { 1087 var cert certificate 1088 rest, err := asn1.Unmarshal(asn1Data, &cert) 1089 if err != nil { 1090 return nil, err 1091 } 1092 if len(rest) > 0 { 1093 return nil, asn1.SyntaxError{Msg: "trailing data"} 1094 } 1095 1096 return parseCertificate(&cert) 1097 } 1098 1099 // ParseCertificates parses one or more certificates from the given ASN.1 DER 1100 // data. The certificates must be concatenated with no intermediate padding. 1101 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { 1102 var v []*certificate 1103 1104 for len(asn1Data) > 0 { 1105 cert := new(certificate) 1106 var err error 1107 asn1Data, err = asn1.Unmarshal(asn1Data, cert) 1108 if err != nil { 1109 return nil, err 1110 } 1111 v = append(v, cert) 1112 } 1113 1114 ret := make([]*Certificate, len(v)) 1115 for i, ci := range v { 1116 cert, err := parseCertificate(ci) 1117 if err != nil { 1118 return nil, err 1119 } 1120 ret[i] = cert 1121 } 1122 1123 return ret, nil 1124 } 1125 1126 func reverseBitsInAByte(in byte) byte { 1127 b1 := in>>4 | in<<4 1128 b2 := b1>>2&0x33 | b1<<2&0xcc 1129 b3 := b2>>1&0x55 | b2<<1&0xaa 1130 return b3 1131 } 1132 1133 // asn1BitLength returns the bit-length of bitString by considering the 1134 // most-significant bit in a byte to be the "first" bit. This convention 1135 // matches ASN.1, but differs from almost everything else. 1136 func asn1BitLength(bitString []byte) int { 1137 bitLen := len(bitString) * 8 1138 1139 for i := range bitString { 1140 b := bitString[len(bitString)-i-1] 1141 1142 for bit := uint(0); bit < 8; bit++ { 1143 if (b>>bit)&1 == 1 { 1144 return bitLen 1145 } 1146 bitLen-- 1147 } 1148 } 1149 1150 return 0 1151 } 1152 1153 var ( 1154 oidExtensionSubjectKeyId = []int{2, 5, 29, 14} 1155 oidExtensionKeyUsage = []int{2, 5, 29, 15} 1156 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} 1157 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} 1158 oidExtensionBasicConstraints = []int{2, 5, 29, 19} 1159 oidExtensionSubjectAltName = []int{2, 5, 29, 17} 1160 oidExtensionCertificatePolicies = []int{2, 5, 29, 32} 1161 oidExtensionNameConstraints = []int{2, 5, 29, 30} 1162 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} 1163 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} 1164 ) 1165 1166 var ( 1167 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 1168 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 1169 ) 1170 1171 // oidNotInExtensions returns whether an extension with the given oid exists in 1172 // extensions. 1173 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 1174 for _, e := range extensions { 1175 if e.Id.Equal(oid) { 1176 return true 1177 } 1178 } 1179 return false 1180 } 1181 1182 // marshalSANs marshals a list of addresses into a the contents of an X.509 1183 // SubjectAlternativeName extension. 1184 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { 1185 var rawValues []asn1.RawValue 1186 for _, name := range dnsNames { 1187 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) 1188 } 1189 for _, email := range emailAddresses { 1190 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) 1191 } 1192 for _, rawIP := range ipAddresses { 1193 // If possible, we always want to encode IPv4 addresses in 4 bytes. 1194 ip := rawIP.To4() 1195 if ip == nil { 1196 ip = rawIP 1197 } 1198 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) 1199 } 1200 return asn1.Marshal(rawValues) 1201 } 1202 1203 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) { 1204 ret = make([]pkix.Extension, 10 /* maximum number of elements. */) 1205 n := 0 1206 1207 if template.KeyUsage != 0 && 1208 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { 1209 ret[n].Id = oidExtensionKeyUsage 1210 ret[n].Critical = true 1211 1212 var a [2]byte 1213 a[0] = reverseBitsInAByte(byte(template.KeyUsage)) 1214 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) 1215 1216 l := 1 1217 if a[1] != 0 { 1218 l = 2 1219 } 1220 1221 bitString := a[:l] 1222 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)}) 1223 if err != nil { 1224 return 1225 } 1226 n++ 1227 } 1228 1229 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 1230 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { 1231 ret[n].Id = oidExtensionExtendedKeyUsage 1232 1233 var oids []asn1.ObjectIdentifier 1234 for _, u := range template.ExtKeyUsage { 1235 if oid, ok := oidFromExtKeyUsage(u); ok { 1236 oids = append(oids, oid) 1237 } else { 1238 panic("internal error") 1239 } 1240 } 1241 1242 oids = append(oids, template.UnknownExtKeyUsage...) 1243 1244 ret[n].Value, err = asn1.Marshal(oids) 1245 if err != nil { 1246 return 1247 } 1248 n++ 1249 } 1250 1251 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { 1252 // Leaving MaxPathLen as zero indicates that no maximum path 1253 // length is desired, unless MaxPathLenZero is set. A value of 1254 // -1 causes encoding/asn1 to omit the value as desired. 1255 maxPathLen := template.MaxPathLen 1256 if maxPathLen == 0 && !template.MaxPathLenZero { 1257 maxPathLen = -1 1258 } 1259 ret[n].Id = oidExtensionBasicConstraints 1260 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen}) 1261 ret[n].Critical = true 1262 if err != nil { 1263 return 1264 } 1265 n++ 1266 } 1267 1268 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { 1269 ret[n].Id = oidExtensionSubjectKeyId 1270 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) 1271 if err != nil { 1272 return 1273 } 1274 n++ 1275 } 1276 1277 if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { 1278 ret[n].Id = oidExtensionAuthorityKeyId 1279 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) 1280 if err != nil { 1281 return 1282 } 1283 n++ 1284 } 1285 1286 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 1287 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { 1288 ret[n].Id = oidExtensionAuthorityInfoAccess 1289 var aiaValues []authorityInfoAccess 1290 for _, name := range template.OCSPServer { 1291 aiaValues = append(aiaValues, authorityInfoAccess{ 1292 Method: oidAuthorityInfoAccessOcsp, 1293 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1294 }) 1295 } 1296 for _, name := range template.IssuingCertificateURL { 1297 aiaValues = append(aiaValues, authorityInfoAccess{ 1298 Method: oidAuthorityInfoAccessIssuers, 1299 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1300 }) 1301 } 1302 ret[n].Value, err = asn1.Marshal(aiaValues) 1303 if err != nil { 1304 return 1305 } 1306 n++ 1307 } 1308 1309 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 1310 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1311 ret[n].Id = oidExtensionSubjectAltName 1312 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 1313 if err != nil { 1314 return 1315 } 1316 n++ 1317 } 1318 1319 if len(template.PolicyIdentifiers) > 0 && 1320 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { 1321 ret[n].Id = oidExtensionCertificatePolicies 1322 policies := make([]policyInformation, len(template.PolicyIdentifiers)) 1323 for i, policy := range template.PolicyIdentifiers { 1324 policies[i].Policy = policy 1325 } 1326 ret[n].Value, err = asn1.Marshal(policies) 1327 if err != nil { 1328 return 1329 } 1330 n++ 1331 } 1332 1333 if len(template.PermittedDNSDomains) > 0 && 1334 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { 1335 ret[n].Id = oidExtensionNameConstraints 1336 ret[n].Critical = template.PermittedDNSDomainsCritical 1337 1338 var out nameConstraints 1339 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains)) 1340 for i, permitted := range template.PermittedDNSDomains { 1341 out.Permitted[i] = generalSubtree{Name: permitted} 1342 } 1343 ret[n].Value, err = asn1.Marshal(out) 1344 if err != nil { 1345 return 1346 } 1347 n++ 1348 } 1349 1350 if len(template.CRLDistributionPoints) > 0 && 1351 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { 1352 ret[n].Id = oidExtensionCRLDistributionPoints 1353 1354 var crlDp []distributionPoint 1355 for _, name := range template.CRLDistributionPoints { 1356 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) 1357 1358 dp := distributionPoint{ 1359 DistributionPoint: distributionPointName{ 1360 FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName}, 1361 }, 1362 } 1363 crlDp = append(crlDp, dp) 1364 } 1365 1366 ret[n].Value, err = asn1.Marshal(crlDp) 1367 if err != nil { 1368 return 1369 } 1370 n++ 1371 } 1372 1373 // Adding another extension here? Remember to update the maximum number 1374 // of elements in the make() at the top of the function. 1375 1376 return append(ret[:n], template.ExtraExtensions...), nil 1377 } 1378 1379 func subjectBytes(cert *Certificate) ([]byte, error) { 1380 if len(cert.RawSubject) > 0 { 1381 return cert.RawSubject, nil 1382 } 1383 1384 return asn1.Marshal(cert.Subject.ToRDNSequence()) 1385 } 1386 1387 // signingParamsForPublicKey returns the parameters to use for signing with 1388 // priv. If requestedSigAlgo is not zero then it overrides the default 1389 // signature algorithm. 1390 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { 1391 var pubType PublicKeyAlgorithm 1392 1393 switch pub := pub.(type) { 1394 case *rsa.PublicKey: 1395 pubType = RSA 1396 hashFunc = crypto.SHA256 1397 sigAlgo.Algorithm = oidSignatureSHA256WithRSA 1398 sigAlgo.Parameters = asn1.RawValue{ 1399 Tag: 5, 1400 } 1401 1402 case *ecdsa.PublicKey: 1403 pubType = ECDSA 1404 1405 switch pub.Curve { 1406 case elliptic.P224(), elliptic.P256(): 1407 hashFunc = crypto.SHA256 1408 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 1409 case elliptic.P384(): 1410 hashFunc = crypto.SHA384 1411 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 1412 case elliptic.P521(): 1413 hashFunc = crypto.SHA512 1414 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 1415 default: 1416 err = errors.New("x509: unknown elliptic curve") 1417 } 1418 1419 default: 1420 err = errors.New("x509: only RSA and ECDSA keys supported") 1421 } 1422 1423 if err != nil { 1424 return 1425 } 1426 1427 if requestedSigAlgo == 0 { 1428 return 1429 } 1430 1431 found := false 1432 for _, details := range signatureAlgorithmDetails { 1433 if details.algo == requestedSigAlgo { 1434 if details.pubKeyAlgo != pubType { 1435 err = errors.New("x509: requested SignatureAlgorithm does not match private key type") 1436 return 1437 } 1438 sigAlgo.Algorithm, hashFunc = details.oid, details.hash 1439 if hashFunc == 0 { 1440 err = errors.New("x509: cannot sign with hash function requested") 1441 return 1442 } 1443 found = true 1444 break 1445 } 1446 } 1447 1448 if !found { 1449 err = errors.New("x509: unknown SignatureAlgorithm") 1450 } 1451 1452 return 1453 } 1454 1455 // CreateCertificate creates a new certificate based on a template. The 1456 // following members of template are used: SerialNumber, Subject, NotBefore, 1457 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, 1458 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, 1459 // PermittedDNSDomains, SignatureAlgorithm. 1460 // 1461 // The certificate is signed by parent. If parent is equal to template then the 1462 // certificate is self-signed. The parameter pub is the public key of the 1463 // signee and priv is the private key of the signer. 1464 // 1465 // The returned slice is the certificate in DER encoding. 1466 // 1467 // All keys types that are implemented via crypto.Signer are supported (This 1468 // includes *rsa.PublicKey and *ecdsa.PublicKey.) 1469 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) { 1470 key, ok := priv.(crypto.Signer) 1471 if !ok { 1472 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 1473 } 1474 1475 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 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 len(parent.SubjectKeyId) > 0 { 1486 template.AuthorityKeyId = parent.SubjectKeyId 1487 } 1488 1489 extensions, err := buildExtensions(template) 1490 if err != nil { 1491 return 1492 } 1493 1494 asn1Issuer, err := subjectBytes(parent) 1495 if err != nil { 1496 return 1497 } 1498 1499 asn1Subject, err := subjectBytes(template) 1500 if err != nil { 1501 return 1502 } 1503 1504 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 1505 c := tbsCertificate{ 1506 Version: 2, 1507 SerialNumber: template.SerialNumber, 1508 SignatureAlgorithm: signatureAlgorithm, 1509 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 1510 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 1511 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1512 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 1513 Extensions: extensions, 1514 } 1515 1516 tbsCertContents, err := asn1.Marshal(c) 1517 if err != nil { 1518 return 1519 } 1520 1521 c.Raw = tbsCertContents 1522 1523 h := hashFunc.New() 1524 h.Write(tbsCertContents) 1525 digest := h.Sum(nil) 1526 1527 var signature []byte 1528 signature, err = key.Sign(rand, digest, hashFunc) 1529 if err != nil { 1530 return 1531 } 1532 1533 return asn1.Marshal(certificate{ 1534 nil, 1535 c, 1536 signatureAlgorithm, 1537 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1538 }) 1539 } 1540 1541 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded 1542 // CRL. 1543 var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 1544 1545 // pemType is the type of a PEM encoded CRL. 1546 var pemType = "X509 CRL" 1547 1548 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM 1549 // encoded CRLs will appear where they should be DER encoded, so this function 1550 // will transparently handle PEM encoding as long as there isn't any leading 1551 // garbage. 1552 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) { 1553 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 1554 block, _ := pem.Decode(crlBytes) 1555 if block != nil && block.Type == pemType { 1556 crlBytes = block.Bytes 1557 } 1558 } 1559 return ParseDERCRL(crlBytes) 1560 } 1561 1562 // ParseDERCRL parses a DER encoded CRL from the given bytes. 1563 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) { 1564 certList = new(pkix.CertificateList) 1565 _, err = asn1.Unmarshal(derBytes, certList) 1566 if err != nil { 1567 certList = nil 1568 } 1569 return 1570 } 1571 1572 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that 1573 // contains the given list of revoked certificates. 1574 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 1575 key, ok := priv.(crypto.Signer) 1576 if !ok { 1577 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 1578 } 1579 1580 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) 1581 if err != nil { 1582 return nil, err 1583 } 1584 1585 tbsCertList := pkix.TBSCertificateList{ 1586 Version: 1, 1587 Signature: signatureAlgorithm, 1588 Issuer: c.Subject.ToRDNSequence(), 1589 ThisUpdate: now.UTC(), 1590 NextUpdate: expiry.UTC(), 1591 RevokedCertificates: revokedCerts, 1592 } 1593 1594 // Authority Key Id 1595 if len(c.SubjectKeyId) > 0 { 1596 var aki pkix.Extension 1597 aki.Id = oidExtensionAuthorityKeyId 1598 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) 1599 if err != nil { 1600 return 1601 } 1602 tbsCertList.Extensions = append(tbsCertList.Extensions, aki) 1603 } 1604 1605 tbsCertListContents, err := asn1.Marshal(tbsCertList) 1606 if err != nil { 1607 return 1608 } 1609 1610 h := hashFunc.New() 1611 h.Write(tbsCertListContents) 1612 digest := h.Sum(nil) 1613 1614 var signature []byte 1615 signature, err = key.Sign(rand, digest, hashFunc) 1616 if err != nil { 1617 return 1618 } 1619 1620 return asn1.Marshal(pkix.CertificateList{ 1621 TBSCertList: tbsCertList, 1622 SignatureAlgorithm: signatureAlgorithm, 1623 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1624 }) 1625 } 1626 1627 // CertificateRequest represents a PKCS #10, certificate signature request. 1628 type CertificateRequest struct { 1629 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). 1630 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. 1631 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 1632 RawSubject []byte // DER encoded Subject. 1633 1634 Version int 1635 Signature []byte 1636 SignatureAlgorithm SignatureAlgorithm 1637 1638 PublicKeyAlgorithm PublicKeyAlgorithm 1639 PublicKey interface{} 1640 1641 Subject pkix.Name 1642 1643 // Attributes is a collection of attributes providing 1644 // additional information about the subject of the certificate. 1645 // See RFC 2986 section 4.1. 1646 Attributes []pkix.AttributeTypeAndValueSET 1647 1648 // Extensions contains raw X.509 extensions. When parsing CSRs, this 1649 // can be used to extract extensions that are not parsed by this 1650 // package. 1651 Extensions []pkix.Extension 1652 1653 // ExtraExtensions contains extensions to be copied, raw, into any 1654 // marshaled CSR. Values override any extensions that would otherwise 1655 // be produced based on the other fields but are overridden by any 1656 // extensions specified in Attributes. 1657 // 1658 // The ExtraExtensions field is not populated when parsing CSRs, see 1659 // Extensions. 1660 ExtraExtensions []pkix.Extension 1661 1662 // Subject Alternate Name values. 1663 DNSNames []string 1664 EmailAddresses []string 1665 IPAddresses []net.IP 1666 } 1667 1668 // These structures reflect the ASN.1 structure of X.509 certificate 1669 // signature requests (see RFC 2986): 1670 1671 type tbsCertificateRequest struct { 1672 Raw asn1.RawContent 1673 Version int 1674 Subject asn1.RawValue 1675 PublicKey publicKeyInfo 1676 RawAttributes []asn1.RawValue `asn1:"tag:0"` 1677 } 1678 1679 type certificateRequest struct { 1680 Raw asn1.RawContent 1681 TBSCSR tbsCertificateRequest 1682 SignatureAlgorithm pkix.AlgorithmIdentifier 1683 SignatureValue asn1.BitString 1684 } 1685 1686 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested 1687 // extensions in a CSR. 1688 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} 1689 1690 // newRawAttributes converts AttributeTypeAndValueSETs from a template 1691 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes. 1692 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { 1693 var rawAttributes []asn1.RawValue 1694 b, err := asn1.Marshal(attributes) 1695 rest, err := asn1.Unmarshal(b, &rawAttributes) 1696 if err != nil { 1697 return nil, err 1698 } 1699 if len(rest) != 0 { 1700 return nil, errors.New("x509: failed to unmarshall raw CSR Attributes") 1701 } 1702 return rawAttributes, nil 1703 } 1704 1705 // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs. 1706 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { 1707 var attributes []pkix.AttributeTypeAndValueSET 1708 for _, rawAttr := range rawAttributes { 1709 var attr pkix.AttributeTypeAndValueSET 1710 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) 1711 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET 1712 // (i.e.: challengePassword or unstructuredName). 1713 if err == nil && len(rest) == 0 { 1714 attributes = append(attributes, attr) 1715 } 1716 } 1717 return attributes 1718 } 1719 1720 // CreateCertificateRequest creates a new certificate based on a template. The 1721 // following members of template are used: Subject, Attributes, 1722 // SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses. 1723 // The private key is the private key of the signer. 1724 // 1725 // The returned slice is the certificate request in DER encoding. 1726 // 1727 // All keys types that are implemented via crypto.Signer are supported (This 1728 // includes *rsa.PublicKey and *ecdsa.PublicKey.) 1729 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { 1730 key, ok := priv.(crypto.Signer) 1731 if !ok { 1732 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 1733 } 1734 1735 var hashFunc crypto.Hash 1736 var sigAlgo pkix.AlgorithmIdentifier 1737 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 1738 if err != nil { 1739 return nil, err 1740 } 1741 1742 var publicKeyBytes []byte 1743 var publicKeyAlgorithm pkix.AlgorithmIdentifier 1744 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public()) 1745 if err != nil { 1746 return nil, err 1747 } 1748 1749 var extensions []pkix.Extension 1750 1751 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 1752 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1753 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 1754 if err != nil { 1755 return nil, err 1756 } 1757 1758 extensions = append(extensions, pkix.Extension{ 1759 Id: oidExtensionSubjectAltName, 1760 Value: sanBytes, 1761 }) 1762 } 1763 1764 extensions = append(extensions, template.ExtraExtensions...) 1765 1766 var attributes []pkix.AttributeTypeAndValueSET 1767 attributes = append(attributes, template.Attributes...) 1768 1769 if len(extensions) > 0 { 1770 // specifiedExtensions contains all the extensions that we 1771 // found specified via template.Attributes. 1772 specifiedExtensions := make(map[string]bool) 1773 1774 for _, atvSet := range template.Attributes { 1775 if !atvSet.Type.Equal(oidExtensionRequest) { 1776 continue 1777 } 1778 1779 for _, atvs := range atvSet.Value { 1780 for _, atv := range atvs { 1781 specifiedExtensions[atv.Type.String()] = true 1782 } 1783 } 1784 } 1785 1786 atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions)) 1787 for _, e := range extensions { 1788 if specifiedExtensions[e.Id.String()] { 1789 // Attributes already contained a value for 1790 // this extension and it takes priority. 1791 continue 1792 } 1793 1794 atvs = append(atvs, pkix.AttributeTypeAndValue{ 1795 // There is no place for the critical flag in a CSR. 1796 Type: e.Id, 1797 Value: e.Value, 1798 }) 1799 } 1800 1801 // Append the extensions to an existing attribute if possible. 1802 appended := false 1803 for _, atvSet := range attributes { 1804 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { 1805 continue 1806 } 1807 1808 atvSet.Value[0] = append(atvSet.Value[0], atvs...) 1809 appended = true 1810 break 1811 } 1812 1813 // Otherwise, add a new attribute for the extensions. 1814 if !appended { 1815 attributes = append(attributes, pkix.AttributeTypeAndValueSET{ 1816 Type: oidExtensionRequest, 1817 Value: [][]pkix.AttributeTypeAndValue{ 1818 atvs, 1819 }, 1820 }) 1821 } 1822 } 1823 1824 asn1Subject := template.RawSubject 1825 if len(asn1Subject) == 0 { 1826 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) 1827 if err != nil { 1828 return 1829 } 1830 } 1831 1832 rawAttributes, err := newRawAttributes(attributes) 1833 if err != nil { 1834 return 1835 } 1836 1837 tbsCSR := tbsCertificateRequest{ 1838 Version: 0, // PKCS #10, RFC 2986 1839 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1840 PublicKey: publicKeyInfo{ 1841 Algorithm: publicKeyAlgorithm, 1842 PublicKey: asn1.BitString{ 1843 Bytes: publicKeyBytes, 1844 BitLength: len(publicKeyBytes) * 8, 1845 }, 1846 }, 1847 RawAttributes: rawAttributes, 1848 } 1849 1850 tbsCSRContents, err := asn1.Marshal(tbsCSR) 1851 if err != nil { 1852 return 1853 } 1854 tbsCSR.Raw = tbsCSRContents 1855 1856 h := hashFunc.New() 1857 h.Write(tbsCSRContents) 1858 digest := h.Sum(nil) 1859 1860 var signature []byte 1861 signature, err = key.Sign(rand, digest, hashFunc) 1862 if err != nil { 1863 return 1864 } 1865 1866 return asn1.Marshal(certificateRequest{ 1867 TBSCSR: tbsCSR, 1868 SignatureAlgorithm: sigAlgo, 1869 SignatureValue: asn1.BitString{ 1870 Bytes: signature, 1871 BitLength: len(signature) * 8, 1872 }, 1873 }) 1874 } 1875 1876 // ParseCertificateRequest parses a single certificate request from the 1877 // given ASN.1 DER data. 1878 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { 1879 var csr certificateRequest 1880 1881 rest, err := asn1.Unmarshal(asn1Data, &csr) 1882 if err != nil { 1883 return nil, err 1884 } else if len(rest) != 0 { 1885 return nil, asn1.SyntaxError{Msg: "trailing data"} 1886 } 1887 1888 return parseCertificateRequest(&csr) 1889 } 1890 1891 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { 1892 out := &CertificateRequest{ 1893 Raw: in.Raw, 1894 RawTBSCertificateRequest: in.TBSCSR.Raw, 1895 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, 1896 RawSubject: in.TBSCSR.Subject.FullBytes, 1897 1898 Signature: in.SignatureValue.RightAlign(), 1899 SignatureAlgorithm: getSignatureAlgorithmFromOID(in.SignatureAlgorithm.Algorithm), 1900 1901 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), 1902 1903 Version: in.TBSCSR.Version, 1904 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes), 1905 } 1906 1907 var err error 1908 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey) 1909 if err != nil { 1910 return nil, err 1911 } 1912 1913 var subject pkix.RDNSequence 1914 if _, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { 1915 return nil, err 1916 } 1917 1918 out.Subject.FillFromRDNSequence(&subject) 1919 1920 var extensions []pkix.AttributeTypeAndValue 1921 1922 for _, atvSet := range out.Attributes { 1923 if !atvSet.Type.Equal(oidExtensionRequest) { 1924 continue 1925 } 1926 1927 for _, atvs := range atvSet.Value { 1928 extensions = append(extensions, atvs...) 1929 } 1930 } 1931 1932 out.Extensions = make([]pkix.Extension, 0, len(extensions)) 1933 1934 for _, e := range extensions { 1935 value, ok := e.Value.([]byte) 1936 if !ok { 1937 return nil, errors.New("x509: extension attribute contained non-OCTET STRING data") 1938 } 1939 1940 out.Extensions = append(out.Extensions, pkix.Extension{ 1941 Id: e.Type, 1942 Value: value, 1943 }) 1944 1945 if len(e.Type) == 4 && e.Type[0] == 2 && e.Type[1] == 5 && e.Type[2] == 29 { 1946 switch e.Type[3] { 1947 case 17: 1948 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(value) 1949 if err != nil { 1950 return nil, err 1951 } 1952 } 1953 } 1954 } 1955 1956 return out, nil 1957 }