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