github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/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 498 SubjectKeyId []byte 499 AuthorityKeyId []byte 500 501 // RFC 5280, 4.2.2.1 (Authority Information Access) 502 OCSPServer []string 503 IssuingCertificateURL []string 504 505 // Subject Alternate Name values 506 DNSNames []string 507 EmailAddresses []string 508 IPAddresses []net.IP 509 510 // Name constraints 511 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. 512 PermittedDNSDomains []string 513 514 // CRL Distribution Points 515 CRLDistributionPoints []string 516 517 PolicyIdentifiers []asn1.ObjectIdentifier 518 } 519 520 // ErrUnsupportedAlgorithm results from attempting to perform an operation that 521 // involves algorithms that are not currently implemented. 522 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") 523 524 // ConstraintViolationError results when a requested usage is not permitted by 525 // a certificate. For example: checking a signature when the public key isn't a 526 // certificate signing key. 527 type ConstraintViolationError struct{} 528 529 func (ConstraintViolationError) Error() string { 530 return "x509: invalid signature: parent certificate cannot sign this kind of certificate" 531 } 532 533 func (c *Certificate) Equal(other *Certificate) bool { 534 return bytes.Equal(c.Raw, other.Raw) 535 } 536 537 // Entrust have a broken root certificate (CN=Entrust.net Certification 538 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid 539 // according to PKIX. 540 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it 541 // from the Basic Constraints requirement. 542 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 543 // 544 // TODO(agl): remove this hack once their reissued root is sufficiently 545 // widespread. 546 var entrustBrokenSPKI = []byte{ 547 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 548 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 549 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 550 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 551 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, 552 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, 553 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, 554 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, 555 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, 556 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, 557 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, 558 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, 559 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, 560 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, 561 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, 562 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, 563 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, 564 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, 565 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, 566 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, 567 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, 568 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, 569 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, 570 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, 571 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, 572 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, 573 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, 574 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, 575 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, 576 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, 577 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, 578 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, 579 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, 580 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, 581 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, 582 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, 583 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, 584 } 585 586 // CheckSignatureFrom verifies that the signature on c is a valid signature 587 // from parent. 588 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) { 589 // RFC 5280, 4.2.1.9: 590 // "If the basic constraints extension is not present in a version 3 591 // certificate, or the extension is present but the cA boolean is not 592 // asserted, then the certified public key MUST NOT be used to verify 593 // certificate signatures." 594 // (except for Entrust, see comment above entrustBrokenSPKI) 595 if (parent.Version == 3 && !parent.BasicConstraintsValid || 596 parent.BasicConstraintsValid && !parent.IsCA) && 597 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { 598 return ConstraintViolationError{} 599 } 600 601 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { 602 return ConstraintViolationError{} 603 } 604 605 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 606 return ErrUnsupportedAlgorithm 607 } 608 609 // TODO(agl): don't ignore the path length constraint. 610 611 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) 612 } 613 614 // CheckSignature verifies that signature is a valid signature over signed from 615 // c's public key. 616 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) { 617 var hashType crypto.Hash 618 619 switch algo { 620 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1: 621 hashType = crypto.SHA1 622 case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256: 623 hashType = crypto.SHA256 624 case SHA384WithRSA, ECDSAWithSHA384: 625 hashType = crypto.SHA384 626 case SHA512WithRSA, ECDSAWithSHA512: 627 hashType = crypto.SHA512 628 default: 629 return ErrUnsupportedAlgorithm 630 } 631 632 if !hashType.Available() { 633 return ErrUnsupportedAlgorithm 634 } 635 h := hashType.New() 636 637 h.Write(signed) 638 digest := h.Sum(nil) 639 640 switch pub := c.PublicKey.(type) { 641 case *rsa.PublicKey: 642 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) 643 case *dsa.PublicKey: 644 dsaSig := new(dsaSignature) 645 if _, err := asn1.Unmarshal(signature, dsaSig); err != nil { 646 return err 647 } 648 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { 649 return errors.New("x509: DSA signature contained zero or negative values") 650 } 651 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { 652 return errors.New("x509: DSA verification failure") 653 } 654 return 655 case *ecdsa.PublicKey: 656 ecdsaSig := new(ecdsaSignature) 657 if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { 658 return err 659 } 660 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { 661 return errors.New("x509: ECDSA signature contained zero or negative values") 662 } 663 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { 664 return errors.New("x509: ECDSA verification failure") 665 } 666 return 667 } 668 return ErrUnsupportedAlgorithm 669 } 670 671 // CheckCRLSignature checks that the signature in crl is from c. 672 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) { 673 algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm) 674 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) 675 } 676 677 type UnhandledCriticalExtension struct{} 678 679 func (h UnhandledCriticalExtension) Error() string { 680 return "x509: unhandled critical extension" 681 } 682 683 type basicConstraints struct { 684 IsCA bool `asn1:"optional"` 685 MaxPathLen int `asn1:"optional,default:-1"` 686 } 687 688 // RFC 5280 4.2.1.4 689 type policyInformation struct { 690 Policy asn1.ObjectIdentifier 691 // policyQualifiers omitted 692 } 693 694 // RFC 5280, 4.2.1.10 695 type nameConstraints struct { 696 Permitted []generalSubtree `asn1:"optional,tag:0"` 697 Excluded []generalSubtree `asn1:"optional,tag:1"` 698 } 699 700 type generalSubtree struct { 701 Name string `asn1:"tag:2,optional,ia5"` 702 } 703 704 // RFC 5280, 4.2.2.1 705 type authorityInfoAccess struct { 706 Method asn1.ObjectIdentifier 707 Location asn1.RawValue 708 } 709 710 // RFC 5280, 4.2.1.14 711 type distributionPoint struct { 712 DistributionPoint distributionPointName `asn1:"optional,tag:0"` 713 Reason asn1.BitString `asn1:"optional,tag:1"` 714 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` 715 } 716 717 type distributionPointName struct { 718 FullName asn1.RawValue `asn1:"optional,tag:0"` 719 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` 720 } 721 722 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { 723 asn1Data := keyData.PublicKey.RightAlign() 724 switch algo { 725 case RSA: 726 p := new(rsaPublicKey) 727 _, err := asn1.Unmarshal(asn1Data, p) 728 if err != nil { 729 return nil, err 730 } 731 732 if p.N.Sign() <= 0 { 733 return nil, errors.New("x509: RSA modulus is not a positive number") 734 } 735 if p.E <= 0 { 736 return nil, errors.New("x509: RSA public exponent is not a positive number") 737 } 738 739 pub := &rsa.PublicKey{ 740 E: p.E, 741 N: p.N, 742 } 743 return pub, nil 744 case DSA: 745 var p *big.Int 746 _, err := asn1.Unmarshal(asn1Data, &p) 747 if err != nil { 748 return nil, err 749 } 750 paramsData := keyData.Algorithm.Parameters.FullBytes 751 params := new(dsaAlgorithmParameters) 752 _, err = asn1.Unmarshal(paramsData, params) 753 if err != nil { 754 return nil, err 755 } 756 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { 757 return nil, errors.New("x509: zero or negative DSA parameter") 758 } 759 pub := &dsa.PublicKey{ 760 Parameters: dsa.Parameters{ 761 P: params.P, 762 Q: params.Q, 763 G: params.G, 764 }, 765 Y: p, 766 } 767 return pub, nil 768 case ECDSA: 769 paramsData := keyData.Algorithm.Parameters.FullBytes 770 namedCurveOID := new(asn1.ObjectIdentifier) 771 _, err := asn1.Unmarshal(paramsData, namedCurveOID) 772 if err != nil { 773 return nil, err 774 } 775 namedCurve := namedCurveFromOID(*namedCurveOID) 776 if namedCurve == nil { 777 return nil, errors.New("x509: unsupported elliptic curve") 778 } 779 x, y := elliptic.Unmarshal(namedCurve, asn1Data) 780 if x == nil { 781 return nil, errors.New("x509: failed to unmarshal elliptic curve point") 782 } 783 pub := &ecdsa.PublicKey{ 784 Curve: namedCurve, 785 X: x, 786 Y: y, 787 } 788 return pub, nil 789 default: 790 return nil, nil 791 } 792 } 793 794 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) { 795 // RFC 5280, 4.2.1.6 796 797 // SubjectAltName ::= GeneralNames 798 // 799 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 800 // 801 // GeneralName ::= CHOICE { 802 // otherName [0] OtherName, 803 // rfc822Name [1] IA5String, 804 // dNSName [2] IA5String, 805 // x400Address [3] ORAddress, 806 // directoryName [4] Name, 807 // ediPartyName [5] EDIPartyName, 808 // uniformResourceIdentifier [6] IA5String, 809 // iPAddress [7] OCTET STRING, 810 // registeredID [8] OBJECT IDENTIFIER } 811 var seq asn1.RawValue 812 if _, err = asn1.Unmarshal(value, &seq); err != nil { 813 return 814 } 815 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { 816 err = asn1.StructuralError{Msg: "bad SAN sequence"} 817 return 818 } 819 820 rest := seq.Bytes 821 for len(rest) > 0 { 822 var v asn1.RawValue 823 rest, err = asn1.Unmarshal(rest, &v) 824 if err != nil { 825 return 826 } 827 switch v.Tag { 828 case 1: 829 emailAddresses = append(emailAddresses, string(v.Bytes)) 830 case 2: 831 dnsNames = append(dnsNames, string(v.Bytes)) 832 case 7: 833 switch len(v.Bytes) { 834 case net.IPv4len, net.IPv6len: 835 ipAddresses = append(ipAddresses, v.Bytes) 836 default: 837 err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes))) 838 return 839 } 840 } 841 } 842 843 return 844 } 845 846 func parseCertificate(in *certificate) (*Certificate, error) { 847 out := new(Certificate) 848 out.Raw = in.Raw 849 out.RawTBSCertificate = in.TBSCertificate.Raw 850 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw 851 out.RawSubject = in.TBSCertificate.Subject.FullBytes 852 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes 853 854 out.Signature = in.SignatureValue.RightAlign() 855 out.SignatureAlgorithm = 856 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm) 857 858 out.PublicKeyAlgorithm = 859 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) 860 var err error 861 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey) 862 if err != nil { 863 return nil, err 864 } 865 866 if in.TBSCertificate.SerialNumber.Sign() < 0 { 867 return nil, errors.New("x509: negative serial number") 868 } 869 870 out.Version = in.TBSCertificate.Version + 1 871 out.SerialNumber = in.TBSCertificate.SerialNumber 872 873 var issuer, subject pkix.RDNSequence 874 if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { 875 return nil, err 876 } 877 if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { 878 return nil, err 879 } 880 881 out.Issuer.FillFromRDNSequence(&issuer) 882 out.Subject.FillFromRDNSequence(&subject) 883 884 out.NotBefore = in.TBSCertificate.Validity.NotBefore 885 out.NotAfter = in.TBSCertificate.Validity.NotAfter 886 887 for _, e := range in.TBSCertificate.Extensions { 888 out.Extensions = append(out.Extensions, e) 889 890 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { 891 switch e.Id[3] { 892 case 15: 893 // RFC 5280, 4.2.1.3 894 var usageBits asn1.BitString 895 _, err := asn1.Unmarshal(e.Value, &usageBits) 896 897 if err == nil { 898 var usage int 899 for i := 0; i < 9; i++ { 900 if usageBits.At(i) != 0 { 901 usage |= 1 << uint(i) 902 } 903 } 904 out.KeyUsage = KeyUsage(usage) 905 continue 906 } 907 case 19: 908 // RFC 5280, 4.2.1.9 909 var constraints basicConstraints 910 _, err := asn1.Unmarshal(e.Value, &constraints) 911 912 if err == nil { 913 out.BasicConstraintsValid = true 914 out.IsCA = constraints.IsCA 915 out.MaxPathLen = constraints.MaxPathLen 916 continue 917 } 918 case 17: 919 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value) 920 if err != nil { 921 return nil, err 922 } 923 924 if len(out.DNSNames) > 0 || len(out.EmailAddresses) > 0 || len(out.IPAddresses) > 0 { 925 continue 926 } 927 // If we didn't parse any of the names then we 928 // fall through to the critical check below. 929 930 case 30: 931 // RFC 5280, 4.2.1.10 932 933 // NameConstraints ::= SEQUENCE { 934 // permittedSubtrees [0] GeneralSubtrees OPTIONAL, 935 // excludedSubtrees [1] GeneralSubtrees OPTIONAL } 936 // 937 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree 938 // 939 // GeneralSubtree ::= SEQUENCE { 940 // base GeneralName, 941 // minimum [0] BaseDistance DEFAULT 0, 942 // maximum [1] BaseDistance OPTIONAL } 943 // 944 // BaseDistance ::= INTEGER (0..MAX) 945 946 var constraints nameConstraints 947 _, err := asn1.Unmarshal(e.Value, &constraints) 948 if err != nil { 949 return nil, err 950 } 951 952 if len(constraints.Excluded) > 0 && e.Critical { 953 return out, UnhandledCriticalExtension{} 954 } 955 956 for _, subtree := range constraints.Permitted { 957 if len(subtree.Name) == 0 { 958 if e.Critical { 959 return out, UnhandledCriticalExtension{} 960 } 961 continue 962 } 963 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name) 964 } 965 continue 966 967 case 31: 968 // RFC 5280, 4.2.1.14 969 970 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 971 // 972 // DistributionPoint ::= SEQUENCE { 973 // distributionPoint [0] DistributionPointName OPTIONAL, 974 // reasons [1] ReasonFlags OPTIONAL, 975 // cRLIssuer [2] GeneralNames OPTIONAL } 976 // 977 // DistributionPointName ::= CHOICE { 978 // fullName [0] GeneralNames, 979 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 980 981 var cdp []distributionPoint 982 _, err := asn1.Unmarshal(e.Value, &cdp) 983 if err != nil { 984 return nil, err 985 } 986 987 for _, dp := range cdp { 988 var n asn1.RawValue 989 _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n) 990 if err != nil { 991 return nil, err 992 } 993 994 if n.Tag == 6 { 995 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) 996 } 997 } 998 continue 999 1000 case 35: 1001 // RFC 5280, 4.2.1.1 1002 var a authKeyId 1003 _, err = asn1.Unmarshal(e.Value, &a) 1004 if err != nil { 1005 return nil, err 1006 } 1007 out.AuthorityKeyId = a.Id 1008 continue 1009 1010 case 37: 1011 // RFC 5280, 4.2.1.12. Extended Key Usage 1012 1013 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } 1014 // 1015 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId 1016 // 1017 // KeyPurposeId ::= OBJECT IDENTIFIER 1018 1019 var keyUsage []asn1.ObjectIdentifier 1020 _, err = asn1.Unmarshal(e.Value, &keyUsage) 1021 if err != nil { 1022 return nil, err 1023 } 1024 1025 for _, u := range keyUsage { 1026 if extKeyUsage, ok := extKeyUsageFromOID(u); ok { 1027 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) 1028 } else { 1029 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) 1030 } 1031 } 1032 1033 continue 1034 1035 case 14: 1036 // RFC 5280, 4.2.1.2 1037 var keyid []byte 1038 _, err = asn1.Unmarshal(e.Value, &keyid) 1039 if err != nil { 1040 return nil, err 1041 } 1042 out.SubjectKeyId = keyid 1043 continue 1044 1045 case 32: 1046 // RFC 5280 4.2.1.4: Certificate Policies 1047 var policies []policyInformation 1048 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { 1049 return nil, err 1050 } 1051 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) 1052 for i, policy := range policies { 1053 out.PolicyIdentifiers[i] = policy.Policy 1054 } 1055 } 1056 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { 1057 // RFC 5280 4.2.2.1: Authority Information Access 1058 var aia []authorityInfoAccess 1059 if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { 1060 return nil, err 1061 } 1062 1063 for _, v := range aia { 1064 // GeneralName: uniformResourceIdentifier [6] IA5String 1065 if v.Location.Tag != 6 { 1066 continue 1067 } 1068 if v.Method.Equal(oidAuthorityInfoAccessOcsp) { 1069 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) 1070 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { 1071 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) 1072 } 1073 } 1074 } 1075 1076 if e.Critical { 1077 return out, UnhandledCriticalExtension{} 1078 } 1079 } 1080 1081 return out, nil 1082 } 1083 1084 // ParseCertificate parses a single certificate from the given ASN.1 DER data. 1085 func ParseCertificate(asn1Data []byte) (*Certificate, error) { 1086 var cert certificate 1087 rest, err := asn1.Unmarshal(asn1Data, &cert) 1088 if err != nil { 1089 return nil, err 1090 } 1091 if len(rest) > 0 { 1092 return nil, asn1.SyntaxError{Msg: "trailing data"} 1093 } 1094 1095 return parseCertificate(&cert) 1096 } 1097 1098 // ParseCertificates parses one or more certificates from the given ASN.1 DER 1099 // data. The certificates must be concatenated with no intermediate padding. 1100 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { 1101 var v []*certificate 1102 1103 for len(asn1Data) > 0 { 1104 cert := new(certificate) 1105 var err error 1106 asn1Data, err = asn1.Unmarshal(asn1Data, cert) 1107 if err != nil { 1108 return nil, err 1109 } 1110 v = append(v, cert) 1111 } 1112 1113 ret := make([]*Certificate, len(v)) 1114 for i, ci := range v { 1115 cert, err := parseCertificate(ci) 1116 if err != nil { 1117 return nil, err 1118 } 1119 ret[i] = cert 1120 } 1121 1122 return ret, nil 1123 } 1124 1125 func reverseBitsInAByte(in byte) byte { 1126 b1 := in>>4 | in<<4 1127 b2 := b1>>2&0x33 | b1<<2&0xcc 1128 b3 := b2>>1&0x55 | b2<<1&0xaa 1129 return b3 1130 } 1131 1132 var ( 1133 oidExtensionSubjectKeyId = []int{2, 5, 29, 14} 1134 oidExtensionKeyUsage = []int{2, 5, 29, 15} 1135 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} 1136 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} 1137 oidExtensionBasicConstraints = []int{2, 5, 29, 19} 1138 oidExtensionSubjectAltName = []int{2, 5, 29, 17} 1139 oidExtensionCertificatePolicies = []int{2, 5, 29, 32} 1140 oidExtensionNameConstraints = []int{2, 5, 29, 30} 1141 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} 1142 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} 1143 ) 1144 1145 var ( 1146 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 1147 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 1148 ) 1149 1150 // oidNotInExtensions returns whether an extension with the given oid exists in 1151 // extensions. 1152 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 1153 for _, e := range extensions { 1154 if e.Id.Equal(oid) { 1155 return true 1156 } 1157 } 1158 return false 1159 } 1160 1161 // marshalSANs marshals a list of addresses into a the contents of an X.509 1162 // SubjectAlternativeName extension. 1163 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { 1164 var rawValues []asn1.RawValue 1165 for _, name := range dnsNames { 1166 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) 1167 } 1168 for _, email := range emailAddresses { 1169 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) 1170 } 1171 for _, rawIP := range ipAddresses { 1172 // If possible, we always want to encode IPv4 addresses in 4 bytes. 1173 ip := rawIP.To4() 1174 if ip == nil { 1175 ip = rawIP 1176 } 1177 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) 1178 } 1179 return asn1.Marshal(rawValues) 1180 } 1181 1182 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) { 1183 ret = make([]pkix.Extension, 10 /* maximum number of elements. */) 1184 n := 0 1185 1186 if template.KeyUsage != 0 && 1187 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { 1188 ret[n].Id = oidExtensionKeyUsage 1189 ret[n].Critical = true 1190 1191 var a [2]byte 1192 a[0] = reverseBitsInAByte(byte(template.KeyUsage)) 1193 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) 1194 1195 l := 1 1196 if a[1] != 0 { 1197 l = 2 1198 } 1199 1200 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8}) 1201 if err != nil { 1202 return 1203 } 1204 n++ 1205 } 1206 1207 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 1208 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { 1209 ret[n].Id = oidExtensionExtendedKeyUsage 1210 1211 var oids []asn1.ObjectIdentifier 1212 for _, u := range template.ExtKeyUsage { 1213 if oid, ok := oidFromExtKeyUsage(u); ok { 1214 oids = append(oids, oid) 1215 } else { 1216 panic("internal error") 1217 } 1218 } 1219 1220 oids = append(oids, template.UnknownExtKeyUsage...) 1221 1222 ret[n].Value, err = asn1.Marshal(oids) 1223 if err != nil { 1224 return 1225 } 1226 n++ 1227 } 1228 1229 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { 1230 ret[n].Id = oidExtensionBasicConstraints 1231 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen}) 1232 ret[n].Critical = true 1233 if err != nil { 1234 return 1235 } 1236 n++ 1237 } 1238 1239 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { 1240 ret[n].Id = oidExtensionSubjectKeyId 1241 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) 1242 if err != nil { 1243 return 1244 } 1245 n++ 1246 } 1247 1248 if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { 1249 ret[n].Id = oidExtensionAuthorityKeyId 1250 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) 1251 if err != nil { 1252 return 1253 } 1254 n++ 1255 } 1256 1257 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 1258 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { 1259 ret[n].Id = oidExtensionAuthorityInfoAccess 1260 var aiaValues []authorityInfoAccess 1261 for _, name := range template.OCSPServer { 1262 aiaValues = append(aiaValues, authorityInfoAccess{ 1263 Method: oidAuthorityInfoAccessOcsp, 1264 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1265 }) 1266 } 1267 for _, name := range template.IssuingCertificateURL { 1268 aiaValues = append(aiaValues, authorityInfoAccess{ 1269 Method: oidAuthorityInfoAccessIssuers, 1270 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 1271 }) 1272 } 1273 ret[n].Value, err = asn1.Marshal(aiaValues) 1274 if err != nil { 1275 return 1276 } 1277 n++ 1278 } 1279 1280 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 1281 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1282 ret[n].Id = oidExtensionSubjectAltName 1283 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 1284 if err != nil { 1285 return 1286 } 1287 n++ 1288 } 1289 1290 if len(template.PolicyIdentifiers) > 0 && 1291 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { 1292 ret[n].Id = oidExtensionCertificatePolicies 1293 policies := make([]policyInformation, len(template.PolicyIdentifiers)) 1294 for i, policy := range template.PolicyIdentifiers { 1295 policies[i].Policy = policy 1296 } 1297 ret[n].Value, err = asn1.Marshal(policies) 1298 if err != nil { 1299 return 1300 } 1301 n++ 1302 } 1303 1304 if len(template.PermittedDNSDomains) > 0 && 1305 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { 1306 ret[n].Id = oidExtensionNameConstraints 1307 ret[n].Critical = template.PermittedDNSDomainsCritical 1308 1309 var out nameConstraints 1310 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains)) 1311 for i, permitted := range template.PermittedDNSDomains { 1312 out.Permitted[i] = generalSubtree{Name: permitted} 1313 } 1314 ret[n].Value, err = asn1.Marshal(out) 1315 if err != nil { 1316 return 1317 } 1318 n++ 1319 } 1320 1321 if len(template.CRLDistributionPoints) > 0 && 1322 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { 1323 ret[n].Id = oidExtensionCRLDistributionPoints 1324 1325 var crlDp []distributionPoint 1326 for _, name := range template.CRLDistributionPoints { 1327 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) 1328 1329 dp := distributionPoint{ 1330 DistributionPoint: distributionPointName{ 1331 FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName}, 1332 }, 1333 } 1334 crlDp = append(crlDp, dp) 1335 } 1336 1337 ret[n].Value, err = asn1.Marshal(crlDp) 1338 if err != nil { 1339 return 1340 } 1341 n++ 1342 } 1343 1344 // Adding another extension here? Remember to update the maximum number 1345 // of elements in the make() at the top of the function. 1346 1347 return append(ret[:n], template.ExtraExtensions...), nil 1348 } 1349 1350 func subjectBytes(cert *Certificate) ([]byte, error) { 1351 if len(cert.RawSubject) > 0 { 1352 return cert.RawSubject, nil 1353 } 1354 1355 return asn1.Marshal(cert.Subject.ToRDNSequence()) 1356 } 1357 1358 // signingParamsForPrivateKey returns the parameters to use for signing with 1359 // priv. If requestedSigAlgo is not zero then it overrides the default 1360 // signature algorithm. 1361 func signingParamsForPrivateKey(priv interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { 1362 var pubType PublicKeyAlgorithm 1363 1364 switch priv := priv.(type) { 1365 case *rsa.PrivateKey: 1366 pubType = RSA 1367 sigAlgo.Algorithm = oidSignatureSHA256WithRSA 1368 hashFunc = crypto.SHA256 1369 1370 case *ecdsa.PrivateKey: 1371 pubType = ECDSA 1372 1373 switch priv.Curve { 1374 case elliptic.P224(), elliptic.P256(): 1375 hashFunc = crypto.SHA256 1376 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 1377 case elliptic.P384(): 1378 hashFunc = crypto.SHA384 1379 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 1380 case elliptic.P521(): 1381 hashFunc = crypto.SHA512 1382 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 1383 default: 1384 err = errors.New("x509: unknown elliptic curve") 1385 } 1386 1387 default: 1388 err = errors.New("x509: only RSA and ECDSA private keys supported") 1389 } 1390 1391 if err != nil { 1392 return 1393 } 1394 1395 if requestedSigAlgo == 0 { 1396 return 1397 } 1398 1399 found := false 1400 for _, details := range signatureAlgorithmDetails { 1401 if details.algo == requestedSigAlgo { 1402 if details.pubKeyAlgo != pubType { 1403 err = errors.New("x509: requested SignatureAlgorithm does not match private key type") 1404 return 1405 } 1406 sigAlgo.Algorithm, hashFunc = details.oid, details.hash 1407 if hashFunc == 0 { 1408 err = errors.New("x509: cannot sign with hash function requested") 1409 return 1410 } 1411 found = true 1412 break 1413 } 1414 } 1415 1416 if !found { 1417 err = errors.New("x509: unknown SignatureAlgorithm") 1418 } 1419 1420 return 1421 } 1422 1423 // CreateCertificate creates a new certificate based on a template. The 1424 // following members of template are used: SerialNumber, Subject, NotBefore, 1425 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, 1426 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, 1427 // PermittedDNSDomains, SignatureAlgorithm. 1428 // 1429 // The certificate is signed by parent. If parent is equal to template then the 1430 // certificate is self-signed. The parameter pub is the public key of the 1431 // signee and priv is the private key of the signer. 1432 // 1433 // The returned slice is the certificate in DER encoding. 1434 // 1435 // The only supported key types are RSA and ECDSA (*rsa.PublicKey or 1436 // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PrivateKey for priv). 1437 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) { 1438 hashFunc, signatureAlgorithm, err := signingParamsForPrivateKey(priv, template.SignatureAlgorithm) 1439 if err != nil { 1440 return nil, err 1441 } 1442 1443 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub) 1444 if err != nil { 1445 return nil, err 1446 } 1447 1448 if err != nil { 1449 return 1450 } 1451 1452 if len(parent.SubjectKeyId) > 0 { 1453 template.AuthorityKeyId = parent.SubjectKeyId 1454 } 1455 1456 extensions, err := buildExtensions(template) 1457 if err != nil { 1458 return 1459 } 1460 1461 asn1Issuer, err := subjectBytes(parent) 1462 if err != nil { 1463 return 1464 } 1465 1466 asn1Subject, err := subjectBytes(template) 1467 if err != nil { 1468 return 1469 } 1470 1471 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 1472 c := tbsCertificate{ 1473 Version: 2, 1474 SerialNumber: template.SerialNumber, 1475 SignatureAlgorithm: signatureAlgorithm, 1476 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 1477 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 1478 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1479 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 1480 Extensions: extensions, 1481 } 1482 1483 tbsCertContents, err := asn1.Marshal(c) 1484 if err != nil { 1485 return 1486 } 1487 1488 c.Raw = tbsCertContents 1489 1490 h := hashFunc.New() 1491 h.Write(tbsCertContents) 1492 digest := h.Sum(nil) 1493 1494 var signature []byte 1495 1496 switch priv := priv.(type) { 1497 case *rsa.PrivateKey: 1498 signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) 1499 case *ecdsa.PrivateKey: 1500 var r, s *big.Int 1501 if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { 1502 signature, err = asn1.Marshal(ecdsaSignature{r, s}) 1503 } 1504 default: 1505 panic("internal error") 1506 } 1507 1508 if err != nil { 1509 return 1510 } 1511 1512 cert, err = asn1.Marshal(certificate{ 1513 nil, 1514 c, 1515 signatureAlgorithm, 1516 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1517 }) 1518 return 1519 } 1520 1521 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded 1522 // CRL. 1523 var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 1524 1525 // pemType is the type of a PEM encoded CRL. 1526 var pemType = "X509 CRL" 1527 1528 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM 1529 // encoded CRLs will appear where they should be DER encoded, so this function 1530 // will transparently handle PEM encoding as long as there isn't any leading 1531 // garbage. 1532 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) { 1533 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 1534 block, _ := pem.Decode(crlBytes) 1535 if block != nil && block.Type == pemType { 1536 crlBytes = block.Bytes 1537 } 1538 } 1539 return ParseDERCRL(crlBytes) 1540 } 1541 1542 // ParseDERCRL parses a DER encoded CRL from the given bytes. 1543 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) { 1544 certList = new(pkix.CertificateList) 1545 _, err = asn1.Unmarshal(derBytes, certList) 1546 if err != nil { 1547 certList = nil 1548 } 1549 return 1550 } 1551 1552 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that 1553 // contains the given list of revoked certificates. 1554 // 1555 // The only supported key type is RSA (*rsa.PrivateKey for priv). 1556 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 1557 rsaPriv, ok := priv.(*rsa.PrivateKey) 1558 if !ok { 1559 return nil, errors.New("x509: non-RSA private keys not supported") 1560 } 1561 tbsCertList := pkix.TBSCertificateList{ 1562 Version: 2, 1563 Signature: pkix.AlgorithmIdentifier{ 1564 Algorithm: oidSignatureSHA1WithRSA, 1565 }, 1566 Issuer: c.Subject.ToRDNSequence(), 1567 ThisUpdate: now.UTC(), 1568 NextUpdate: expiry.UTC(), 1569 RevokedCertificates: revokedCerts, 1570 } 1571 1572 tbsCertListContents, err := asn1.Marshal(tbsCertList) 1573 if err != nil { 1574 return 1575 } 1576 1577 h := sha1.New() 1578 h.Write(tbsCertListContents) 1579 digest := h.Sum(nil) 1580 1581 signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest) 1582 if err != nil { 1583 return 1584 } 1585 1586 return asn1.Marshal(pkix.CertificateList{ 1587 TBSCertList: tbsCertList, 1588 SignatureAlgorithm: pkix.AlgorithmIdentifier{ 1589 Algorithm: oidSignatureSHA1WithRSA, 1590 }, 1591 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 1592 }) 1593 } 1594 1595 // CertificateRequest represents a PKCS #10, certificate signature request. 1596 type CertificateRequest struct { 1597 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). 1598 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. 1599 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 1600 RawSubject []byte // DER encoded Subject. 1601 1602 Version int 1603 Signature []byte 1604 SignatureAlgorithm SignatureAlgorithm 1605 1606 PublicKeyAlgorithm PublicKeyAlgorithm 1607 PublicKey interface{} 1608 1609 Subject pkix.Name 1610 1611 // Attributes is a collection of attributes providing 1612 // additional information about the subject of the certificate. 1613 // See RFC 2986 section 4.1. 1614 Attributes []pkix.AttributeTypeAndValueSET 1615 1616 // Extensions contains raw X.509 extensions. When parsing CSRs, this 1617 // can be used to extract extensions that are not parsed by this 1618 // package. 1619 Extensions []pkix.Extension 1620 1621 // ExtraExtensions contains extensions to be copied, raw, into any 1622 // marshaled CSR. Values override any extensions that would otherwise 1623 // be produced based on the other fields but are overridden by any 1624 // extensions specified in Attributes. 1625 // 1626 // The ExtraExtensions field is not populated when parsing CSRs, see 1627 // Extensions. 1628 ExtraExtensions []pkix.Extension 1629 1630 // Subject Alternate Name values. 1631 DNSNames []string 1632 EmailAddresses []string 1633 IPAddresses []net.IP 1634 } 1635 1636 // These structures reflect the ASN.1 structure of X.509 certificate 1637 // signature requests (see RFC 2986): 1638 1639 type tbsCertificateRequest struct { 1640 Raw asn1.RawContent 1641 Version int 1642 Subject asn1.RawValue 1643 PublicKey publicKeyInfo 1644 Attributes []pkix.AttributeTypeAndValueSET `asn1:"tag:0"` 1645 } 1646 1647 type certificateRequest struct { 1648 Raw asn1.RawContent 1649 TBSCSR tbsCertificateRequest 1650 SignatureAlgorithm pkix.AlgorithmIdentifier 1651 SignatureValue asn1.BitString 1652 } 1653 1654 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested 1655 // extensions in a CSR. 1656 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} 1657 1658 // CreateCertificateRequest creates a new certificate based on a template. The 1659 // following members of template are used: Subject, Attributes, 1660 // SignatureAlgorithm, Extension, DNSNames, EmailAddresses, and IPAddresses. 1661 // The private key is the private key of the signer. 1662 // 1663 // The returned slice is the certificate request in DER encoding. 1664 // 1665 // The only supported key types are RSA (*rsa.PrivateKey) and ECDSA 1666 // (*ecdsa.PrivateKey). 1667 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { 1668 hashFunc, sigAlgo, err := signingParamsForPrivateKey(priv, template.SignatureAlgorithm) 1669 if err != nil { 1670 return nil, err 1671 } 1672 1673 var publicKeyBytes []byte 1674 var publicKeyAlgorithm pkix.AlgorithmIdentifier 1675 1676 switch priv := priv.(type) { 1677 case *rsa.PrivateKey: 1678 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(&priv.PublicKey) 1679 case *ecdsa.PrivateKey: 1680 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(&priv.PublicKey) 1681 default: 1682 panic("internal error") 1683 } 1684 1685 if err != nil { 1686 return nil, err 1687 } 1688 1689 var extensions []pkix.Extension 1690 1691 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 1692 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 1693 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 1694 if err != nil { 1695 return nil, err 1696 } 1697 1698 extensions = append(extensions, pkix.Extension{ 1699 Id: oidExtensionSubjectAltName, 1700 Value: sanBytes, 1701 }) 1702 } 1703 1704 extensions = append(extensions, template.ExtraExtensions...) 1705 1706 var attributes []pkix.AttributeTypeAndValueSET 1707 attributes = append(attributes, template.Attributes...) 1708 1709 if len(extensions) > 0 { 1710 // specifiedExtensions contains all the extensions that we 1711 // found specified via template.Attributes. 1712 specifiedExtensions := make(map[string]bool) 1713 1714 for _, atvSet := range template.Attributes { 1715 if !atvSet.Type.Equal(oidExtensionRequest) { 1716 continue 1717 } 1718 1719 for _, atvs := range atvSet.Value { 1720 for _, atv := range atvs { 1721 specifiedExtensions[atv.Type.String()] = true 1722 } 1723 } 1724 } 1725 1726 atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions)) 1727 for _, e := range extensions { 1728 if specifiedExtensions[e.Id.String()] { 1729 // Attributes already contained a value for 1730 // this extension and it takes priority. 1731 continue 1732 } 1733 1734 atvs = append(atvs, pkix.AttributeTypeAndValue{ 1735 // There is no place for the critical flag in a CSR. 1736 Type: e.Id, 1737 Value: e.Value, 1738 }) 1739 } 1740 1741 // Append the extensions to an existing attribute if possible. 1742 appended := false 1743 for _, atvSet := range attributes { 1744 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { 1745 continue 1746 } 1747 1748 atvSet.Value[0] = append(atvSet.Value[0], atvs...) 1749 appended = true 1750 break 1751 } 1752 1753 // Otherwise, add a new attribute for the extensions. 1754 if !appended { 1755 attributes = append(attributes, pkix.AttributeTypeAndValueSET{ 1756 Type: oidExtensionRequest, 1757 Value: [][]pkix.AttributeTypeAndValue{ 1758 atvs, 1759 }, 1760 }) 1761 } 1762 } 1763 1764 asn1Subject := template.RawSubject 1765 if len(asn1Subject) == 0 { 1766 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) 1767 if err != nil { 1768 return 1769 } 1770 } 1771 1772 tbsCSR := tbsCertificateRequest{ 1773 Version: 0, // PKCS #10, RFC 2986 1774 Subject: asn1.RawValue{FullBytes: asn1Subject}, 1775 PublicKey: publicKeyInfo{ 1776 Algorithm: publicKeyAlgorithm, 1777 PublicKey: asn1.BitString{ 1778 Bytes: publicKeyBytes, 1779 BitLength: len(publicKeyBytes) * 8, 1780 }, 1781 }, 1782 Attributes: attributes, 1783 } 1784 1785 tbsCSRContents, err := asn1.Marshal(tbsCSR) 1786 if err != nil { 1787 return 1788 } 1789 tbsCSR.Raw = tbsCSRContents 1790 1791 h := hashFunc.New() 1792 h.Write(tbsCSRContents) 1793 digest := h.Sum(nil) 1794 1795 var signature []byte 1796 switch priv := priv.(type) { 1797 case *rsa.PrivateKey: 1798 signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) 1799 case *ecdsa.PrivateKey: 1800 var r, s *big.Int 1801 if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { 1802 signature, err = asn1.Marshal(ecdsaSignature{r, s}) 1803 } 1804 default: 1805 panic("internal error") 1806 } 1807 1808 if err != nil { 1809 return 1810 } 1811 1812 return asn1.Marshal(certificateRequest{ 1813 TBSCSR: tbsCSR, 1814 SignatureAlgorithm: sigAlgo, 1815 SignatureValue: asn1.BitString{ 1816 Bytes: signature, 1817 BitLength: len(signature) * 8, 1818 }, 1819 }) 1820 } 1821 1822 // ParseCertificateRequest parses a single certificate request from the 1823 // given ASN.1 DER data. 1824 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { 1825 var csr certificateRequest 1826 1827 rest, err := asn1.Unmarshal(asn1Data, &csr) 1828 if err != nil { 1829 return nil, err 1830 } else if len(rest) != 0 { 1831 return nil, asn1.SyntaxError{Msg: "trailing data"} 1832 } 1833 1834 return parseCertificateRequest(&csr) 1835 } 1836 1837 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { 1838 out := &CertificateRequest{ 1839 Raw: in.Raw, 1840 RawTBSCertificateRequest: in.TBSCSR.Raw, 1841 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, 1842 RawSubject: in.TBSCSR.Subject.FullBytes, 1843 1844 Signature: in.SignatureValue.RightAlign(), 1845 SignatureAlgorithm: getSignatureAlgorithmFromOID(in.SignatureAlgorithm.Algorithm), 1846 1847 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), 1848 1849 Version: in.TBSCSR.Version, 1850 Attributes: in.TBSCSR.Attributes, 1851 } 1852 1853 var err error 1854 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey) 1855 if err != nil { 1856 return nil, err 1857 } 1858 1859 var subject pkix.RDNSequence 1860 if _, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { 1861 return nil, err 1862 } 1863 1864 out.Subject.FillFromRDNSequence(&subject) 1865 1866 var extensions []pkix.AttributeTypeAndValue 1867 1868 for _, atvSet := range in.TBSCSR.Attributes { 1869 if !atvSet.Type.Equal(oidExtensionRequest) { 1870 continue 1871 } 1872 1873 for _, atvs := range atvSet.Value { 1874 extensions = append(extensions, atvs...) 1875 } 1876 } 1877 1878 out.Extensions = make([]pkix.Extension, 0, len(extensions)) 1879 1880 for _, e := range extensions { 1881 value, ok := e.Value.([]byte) 1882 if !ok { 1883 return nil, errors.New("x509: extension attribute contained non-OCTET STRING data") 1884 } 1885 1886 out.Extensions = append(out.Extensions, pkix.Extension{ 1887 Id: e.Type, 1888 Value: value, 1889 }) 1890 1891 if len(e.Type) == 4 && e.Type[0] == 2 && e.Type[1] == 5 && e.Type[2] == 29 { 1892 switch e.Type[3] { 1893 case 17: 1894 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(value) 1895 if err != nil { 1896 return nil, err 1897 } 1898 } 1899 } 1900 } 1901 1902 return out, nil 1903 }