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