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