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