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