github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/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 // Originally based on the go/crypto/x509 standard library, 8 // this package has now diverged enough that it is no longer 9 // updated with direct correspondence to new go releases. 10 11 package x509 12 13 import ( 14 // all of the hash libraries need to be imported for side-effects, 15 // so that crypto.RegisterHash is called 16 _ "crypto/md5" 17 "crypto/sha256" 18 _ "crypto/sha512" 19 "io" 20 "strings" 21 "unicode" 22 23 "bytes" 24 "crypto" 25 "crypto/ecdsa" 26 "crypto/elliptic" 27 "crypto/rsa" 28 _ "crypto/sha1" 29 _ "crypto/sha256" 30 "encoding/pem" 31 "errors" 32 "fmt" 33 "math/big" 34 "net" 35 "strconv" 36 "time" 37 38 "github.com/weppos/publicsuffix-go/publicsuffix" 39 "github.com/zmap/zcrypto/dsa" 40 "github.com/zmap/zcrypto/encoding/asn1" 41 "github.com/zmap/zcrypto/x509/ct" 42 "github.com/zmap/zcrypto/x509/pkix" 43 "golang.org/x/crypto/ed25519" 44 ) 45 46 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo 47 // in RFC 3280. 48 type pkixPublicKey struct { 49 Algo pkix.AlgorithmIdentifier 50 BitString asn1.BitString 51 } 52 53 // ParsePKIXPublicKey parses a DER encoded public key. These values are 54 // typically found in PEM blocks with "BEGIN PUBLIC KEY". 55 // 56 // Supported key types include RSA, DSA, and ECDSA. Unknown key 57 // types result in an error. 58 // 59 // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey, 60 // or *ecdsa.PublicKey. 61 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { 62 var pki publicKeyInfo 63 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil { 64 return nil, err 65 } else if len(rest) != 0 { 66 return nil, errors.New("x509: trailing data after ASN.1 of public-key") 67 } 68 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) 69 if algo == UnknownPublicKeyAlgorithm { 70 return nil, errors.New("x509: unknown public key algorithm") 71 } 72 return parsePublicKey(algo, &pki) 73 } 74 75 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { 76 switch pub := pub.(type) { 77 case *rsa.PublicKey: 78 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{ 79 N: pub.N, 80 E: pub.E, 81 }) 82 if err != nil { 83 return nil, pkix.AlgorithmIdentifier{}, err 84 } 85 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA 86 // This is a NULL parameters value which is required by 87 // https://tools.ietf.org/html/rfc3279#section-2.3.1. 88 publicKeyAlgorithm.Parameters = asn1.NullRawValue 89 case *ecdsa.PublicKey: 90 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) 91 oid, ok := oidFromNamedCurve(pub.Curve) 92 if !ok { 93 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") 94 } 95 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA 96 var paramBytes []byte 97 paramBytes, err = asn1.Marshal(oid) 98 if err != nil { 99 return 100 } 101 publicKeyAlgorithm.Parameters.FullBytes = paramBytes 102 case *AugmentedECDSA: 103 return marshalPublicKey(pub.Pub) 104 case ed25519.PublicKey: 105 publicKeyAlgorithm.Algorithm = oidKeyEd25519 106 return []byte(pub), publicKeyAlgorithm, nil 107 case X25519PublicKey: 108 publicKeyAlgorithm.Algorithm = oidKeyX25519 109 return []byte(pub), publicKeyAlgorithm, nil 110 default: 111 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA, ECDSA, ed25519, or X25519 public keys supported") 112 } 113 114 return publicKeyBytes, publicKeyAlgorithm, nil 115 } 116 117 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. 118 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { 119 var publicKeyBytes []byte 120 var publicKeyAlgorithm pkix.AlgorithmIdentifier 121 var err error 122 123 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { 124 return nil, err 125 } 126 127 pkix := pkixPublicKey{ 128 Algo: publicKeyAlgorithm, 129 BitString: asn1.BitString{ 130 Bytes: publicKeyBytes, 131 BitLength: 8 * len(publicKeyBytes), 132 }, 133 } 134 135 ret, _ := asn1.Marshal(pkix) 136 return ret, nil 137 } 138 139 // These structures reflect the ASN.1 structure of X.509 certificates.: 140 141 type certificate struct { 142 Raw asn1.RawContent 143 TBSCertificate tbsCertificate 144 SignatureAlgorithm pkix.AlgorithmIdentifier 145 SignatureValue asn1.BitString 146 } 147 148 type tbsCertificate struct { 149 Raw asn1.RawContent 150 Version int `asn1:"optional,explicit,default:0,tag:0"` 151 SerialNumber *big.Int 152 SignatureAlgorithm pkix.AlgorithmIdentifier 153 Issuer asn1.RawValue 154 Validity validity 155 Subject asn1.RawValue 156 PublicKey publicKeyInfo 157 UniqueId asn1.BitString `asn1:"optional,tag:1"` 158 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` 159 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` 160 } 161 162 type dsaAlgorithmParameters struct { 163 P, Q, G *big.Int 164 } 165 166 type dsaSignature struct { 167 R, S *big.Int 168 } 169 170 type ecdsaSignature dsaSignature 171 172 type AugmentedECDSA struct { 173 Pub *ecdsa.PublicKey 174 Raw asn1.BitString 175 } 176 177 type validity struct { 178 NotBefore, NotAfter time.Time 179 } 180 181 type publicKeyInfo struct { 182 Raw asn1.RawContent 183 Algorithm pkix.AlgorithmIdentifier 184 PublicKey asn1.BitString 185 } 186 187 // RFC 5280, 4.2.1.1 188 type authKeyId struct { 189 Id []byte `asn1:"optional,tag:0"` 190 } 191 192 type SignatureAlgorithmOID asn1.ObjectIdentifier 193 194 type SignatureAlgorithm int 195 196 const ( 197 UnknownSignatureAlgorithm SignatureAlgorithm = iota 198 MD2WithRSA 199 MD5WithRSA 200 SHA1WithRSA 201 SHA256WithRSA 202 SHA384WithRSA 203 SHA512WithRSA 204 DSAWithSHA1 205 DSAWithSHA256 206 ECDSAWithSHA1 207 ECDSAWithSHA256 208 ECDSAWithSHA384 209 ECDSAWithSHA512 210 SHA256WithRSAPSS 211 SHA384WithRSAPSS 212 SHA512WithRSAPSS 213 Ed25519Sig 214 ) 215 216 func (algo SignatureAlgorithm) isRSAPSS() bool { 217 switch algo { 218 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS: 219 return true 220 default: 221 return false 222 } 223 } 224 225 var algoName = [...]string{ 226 MD2WithRSA: "MD2-RSA", 227 MD5WithRSA: "MD5-RSA", 228 SHA1WithRSA: "SHA1-RSA", 229 SHA256WithRSA: "SHA256-RSA", 230 SHA384WithRSA: "SHA384-RSA", 231 SHA512WithRSA: "SHA512-RSA", 232 SHA256WithRSAPSS: "SHA256-RSAPSS", 233 SHA384WithRSAPSS: "SHA384-RSAPSS", 234 SHA512WithRSAPSS: "SHA512-RSAPSS", 235 DSAWithSHA1: "DSA-SHA1", 236 DSAWithSHA256: "DSA-SHA256", 237 ECDSAWithSHA1: "ECDSA-SHA1", 238 ECDSAWithSHA256: "ECDSA-SHA256", 239 ECDSAWithSHA384: "ECDSA-SHA384", 240 ECDSAWithSHA512: "ECDSA-SHA512", 241 Ed25519Sig: "Ed25519", 242 } 243 244 func (algo SignatureAlgorithm) String() string { 245 if 0 < algo && int(algo) < len(algoName) { 246 return algoName[algo] 247 } 248 return strconv.Itoa(int(algo)) 249 } 250 251 var keyAlgorithmNames = []string{ 252 "unknown_algorithm", 253 "RSA", 254 "DSA", 255 "ECDSA", 256 "Ed25519", 257 "X25519", 258 } 259 260 type PublicKeyAlgorithm int 261 262 const ( 263 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota 264 RSA 265 DSA 266 ECDSA 267 Ed25519 268 X25519 269 total_key_algorithms 270 ) 271 272 // curve25519 package does not expose key types 273 type X25519PublicKey []byte 274 275 // OIDs for signature algorithms 276 // 277 // pkcs-1 OBJECT IDENTIFIER ::= { 278 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } 279 // 280 // 281 // RFC 3279 2.2.1 RSA Signature Algorithms 282 // 283 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } 284 // 285 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } 286 // 287 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } 288 // 289 // dsaWithSha1 OBJECT IDENTIFIER ::= { 290 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 291 // 292 // RFC 3279 2.2.3 ECDSA Signature Algorithm 293 // 294 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { 295 // iso(1) member-body(2) us(840) ansi-x962(10045) 296 // signatures(4) ecdsa-with-SHA1(1)} 297 // 298 // 299 // RFC 4055 5 PKCS #1 Version 1.5 300 // 301 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } 302 // 303 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } 304 // 305 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } 306 // 307 // 308 // RFC 5758 3.1 DSA Signature Algorithms 309 // 310 // dsaWithSha256 OBJECT IDENTIFIER ::= { 311 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) 312 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2} 313 // 314 // RFC 5758 3.2 ECDSA Signature Algorithm 315 // 316 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 317 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } 318 // 319 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 320 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } 321 // 322 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) 323 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } 324 325 var ( 326 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} 327 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} 328 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} 329 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} 330 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} 331 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} 332 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10} 333 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} 334 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2} 335 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} 336 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} 337 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} 338 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} 339 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112} 340 341 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1} 342 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2} 343 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3} 344 345 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8} 346 347 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA 348 // but it's specified by ISO. Microsoft's makecert.exe has been known 349 // to produce certificates with this OID. 350 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29} 351 ) 352 353 // cryptoNoDigest means that the signature algorithm does not require a hash 354 // digest. The distinction between cryptoNoDigest and crypto.Hash(0) 355 // is purely superficial. crypto.Hash(0) is used in place of a null value 356 // when hashing is not supported for the given algorithm (as in the case of 357 // MD2WithRSA below). 358 var cryptoNoDigest = crypto.Hash(0) 359 360 var signatureAlgorithmDetails = []struct { 361 algo SignatureAlgorithm 362 oid asn1.ObjectIdentifier 363 pubKeyAlgo PublicKeyAlgorithm 364 hash crypto.Hash 365 }{ 366 {MD2WithRSA, oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */}, 367 {MD5WithRSA, oidSignatureMD5WithRSA, RSA, crypto.MD5}, 368 {SHA1WithRSA, oidSignatureSHA1WithRSA, RSA, crypto.SHA1}, 369 {SHA1WithRSA, oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1}, 370 {SHA256WithRSA, oidSignatureSHA256WithRSA, RSA, crypto.SHA256}, 371 {SHA384WithRSA, oidSignatureSHA384WithRSA, RSA, crypto.SHA384}, 372 {SHA512WithRSA, oidSignatureSHA512WithRSA, RSA, crypto.SHA512}, 373 {SHA256WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA256}, 374 {SHA384WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA384}, 375 {SHA512WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA512}, 376 {DSAWithSHA1, oidSignatureDSAWithSHA1, DSA, crypto.SHA1}, 377 {DSAWithSHA256, oidSignatureDSAWithSHA256, DSA, crypto.SHA256}, 378 {ECDSAWithSHA1, oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1}, 379 {ECDSAWithSHA256, oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256}, 380 {ECDSAWithSHA384, oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384}, 381 {ECDSAWithSHA512, oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512}, 382 {Ed25519Sig, oidKeyEd25519, Ed25519, cryptoNoDigest}, 383 } 384 385 // pssParameters reflects the parameters in an AlgorithmIdentifier that 386 // specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3 387 type pssParameters struct { 388 // The following three fields are not marked as 389 // optional because the default values specify SHA-1, 390 // which is no longer suitable for use in signatures. 391 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"` 392 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"` 393 SaltLength int `asn1:"explicit,tag:2"` 394 TrailerField int `asn1:"optional,explicit,tag:3,default:1"` 395 } 396 397 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters 398 // in an AlgorithmIdentifier that specifies RSA PSS. 399 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue { 400 var hashOID asn1.ObjectIdentifier 401 402 switch hashFunc { 403 case crypto.SHA256: 404 hashOID = oidSHA256 405 case crypto.SHA384: 406 hashOID = oidSHA384 407 case crypto.SHA512: 408 hashOID = oidSHA512 409 } 410 411 params := pssParameters{ 412 Hash: pkix.AlgorithmIdentifier{ 413 Algorithm: hashOID, 414 Parameters: asn1.NullRawValue, 415 }, 416 MGF: pkix.AlgorithmIdentifier{ 417 Algorithm: oidMGF1, 418 }, 419 SaltLength: hashFunc.Size(), 420 TrailerField: 1, 421 } 422 423 mgf1Params := pkix.AlgorithmIdentifier{ 424 Algorithm: hashOID, 425 Parameters: asn1.NullRawValue, 426 } 427 428 var err error 429 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params) 430 if err != nil { 431 panic(err) 432 } 433 434 serialized, err := asn1.Marshal(params) 435 if err != nil { 436 panic(err) 437 } 438 439 return asn1.RawValue{FullBytes: serialized} 440 } 441 442 // GetSignatureAlgorithmFromAI converts asn1 AlgorithmIdentifier to SignatureAlgorithm int 443 func GetSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm { 444 if !ai.Algorithm.Equal(oidSignatureRSAPSS) { 445 for _, details := range signatureAlgorithmDetails { 446 if ai.Algorithm.Equal(details.oid) { 447 return details.algo 448 } 449 } 450 return UnknownSignatureAlgorithm 451 } 452 453 // RSA PSS is special because it encodes important parameters 454 // in the Parameters. 455 456 var params pssParameters 457 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil { 458 return UnknownSignatureAlgorithm 459 } 460 461 var mgf1HashFunc pkix.AlgorithmIdentifier 462 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil { 463 return UnknownSignatureAlgorithm 464 } 465 466 // PSS is greatly overburdened with options. This code forces 467 // them into three buckets by requiring that the MGF1 hash 468 // function always match the message hash function (as 469 // recommended in 470 // https://tools.ietf.org/html/rfc3447#section-8.1), that the 471 // salt length matches the hash length, and that the trailer 472 // field has the default value. 473 if !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes) || 474 !params.MGF.Algorithm.Equal(oidMGF1) || 475 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) || 476 !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes) || 477 params.TrailerField != 1 { 478 return UnknownSignatureAlgorithm 479 } 480 481 switch { 482 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32: 483 return SHA256WithRSAPSS 484 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48: 485 return SHA384WithRSAPSS 486 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64: 487 return SHA512WithRSAPSS 488 } 489 490 return UnknownSignatureAlgorithm 491 } 492 493 // RFC 3279, 2.3 Public Key Algorithms 494 // 495 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 496 // 497 // rsadsi(113549) pkcs(1) 1 } 498 // 499 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } 500 // 501 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) 502 // 503 // x9-57(10040) x9cm(4) 1 } 504 // 505 // # RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters 506 // 507 // id-ecPublicKey OBJECT IDENTIFIER ::= { 508 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } 509 var ( 510 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} 511 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} 512 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} 513 ) 514 515 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { 516 switch { 517 case oid.Equal(oidPublicKeyRSA): 518 return RSA 519 case oid.Equal(oidPublicKeyDSA): 520 return DSA 521 case oid.Equal(oidPublicKeyECDSA): 522 return ECDSA 523 case oid.Equal(oidKeyEd25519): 524 return Ed25519 525 case oid.Equal(oidKeyX25519): 526 return X25519 527 } 528 return UnknownPublicKeyAlgorithm 529 } 530 531 // RFC 5480, 2.1.1.1. Named Curve 532 // 533 // secp224r1 OBJECT IDENTIFIER ::= { 534 // iso(1) identified-organization(3) certicom(132) curve(0) 33 } 535 // 536 // secp256r1 OBJECT IDENTIFIER ::= { 537 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) 538 // prime(1) 7 } 539 // 540 // secp384r1 OBJECT IDENTIFIER ::= { 541 // iso(1) identified-organization(3) certicom(132) curve(0) 34 } 542 // 543 // secp521r1 OBJECT IDENTIFIER ::= { 544 // iso(1) identified-organization(3) certicom(132) curve(0) 35 } 545 // 546 // NB: secp256r1 is equivalent to prime256v1 547 var ( 548 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} 549 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} 550 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} 551 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} 552 ) 553 554 // https://datatracker.ietf.org/doc/draft-ietf-curdle-pkix/?include_text=1 555 // id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 } 556 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 } 557 var ( 558 oidKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110} 559 oidKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112} 560 ) 561 562 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { 563 switch { 564 case oid.Equal(oidNamedCurveP224): 565 return elliptic.P224() 566 case oid.Equal(oidNamedCurveP256): 567 return elliptic.P256() 568 case oid.Equal(oidNamedCurveP384): 569 return elliptic.P384() 570 case oid.Equal(oidNamedCurveP521): 571 return elliptic.P521() 572 } 573 return nil 574 } 575 576 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { 577 switch curve { 578 case elliptic.P224(): 579 return oidNamedCurveP224, true 580 case elliptic.P256(): 581 return oidNamedCurveP256, true 582 case elliptic.P384(): 583 return oidNamedCurveP384, true 584 case elliptic.P521(): 585 return oidNamedCurveP521, true 586 } 587 588 return nil, false 589 } 590 591 // KeyUsage represents the set of actions that are valid for a given key. It's 592 // a bitmap of the KeyUsage* constants. 593 type KeyUsage int 594 595 const ( 596 KeyUsageDigitalSignature KeyUsage = 1 << iota 597 KeyUsageContentCommitment 598 KeyUsageKeyEncipherment 599 KeyUsageDataEncipherment 600 KeyUsageKeyAgreement 601 KeyUsageCertSign 602 KeyUsageCRLSign 603 KeyUsageEncipherOnly 604 KeyUsageDecipherOnly 605 ) 606 607 // RFC 5280, 4.2.1.12 Extended Key Usage 608 // 609 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } 610 // 611 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } 612 // 613 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } 614 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } 615 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } 616 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } 617 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } 618 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } 619 //var ( 620 // oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} 621 // oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} 622 // oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} 623 // oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} 624 // oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} 625 // oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} 626 // oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} 627 // oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} 628 // oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} 629 // oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} 630 // oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} 631 // oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} 632 //) 633 634 // ExtKeyUsage represents an extended set of actions that are valid for a given key. 635 // Each of the ExtKeyUsage* constants define a unique action. 636 type ExtKeyUsage int 637 638 // TODO: slight differences in case in some names. Should be easy to align with stdlib. 639 // leaving for now to not break compatibility 640 641 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. 642 var extKeyUsageOIDs = []struct { 643 extKeyUsage ExtKeyUsage 644 oid asn1.ObjectIdentifier 645 }{ 646 {ExtKeyUsageAny, oidExtKeyUsageAny}, 647 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, 648 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, 649 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, 650 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, 651 //{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, 652 {ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecEndSystem}, 653 //{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, 654 {ExtKeyUsageIpsecTunnel, oidExtKeyUsageIpsecTunnel}, 655 //{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, 656 {ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecUser}, 657 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, 658 //{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, 659 {ExtKeyUsageOcspSigning, oidExtKeyUsageOcspSigning}, 660 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, 661 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, 662 } 663 664 // TODO: slight differences in case in some names. Should be easy to align with stdlib. 665 // leaving for now to not break compatibility 666 667 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. 668 var nativeExtKeyUsageOIDs = []struct { 669 extKeyUsage ExtKeyUsage 670 oid asn1.ObjectIdentifier 671 }{ 672 {ExtKeyUsageAny, oidExtKeyUsageAny}, 673 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, 674 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, 675 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, 676 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, 677 {ExtKeyUsageIpsecEndSystem, oidExtKeyUsageIpsecEndSystem}, 678 {ExtKeyUsageIpsecTunnel, oidExtKeyUsageIpsecTunnel}, 679 {ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecUser}, 680 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, 681 {ExtKeyUsageOcspSigning, oidExtKeyUsageOcspSigning}, 682 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, 683 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, 684 } 685 686 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { 687 s := oid.String() 688 eku, ok = ekuConstants[s] 689 return 690 } 691 692 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { 693 for _, pair := range nativeExtKeyUsageOIDs { 694 if eku == pair.extKeyUsage { 695 return pair.oid, true 696 } 697 } 698 return 699 } 700 701 // A Certificate represents an X.509 certificate. 702 type Certificate struct { 703 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature). 704 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content. 705 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 706 RawSubject []byte // DER encoded Subject 707 RawIssuer []byte // DER encoded Issuer 708 709 Signature []byte 710 SignatureAlgorithm SignatureAlgorithm 711 712 SelfSigned bool 713 714 SignatureAlgorithmOID asn1.ObjectIdentifier 715 716 PublicKeyAlgorithm PublicKeyAlgorithm 717 PublicKey interface{} 718 719 PublicKeyAlgorithmOID asn1.ObjectIdentifier 720 721 Version int 722 SerialNumber *big.Int 723 Issuer pkix.Name 724 Subject pkix.Name 725 NotBefore, NotAfter time.Time // Validity bounds. 726 ValidityPeriod int 727 KeyUsage KeyUsage 728 729 IssuerUniqueId asn1.BitString 730 SubjectUniqueId asn1.BitString 731 732 // Extensions contains raw X.509 extensions. When parsing certificates, 733 // this can be used to extract non-critical extensions that are not 734 // parsed by this package. When marshaling certificates, the Extensions 735 // field is ignored, see ExtraExtensions. 736 Extensions []pkix.Extension 737 738 // ExtensionsMap contains raw x.509 extensions keyed by OID (in string 739 // representation). It allows fast membership testing of specific OIDs. Like 740 // the Extensions field this field is ignored when marshaling certificates. If 741 // multiple extensions with the same OID are present only the last 742 // pkix.Extension will be in this map. Consult the `Extensions` slice when it 743 // is required to process all extensions including duplicates. 744 ExtensionsMap map[string]pkix.Extension 745 746 // ExtraExtensions contains extensions to be copied, raw, into any 747 // marshaled certificates. Values override any extensions that would 748 // otherwise be produced based on the other fields. The ExtraExtensions 749 // field is not populated when parsing certificates, see Extensions. 750 ExtraExtensions []pkix.Extension 751 752 // UnhandledCriticalExtensions contains a list of extension IDs that 753 // were not (fully) processed when parsing. Verify will fail if this 754 // slice is non-empty, unless verification is delegated to an OS 755 // library which understands all the critical extensions. 756 // 757 // Users can access these extensions using Extensions and can remove 758 // elements from this slice if they believe that they have been 759 // handled. 760 UnhandledCriticalExtensions []asn1.ObjectIdentifier 761 762 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. 763 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. 764 765 BasicConstraintsValid bool // if true then the next two fields are valid. 766 IsCA bool 767 768 // MaxPathLen and MaxPathLenZero indicate the presence and 769 // value of the BasicConstraints' "pathLenConstraint". 770 // 771 // When parsing a certificate, a positive non-zero MaxPathLen 772 // means that the field was specified, -1 means it was unset, 773 // and MaxPathLenZero being true mean that the field was 774 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false 775 // should be treated equivalent to -1 (unset). 776 // 777 // When generating a certificate, an unset pathLenConstraint 778 // can be requested with either MaxPathLen == -1 or using the 779 // zero value for both MaxPathLen and MaxPathLenZero. 780 MaxPathLen int 781 // MaxPathLenZero indicates that BasicConstraintsValid==true and 782 // MaxPathLen==0 should be interpreted as an actual Max path length 783 // of zero. Otherwise, that combination is interpreted as MaxPathLen 784 // not being set. 785 MaxPathLenZero bool 786 787 SubjectKeyId []byte 788 AuthorityKeyId []byte 789 790 // RFC 5280, 4.2.2.1 (Authority Information Access) 791 OCSPServer []string 792 IssuingCertificateURL []string 793 794 // Subject Alternate Name values 795 OtherNames []pkix.OtherName 796 DNSNames []string 797 EmailAddresses []string 798 DirectoryNames []pkix.Name 799 EDIPartyNames []pkix.EDIPartyName 800 URIs []string 801 IPAddresses []net.IP 802 RegisteredIDs []asn1.ObjectIdentifier 803 804 // Issuer Alternative Name values 805 IANOtherNames []pkix.OtherName 806 IANDNSNames []string 807 IANEmailAddresses []string 808 IANDirectoryNames []pkix.Name 809 IANEDIPartyNames []pkix.EDIPartyName 810 IANURIs []string 811 IANIPAddresses []net.IP 812 IANRegisteredIDs []asn1.ObjectIdentifier 813 814 // Certificate Policies values 815 QualifierId [][]asn1.ObjectIdentifier 816 CPSuri [][]string 817 ExplicitTexts [][]asn1.RawValue 818 NoticeRefOrgnization [][]asn1.RawValue 819 NoticeRefNumbers [][]NoticeNumber 820 821 ParsedExplicitTexts [][]string 822 ParsedNoticeRefOrganization [][]string 823 824 // Name constraints 825 NameConstraintsCritical bool // if true then the name constraints are marked critical. 826 PermittedDNSNames []GeneralSubtreeString 827 ExcludedDNSNames []GeneralSubtreeString 828 PermittedEmailAddresses []GeneralSubtreeString 829 ExcludedEmailAddresses []GeneralSubtreeString 830 PermittedURIs []GeneralSubtreeString 831 ExcludedURIs []GeneralSubtreeString 832 PermittedIPAddresses []GeneralSubtreeIP 833 ExcludedIPAddresses []GeneralSubtreeIP 834 PermittedDirectoryNames []GeneralSubtreeName 835 ExcludedDirectoryNames []GeneralSubtreeName 836 PermittedEdiPartyNames []GeneralSubtreeEdi 837 ExcludedEdiPartyNames []GeneralSubtreeEdi 838 PermittedRegisteredIDs []GeneralSubtreeOid 839 ExcludedRegisteredIDs []GeneralSubtreeOid 840 PermittedX400Addresses []GeneralSubtreeRaw 841 ExcludedX400Addresses []GeneralSubtreeRaw 842 843 // FailedToParseNames contains values that are failed to parse, 844 // without returning an error. 845 FailedToParseNames []asn1.RawValue 846 847 // CRL Distribution Points 848 CRLDistributionPoints []string 849 850 PolicyIdentifiers []asn1.ObjectIdentifier 851 ValidationLevel CertValidationLevel 852 853 // Fingerprints 854 FingerprintMD5 CertificateFingerprint 855 FingerprintSHA1 CertificateFingerprint 856 FingerprintSHA256 CertificateFingerprint 857 FingerprintNoCT CertificateFingerprint 858 859 // SPKI 860 SPKIFingerprint CertificateFingerprint 861 SPKISubjectFingerprint CertificateFingerprint 862 TBSCertificateFingerprint CertificateFingerprint 863 864 IsPrecert bool 865 866 // Internal 867 validSignature bool 868 869 // CT 870 SignedCertificateTimestampList []*ct.SignedCertificateTimestamp 871 872 // QWACS 873 CABFOrganizationIdentifier *CABFOrganizationIdentifier 874 QCStatements *QCStatements 875 876 // Used to speed up the zlint checks. Populated by the GetParsedDNSNames method. 877 parsedDNSNames []ParsedDomainName 878 // Used to speed up the zlint checks. Populated by the GetParsedCommonName method 879 parsedCommonName *ParsedDomainName 880 881 // CAB Forum Tor Service Descriptor Hash Extensions (see EV Guidelines 882 // Appendix F) 883 TorServiceDescriptors []*TorServiceDescriptorHash 884 } 885 886 // ParsedDomainName is a structure holding a parsed domain name (CommonName or 887 // DNS SAN) and a parsing error. 888 type ParsedDomainName struct { 889 DomainString string 890 ParsedDomain *publicsuffix.DomainName 891 ParseError error 892 } 893 894 // GetParsedDNSNames returns a list of parsed SAN DNS names. It is used to cache the parsing result and 895 // speed up zlint linters. If invalidateCache is true, then the cache is repopulated with current list of string from 896 // Certificate.DNSNames. This parameter should always be false, unless the Certificate.DNSNames have been modified 897 // after calling GetParsedDNSNames the previous time. 898 func (c *Certificate) GetParsedDNSNames(invalidateCache bool) []ParsedDomainName { 899 if c.parsedDNSNames != nil && !invalidateCache { 900 return c.parsedDNSNames 901 } 902 c.parsedDNSNames = make([]ParsedDomainName, len(c.DNSNames)) 903 904 for i := range c.DNSNames { 905 var parsedDomain, parseError = publicsuffix.ParseFromListWithOptions(publicsuffix.DefaultList, 906 c.DNSNames[i], 907 &publicsuffix.FindOptions{IgnorePrivate: true, DefaultRule: publicsuffix.DefaultRule}) 908 909 c.parsedDNSNames[i].DomainString = c.DNSNames[i] 910 c.parsedDNSNames[i].ParsedDomain = parsedDomain 911 c.parsedDNSNames[i].ParseError = parseError 912 } 913 914 return c.parsedDNSNames 915 } 916 917 // GetParsedCommonName returns parsed subject CommonName. It is used to cache the parsing result and 918 // speed up zlint linters. If invalidateCache is true, then the cache is repopulated with current subject CommonName. 919 // This parameter should always be false, unless the Certificate.Subject.CommonName have been modified 920 // after calling GetParsedSubjectCommonName the previous time. 921 func (c *Certificate) GetParsedSubjectCommonName(invalidateCache bool) ParsedDomainName { 922 if c.parsedCommonName != nil && !invalidateCache { 923 return *c.parsedCommonName 924 } 925 926 var parsedDomain, parseError = publicsuffix.ParseFromListWithOptions(publicsuffix.DefaultList, 927 c.Subject.CommonName, 928 &publicsuffix.FindOptions{IgnorePrivate: true, DefaultRule: publicsuffix.DefaultRule}) 929 930 c.parsedCommonName = &ParsedDomainName{ 931 DomainString: c.Subject.CommonName, 932 ParsedDomain: parsedDomain, 933 ParseError: parseError, 934 } 935 936 return *c.parsedCommonName 937 } 938 939 // ErrUnsupportedAlgorithm results from attempting to perform an operation that 940 // involves algorithms that are not currently implemented. 941 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") 942 943 // An InsecureAlgorithmError 944 type InsecureAlgorithmError SignatureAlgorithm 945 946 func (e InsecureAlgorithmError) Error() string { 947 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) 948 } 949 950 // ConstraintViolationError results when a requested usage is not permitted by 951 // a certificate. For example: checking a signature when the public key isn't a 952 // certificate signing key. 953 type ConstraintViolationError struct{} 954 955 func (ConstraintViolationError) Error() string { 956 return "x509: invalid signature: parent certificate cannot sign this kind of certificate" 957 } 958 959 func (c *Certificate) Equal(other *Certificate) bool { 960 return bytes.Equal(c.Raw, other.Raw) 961 } 962 963 func (c *Certificate) hasSANExtension() bool { 964 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions) 965 } 966 967 // Entrust have a broken root certificate (CN=Entrust.net Certification 968 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid 969 // according to PKIX. 970 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it 971 // from the Basic Constraints requirement. 972 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 973 // 974 // TODO(agl): remove this hack once their reissued root is sufficiently 975 // widespread. 976 var entrustBrokenSPKI = []byte{ 977 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 978 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 979 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 980 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 981 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, 982 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, 983 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, 984 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, 985 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, 986 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, 987 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, 988 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, 989 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, 990 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, 991 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, 992 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, 993 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, 994 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, 995 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, 996 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, 997 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, 998 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, 999 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, 1000 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, 1001 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, 1002 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, 1003 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, 1004 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, 1005 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, 1006 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, 1007 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, 1008 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, 1009 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, 1010 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, 1011 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, 1012 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, 1013 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, 1014 } 1015 1016 // CheckSignatureFrom verifies that the signature on c is a valid signature 1017 // from parent. 1018 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) { 1019 // RFC 5280, 4.2.1.9: 1020 // "If the basic constraints extension is not present in a version 3 1021 // certificate, or the extension is present but the cA boolean is not 1022 // asserted, then the certified public key MUST NOT be used to verify 1023 // certificate signatures." 1024 // (except for Entrust, see comment above entrustBrokenSPKI) 1025 if (parent.Version == 3 && !parent.BasicConstraintsValid || 1026 parent.BasicConstraintsValid && !parent.IsCA) && 1027 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { 1028 return ConstraintViolationError{} 1029 } 1030 1031 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { 1032 return ConstraintViolationError{} 1033 } 1034 1035 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 1036 return ErrUnsupportedAlgorithm 1037 } 1038 1039 // TODO(agl): don't ignore the path length constraint. 1040 1041 if !bytes.Equal(parent.RawSubject, c.RawIssuer) { 1042 return errors.New("Mis-match issuer/subject") 1043 } 1044 1045 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) 1046 } 1047 1048 func CheckSignatureFromKey(publicKey interface{}, algo SignatureAlgorithm, signed, signature []byte) (err error) { 1049 var hashType crypto.Hash 1050 1051 switch algo { 1052 // NOTE: exception to stdlib, allow MD5 algorithm 1053 case MD5WithRSA: 1054 hashType = crypto.MD5 1055 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1: 1056 hashType = crypto.SHA1 1057 case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256: 1058 hashType = crypto.SHA256 1059 case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384: 1060 hashType = crypto.SHA384 1061 case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512: 1062 hashType = crypto.SHA512 1063 //case MD2WithRSA, MD5WithRSA: 1064 case MD2WithRSA: 1065 return InsecureAlgorithmError(algo) 1066 case Ed25519Sig: 1067 hashType = 0 1068 default: 1069 return ErrUnsupportedAlgorithm 1070 } 1071 1072 if hashType != 0 && !hashType.Available() { 1073 return ErrUnsupportedAlgorithm 1074 } 1075 digest := hash(hashType, signed) 1076 1077 switch pub := publicKey.(type) { 1078 case *rsa.PublicKey: 1079 if algo.isRSAPSS() { 1080 return rsa.VerifyPSS(pub, hashType, digest, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}) 1081 } else { 1082 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) 1083 } 1084 case *dsa.PublicKey: 1085 dsaSig := new(dsaSignature) 1086 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil { 1087 return err 1088 } else if len(rest) != 0 { 1089 return errors.New("x509: trailing data after DSA signature") 1090 } 1091 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { 1092 return errors.New("x509: DSA signature contained zero or negative values") 1093 } 1094 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { 1095 return errors.New("x509: DSA verification failure") 1096 } 1097 return 1098 case *ecdsa.PublicKey: 1099 ecdsaSig := new(ecdsaSignature) 1100 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { 1101 return err 1102 } else if len(rest) != 0 { 1103 return errors.New("x509: trailing data after ECDSA signature") 1104 } 1105 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { 1106 return errors.New("x509: ECDSA signature contained zero or negative values") 1107 } 1108 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { 1109 return errors.New("x509: ECDSA verification failure") 1110 } 1111 return 1112 case *AugmentedECDSA: 1113 ecdsaSig := new(ecdsaSignature) 1114 if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { 1115 return err 1116 } 1117 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { 1118 return errors.New("x509: ECDSA signature contained zero or negative values") 1119 } 1120 if !ecdsa.Verify(pub.Pub, digest, ecdsaSig.R, ecdsaSig.S) { 1121 return errors.New("x509: ECDSA verification failure") 1122 } 1123 return 1124 case ed25519.PublicKey: 1125 if !ed25519.Verify(pub, digest, signature) { 1126 return errors.New("x509: Ed25519 verification failure") 1127 } 1128 return 1129 } 1130 return ErrUnsupportedAlgorithm 1131 } 1132 1133 // CheckSignature verifies that signature is a valid signature over signed from 1134 // c's public key. 1135 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) { 1136 return CheckSignatureFromKey(c.PublicKey, algo, signed, signature) 1137 } 1138 1139 // CheckCRLSignature checks that the signature in crl is from c. 1140 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error { 1141 algo := GetSignatureAlgorithmFromAI(crl.SignatureAlgorithm) 1142 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) 1143 } 1144 1145 // UnhandledCriticalExtension results when the certificate contains an 1146 // unimplemented X.509 extension marked as critical. 1147 type UnhandledCriticalExtension struct { 1148 oid asn1.ObjectIdentifier 1149 message string 1150 } 1151 1152 func (h UnhandledCriticalExtension) Error() string { 1153 return fmt.Sprintf("x509: unhandled critical extension: %s | %s", h.oid, h.message) 1154 } 1155 1156 // TimeInValidityPeriod returns true if NotBefore < t < NotAfter 1157 func (c *Certificate) TimeInValidityPeriod(t time.Time) bool { 1158 return c.NotBefore.Before(t) && c.NotAfter.After(t) 1159 } 1160 1161 // RFC 5280 4.2.1.4 1162 type policyInformation struct { 1163 Policy asn1.ObjectIdentifier 1164 Qualifiers []policyQualifierInfo `asn1:"optional"` 1165 } 1166 1167 type policyQualifierInfo struct { 1168 PolicyQualifierId asn1.ObjectIdentifier 1169 Qualifier asn1.RawValue 1170 } 1171 1172 type userNotice struct { 1173 NoticeRef noticeReference `asn1:"optional"` 1174 ExplicitText asn1.RawValue `asn1:"optional"` 1175 } 1176 1177 type noticeReference struct { 1178 Organization asn1.RawValue 1179 NoticeNumbers []int 1180 } 1181 1182 type NoticeNumber []int 1183 1184 type generalSubtree struct { 1185 Value asn1.RawValue `asn1:"optional"` 1186 Min int `asn1:"tag:0,default:0,optional"` 1187 Max int `asn1:"tag:1,optional"` 1188 } 1189 1190 type GeneralSubtreeString struct { 1191 Data string 1192 Max int 1193 Min int 1194 } 1195 1196 type GeneralSubtreeIP struct { 1197 Data net.IPNet 1198 Max int 1199 Min int 1200 } 1201 1202 type GeneralSubtreeName struct { 1203 Data pkix.Name 1204 Max int 1205 Min int 1206 } 1207 1208 type GeneralSubtreeEdi struct { 1209 Data pkix.EDIPartyName 1210 Max int 1211 Min int 1212 } 1213 1214 type GeneralSubtreeOid struct { 1215 Data asn1.ObjectIdentifier 1216 Max int 1217 Min int 1218 } 1219 1220 type GeneralSubtreeRaw struct { 1221 Data asn1.RawValue 1222 Max int 1223 Min int 1224 } 1225 1226 type basicConstraints struct { 1227 IsCA bool `asn1:"optional"` 1228 MaxPathLen int `asn1:"optional,default:-1"` 1229 } 1230 1231 // RFC 5280, 4.2.1.10 1232 type nameConstraints struct { 1233 Permitted []generalSubtree `asn1:"optional,tag:0"` 1234 Excluded []generalSubtree `asn1:"optional,tag:1"` 1235 } 1236 1237 // RFC 5280, 4.2.2.1 1238 type authorityInfoAccess struct { 1239 Method asn1.ObjectIdentifier 1240 Location asn1.RawValue 1241 } 1242 1243 // RFC 5280, 4.2.1.14 1244 type distributionPoint struct { 1245 DistributionPoint distributionPointName `asn1:"optional,tag:0"` 1246 Reason asn1.BitString `asn1:"optional,tag:1"` 1247 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` 1248 } 1249 1250 type distributionPointName struct { 1251 FullName asn1.RawValue `asn1:"optional,tag:0"` 1252 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` 1253 } 1254 1255 func maxValidationLevel(a, b CertValidationLevel) CertValidationLevel { 1256 if a > b { 1257 return a 1258 } 1259 return b 1260 } 1261 1262 func hash(hashFunc crypto.Hash, raw []byte) []byte { 1263 digest := raw 1264 if hashFunc != 0 { 1265 h := hashFunc.New() 1266 h.Write(raw) 1267 digest = h.Sum(nil) 1268 } 1269 return digest 1270 } 1271 1272 func getMaxCertValidationLevel(oids []asn1.ObjectIdentifier) CertValidationLevel { 1273 maxOID := UnknownValidationLevel 1274 for _, oid := range oids { 1275 if _, ok := ExtendedValidationOIDs[oid.String()]; ok { 1276 return EV 1277 } else if _, ok := OrganizationValidationOIDs[oid.String()]; ok { 1278 maxOID = maxValidationLevel(maxOID, OV) 1279 } else if _, ok := DomainValidationOIDs[oid.String()]; ok { 1280 maxOID = maxValidationLevel(maxOID, DV) 1281 } 1282 } 1283 return maxOID 1284 } 1285 1286 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { 1287 asn1Data := keyData.PublicKey.RightAlign() 1288 switch algo { 1289 case RSA: 1290 1291 // TODO: disabled since current behaviour does not expect it. Should be enabled though 1292 // RSA public keys must have a NULL in the parameters 1293 // (https://tools.ietf.org/html/rfc3279#section-2.3.1). 1294 //if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) { 1295 // return nil, errors.New("x509: RSA key missing NULL parameters") 1296 //} 1297 1298 p := new(pkcs1PublicKey) 1299 rest, err := asn1.Unmarshal(asn1Data, p) 1300 if err != nil { 1301 return nil, err 1302 } 1303 if len(rest) != 0 { 1304 return nil, errors.New("x509: trailing data after RSA public key") 1305 } 1306 1307 // ZCrypto: Allow to parse 1308 if !asn1.AllowPermissiveParsing { 1309 1310 if p.N.Sign() <= 0 { 1311 return nil, errors.New("x509: RSA modulus is not a positive number") 1312 } 1313 if p.E <= 0 { 1314 return nil, errors.New("x509: RSA public exponent is not a positive number") 1315 } 1316 } 1317 1318 pub := &rsa.PublicKey{ 1319 E: p.E, 1320 N: p.N, 1321 } 1322 return pub, nil 1323 case DSA: 1324 var p *big.Int 1325 rest, err := asn1.Unmarshal(asn1Data, &p) 1326 if err != nil { 1327 return nil, err 1328 } 1329 if len(rest) != 0 { 1330 return nil, errors.New("x509: trailing data after DSA public key") 1331 } 1332 paramsData := keyData.Algorithm.Parameters.FullBytes 1333 params := new(dsaAlgorithmParameters) 1334 rest, err = asn1.Unmarshal(paramsData, params) 1335 if err != nil { 1336 return nil, err 1337 } 1338 if len(rest) != 0 { 1339 return nil, errors.New("x509: trailing data after DSA parameters") 1340 } 1341 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { 1342 return nil, errors.New("x509: zero or negative DSA parameter") 1343 } 1344 pub := &dsa.PublicKey{ 1345 Parameters: dsa.Parameters{ 1346 P: params.P, 1347 Q: params.Q, 1348 G: params.G, 1349 }, 1350 Y: p, 1351 } 1352 return pub, nil 1353 case ECDSA: 1354 paramsData := keyData.Algorithm.Parameters.FullBytes 1355 namedCurveOID := new(asn1.ObjectIdentifier) 1356 rest, err := asn1.Unmarshal(paramsData, namedCurveOID) 1357 if err != nil { 1358 return nil, err 1359 } 1360 if len(rest) != 0 { 1361 return nil, errors.New("x509: trailing data after ECDSA parameters") 1362 } 1363 namedCurve := namedCurveFromOID(*namedCurveOID) 1364 if namedCurve == nil { 1365 return nil, errors.New("x509: unsupported elliptic curve") 1366 } 1367 x, y := elliptic.Unmarshal(namedCurve, asn1Data) 1368 if x == nil { 1369 return nil, errors.New("x509: failed to unmarshal elliptic curve point") 1370 } 1371 key := &ecdsa.PublicKey{ 1372 Curve: namedCurve, 1373 X: x, 1374 Y: y, 1375 } 1376 1377 pub := &AugmentedECDSA{ 1378 Pub: key, 1379 Raw: keyData.PublicKey, 1380 } 1381 return pub, nil 1382 case Ed25519: 1383 p := ed25519.PublicKey(asn1Data) 1384 if len(p) > ed25519.PublicKeySize { 1385 return nil, errors.New("x509: trailing data after Ed25519 data") 1386 } 1387 return p, nil 1388 case X25519: 1389 p := X25519PublicKey(asn1Data) 1390 if len(p) > 32 { 1391 return nil, errors.New("x509: trailing data after X25519 public key") 1392 } 1393 return p, nil 1394 default: 1395 return nil, nil 1396 } 1397 } 1398 1399 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) { 1400 // RFC 5280, 4.2.1.6 1401 1402 // SubjectAltName ::= GeneralNames 1403 // 1404 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 1405 // 1406 // GeneralName ::= CHOICE { 1407 // otherName [0] OtherName, 1408 // rfc822Name [1] IA5String, 1409 // dNSName [2] IA5String, 1410 // x400Address [3] ORAddress, 1411 // directoryName [4] Name, 1412 // ediPartyName [5] EDIPartyName, 1413 // uniformResourceIdentifier [6] IA5String, 1414 // iPAddress [7] OCTET STRING, 1415 // registeredID [8] OBJECT IDENTIFIER } 1416 var seq asn1.RawValue 1417 var rest []byte 1418 if rest, err = asn1.Unmarshal(value, &seq); err != nil { 1419 return 1420 } else if len(rest) != 0 { 1421 err = errors.New("x509: trailing data after X.509 extension") 1422 return 1423 } 1424 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { 1425 err = asn1.StructuralError{Msg: "bad SAN sequence"} 1426 return 1427 } 1428 1429 rest = seq.Bytes 1430 for len(rest) > 0 { 1431 var v asn1.RawValue 1432 rest, err = asn1.Unmarshal(rest, &v) 1433 if err != nil { 1434 return 1435 } 1436 switch v.Tag { 1437 case 1: 1438 emailAddresses = append(emailAddresses, string(v.Bytes)) 1439 case 2: 1440 dnsNames = append(dnsNames, string(v.Bytes)) 1441 case 7: 1442 switch len(v.Bytes) { 1443 case net.IPv4len, net.IPv6len: 1444 ipAddresses = append(ipAddresses, v.Bytes) 1445 default: 1446 err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes))) 1447 return 1448 } 1449 } 1450 } 1451 1452 return 1453 } 1454 1455 func parseGeneralNames(value []byte) (otherNames []pkix.OtherName, dnsNames, emailAddresses, URIs []string, directoryNames []pkix.Name, ediPartyNames []pkix.EDIPartyName, ipAddresses []net.IP, registeredIDs []asn1.ObjectIdentifier, failedToParse []asn1.RawValue, err error) { 1456 // RFC 5280, 4.2.1.6 1457 1458 // SubjectAltName ::= GeneralNames 1459 // 1460 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName 1461 // 1462 // GeneralName ::= CHOICE { 1463 // otherName [0] OtherName, 1464 // rfc822Name [1] IA5String, 1465 // dNSName [2] IA5String, 1466 // x400Address [3] ORAddress, 1467 // directoryName [4] Name, 1468 // ediPartyName [5] EDIPartyName, 1469 // uniformResourceIdentifier [6] IA5String, 1470 // iPAddress [7] OCTET STRING, 1471 // registeredID [8] OBJECT IDENTIFIER } 1472 var seq asn1.RawValue 1473 if _, err = asn1.Unmarshal(value, &seq); err != nil { 1474 return 1475 } 1476 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { 1477 err = asn1.StructuralError{Msg: "bad SAN sequence"} 1478 return 1479 } 1480 1481 rest := seq.Bytes 1482 for len(rest) > 0 { 1483 var v asn1.RawValue 1484 rest, err = asn1.Unmarshal(rest, &v) 1485 if err != nil { 1486 return 1487 } 1488 switch v.Tag { 1489 case 0: 1490 var oName pkix.OtherName 1491 _, perr := asn1.UnmarshalWithParams(v.FullBytes, &oName, "tag:0") 1492 if perr != nil { 1493 if asn1.AllowPermissiveParsing { 1494 failedToParse = append(failedToParse, v) 1495 continue 1496 } 1497 err = perr 1498 return 1499 } 1500 otherNames = append(otherNames, oName) 1501 case 1: 1502 emailAddresses = append(emailAddresses, string(v.Bytes)) 1503 case 2: 1504 dnsNames = append(dnsNames, string(v.Bytes)) 1505 case 4: 1506 var rdn pkix.RDNSequence 1507 _, perr := asn1.Unmarshal(v.Bytes, &rdn) 1508 if perr != nil { 1509 if asn1.AllowPermissiveParsing { 1510 failedToParse = append(failedToParse, v) 1511 continue 1512 } 1513 err = perr 1514 return 1515 } 1516 var dir pkix.Name 1517 dir.FillFromRDNSequence(&rdn) 1518 directoryNames = append(directoryNames, dir) 1519 case 5: 1520 var ediName pkix.EDIPartyName 1521 _, perr := asn1.UnmarshalWithParams(v.FullBytes, &ediName, "tag:5") 1522 if perr != nil { 1523 if asn1.AllowPermissiveParsing { 1524 failedToParse = append(failedToParse, v) 1525 continue 1526 } 1527 err = perr 1528 return 1529 } 1530 ediPartyNames = append(ediPartyNames, ediName) 1531 case 6: 1532 URIs = append(URIs, string(v.Bytes)) 1533 case 7: 1534 switch len(v.Bytes) { 1535 case net.IPv4len, net.IPv6len: 1536 ipAddresses = append(ipAddresses, v.Bytes) 1537 default: 1538 if asn1.AllowPermissiveParsing { 1539 failedToParse = append(failedToParse, v) 1540 } else { 1541 err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes))) 1542 return 1543 } 1544 } 1545 case 8: 1546 var id asn1.ObjectIdentifier 1547 _, perr := asn1.UnmarshalWithParams(v.FullBytes, &id, "tag:8") 1548 if perr != nil { 1549 if asn1.AllowPermissiveParsing { 1550 failedToParse = append(failedToParse, v) 1551 continue 1552 } 1553 err = perr 1554 return 1555 } 1556 registeredIDs = append(registeredIDs, id) 1557 } 1558 } 1559 1560 return 1561 } 1562 1563 // TODO 1564 func parseCertificate(in *certificate) (*Certificate, error) { 1565 out := new(Certificate) 1566 out.Raw = in.Raw 1567 out.RawTBSCertificate = in.TBSCertificate.Raw 1568 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw 1569 out.RawSubject = in.TBSCertificate.Subject.FullBytes 1570 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes 1571 1572 // Fingerprints 1573 out.FingerprintMD5 = MD5Fingerprint(in.Raw) 1574 out.FingerprintSHA1 = SHA1Fingerprint(in.Raw) 1575 out.FingerprintSHA256 = SHA256Fingerprint(in.Raw) 1576 out.SPKIFingerprint = SHA256Fingerprint(in.TBSCertificate.PublicKey.Raw) 1577 out.TBSCertificateFingerprint = SHA256Fingerprint(in.TBSCertificate.Raw) 1578 1579 tbs := in.TBSCertificate 1580 originalExtensions := in.TBSCertificate.Extensions 1581 1582 // Blow away the raw data since it also includes CT data 1583 tbs.Raw = nil 1584 1585 // remove the CT extensions 1586 extensions := make([]pkix.Extension, 0, len(originalExtensions)) 1587 for _, extension := range originalExtensions { 1588 if extension.Id.Equal(oidExtensionCTPrecertificatePoison) { 1589 continue 1590 } 1591 if extension.Id.Equal(oidExtensionSignedCertificateTimestampList) { 1592 continue 1593 } 1594 extensions = append(extensions, extension) 1595 } 1596 1597 tbs.Extensions = extensions 1598 1599 tbsbytes, err := asn1.Marshal(tbs) 1600 if err != nil { 1601 return nil, err 1602 } 1603 if tbsbytes == nil { 1604 return nil, asn1.SyntaxError{Msg: "Trailing data"} 1605 } 1606 out.FingerprintNoCT = SHA256Fingerprint(tbsbytes[:]) 1607 1608 // Hash both SPKI and Subject to create a fingerprint that we can use to describe a CA 1609 hasher := sha256.New() 1610 hasher.Write(in.TBSCertificate.PublicKey.Raw) 1611 hasher.Write(in.TBSCertificate.Subject.FullBytes) 1612 out.SPKISubjectFingerprint = hasher.Sum(nil) 1613 1614 out.Signature = in.SignatureValue.RightAlign() 1615 out.SignatureAlgorithm = 1616 GetSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm) 1617 1618 out.SignatureAlgorithmOID = in.TBSCertificate.SignatureAlgorithm.Algorithm 1619 1620 out.PublicKeyAlgorithm = 1621 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) 1622 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey) 1623 if err != nil { 1624 return nil, err 1625 } 1626 1627 out.PublicKeyAlgorithmOID = in.TBSCertificate.PublicKey.Algorithm.Algorithm 1628 out.Version = in.TBSCertificate.Version + 1 1629 out.SerialNumber = in.TBSCertificate.SerialNumber 1630 1631 var issuer, subject pkix.RDNSequence 1632 if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { 1633 return nil, err 1634 } 1635 if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { 1636 return nil, err 1637 } 1638 1639 out.Issuer.FillFromRDNSequence(&issuer) 1640 out.Subject.FillFromRDNSequence(&subject) 1641 1642 // Check if self-signed 1643 if bytes.Equal(out.RawSubject, out.RawIssuer) { 1644 // Possibly self-signed, check the signature against itself. 1645 if err := out.CheckSignature(out.SignatureAlgorithm, out.RawTBSCertificate, out.Signature); err == nil { 1646 out.SelfSigned = true 1647 } 1648 } 1649 1650 out.NotBefore = in.TBSCertificate.Validity.NotBefore 1651 out.NotAfter = in.TBSCertificate.Validity.NotAfter 1652 1653 out.ValidityPeriod = int(out.NotAfter.Sub(out.NotBefore).Seconds()) 1654 1655 out.IssuerUniqueId = in.TBSCertificate.UniqueId 1656 out.SubjectUniqueId = in.TBSCertificate.SubjectUniqueId 1657 1658 out.ExtensionsMap = make(map[string]pkix.Extension, len(in.TBSCertificate.Extensions)) 1659 for _, e := range in.TBSCertificate.Extensions { 1660 out.Extensions = append(out.Extensions, e) 1661 out.ExtensionsMap[e.Id.String()] = e 1662 1663 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { 1664 switch e.Id[3] { 1665 case 15: 1666 // RFC 5280, 4.2.1.3 1667 var usageBits asn1.BitString 1668 _, err := asn1.Unmarshal(e.Value, &usageBits) 1669 1670 if err == nil { 1671 var usage int 1672 for i := 0; i < 9; i++ { 1673 if usageBits.At(i) != 0 { 1674 usage |= 1 << uint(i) 1675 } 1676 } 1677 out.KeyUsage = KeyUsage(usage) 1678 continue 1679 } 1680 case 19: 1681 // RFC 5280, 4.2.1.9 1682 var constraints basicConstraints 1683 _, err := asn1.Unmarshal(e.Value, &constraints) 1684 1685 if err == nil { 1686 out.BasicConstraintsValid = true 1687 out.IsCA = constraints.IsCA 1688 out.MaxPathLen = constraints.MaxPathLen 1689 out.MaxPathLenZero = out.MaxPathLen == 0 1690 continue 1691 } 1692 case 17: 1693 out.OtherNames, out.DNSNames, out.EmailAddresses, 1694 out.URIs, out.DirectoryNames, out.EDIPartyNames, 1695 out.IPAddresses, out.RegisteredIDs, out.FailedToParseNames, err = parseGeneralNames(e.Value) 1696 if err != nil { 1697 return nil, err 1698 } 1699 1700 if len(out.DNSNames) > 0 || len(out.EmailAddresses) > 0 || len(out.IPAddresses) > 0 { 1701 continue 1702 } 1703 // If we didn't parse any of the names then we 1704 // fall through to the critical check below. 1705 case 18: 1706 out.IANOtherNames, out.IANDNSNames, out.IANEmailAddresses, 1707 out.IANURIs, out.IANDirectoryNames, out.IANEDIPartyNames, 1708 out.IANIPAddresses, out.IANRegisteredIDs, out.FailedToParseNames, err = parseGeneralNames(e.Value) 1709 if err != nil { 1710 return nil, err 1711 } 1712 1713 if len(out.IANDNSNames) > 0 || len(out.IANEmailAddresses) > 0 || len(out.IANIPAddresses) > 0 { 1714 continue 1715 } 1716 case 30: 1717 // RFC 5280, 4.2.1.10 1718 1719 // NameConstraints ::= SEQUENCE { 1720 // permittedSubtrees [0] GeneralSubtrees OPTIONAL, 1721 // excludedSubtrees [1] GeneralSubtrees OPTIONAL } 1722 // 1723 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree 1724 // 1725 // GeneralSubtree ::= SEQUENCE { 1726 // base GeneralName, 1727 // Min [0] BaseDistance DEFAULT 0, 1728 // Max [1] BaseDistance OPTIONAL } 1729 // 1730 // BaseDistance ::= INTEGER (0..MAX) 1731 1732 var constraints nameConstraints 1733 _, err := asn1.Unmarshal(e.Value, &constraints) 1734 if err != nil { 1735 return nil, err 1736 } 1737 1738 if e.Critical { 1739 out.NameConstraintsCritical = true 1740 } 1741 1742 for _, subtree := range constraints.Permitted { 1743 switch subtree.Value.Tag { 1744 case 1: 1745 out.PermittedEmailAddresses = append(out.PermittedEmailAddresses, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1746 case 2: 1747 out.PermittedDNSNames = append(out.PermittedDNSNames, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1748 case 3: 1749 out.PermittedX400Addresses = append(out.PermittedX400Addresses, GeneralSubtreeRaw{Data: subtree.Value, Max: subtree.Max, Min: subtree.Min}) 1750 case 4: 1751 var rawdn pkix.RDNSequence 1752 if _, err := asn1.Unmarshal(subtree.Value.Bytes, &rawdn); err != nil { 1753 return out, err 1754 } 1755 var dn pkix.Name 1756 dn.FillFromRDNSequence(&rawdn) 1757 out.PermittedDirectoryNames = append(out.PermittedDirectoryNames, GeneralSubtreeName{Data: dn, Max: subtree.Max, Min: subtree.Min}) 1758 case 5: 1759 var ediName pkix.EDIPartyName 1760 _, err = asn1.UnmarshalWithParams(subtree.Value.FullBytes, &ediName, "tag:5") 1761 if err != nil { 1762 return out, err 1763 } 1764 out.PermittedEdiPartyNames = append(out.PermittedEdiPartyNames, GeneralSubtreeEdi{Data: ediName, Max: subtree.Max, Min: subtree.Min}) 1765 case 6: 1766 out.PermittedURIs = append(out.PermittedURIs, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1767 case 7: 1768 switch len(subtree.Value.Bytes) { 1769 case net.IPv4len * 2: 1770 ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv4len], Mask: subtree.Value.Bytes[net.IPv4len:]} 1771 out.PermittedIPAddresses = append(out.PermittedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min}) 1772 case net.IPv6len * 2: 1773 ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv6len], Mask: subtree.Value.Bytes[net.IPv6len:]} 1774 out.PermittedIPAddresses = append(out.PermittedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min}) 1775 default: 1776 if !asn1.AllowPermissiveParsing { 1777 return out, errors.New("x509: certificate name constraint contained IP address range of length " + strconv.Itoa(len(subtree.Value.Bytes))) 1778 } 1779 } 1780 case 8: 1781 var id asn1.ObjectIdentifier 1782 _, err = asn1.UnmarshalWithParams(subtree.Value.FullBytes, &id, "tag:8") 1783 if err != nil { 1784 return out, err 1785 } 1786 out.PermittedRegisteredIDs = append(out.PermittedRegisteredIDs, GeneralSubtreeOid{Data: id, Max: subtree.Max, Min: subtree.Min}) 1787 } 1788 } 1789 for _, subtree := range constraints.Excluded { 1790 switch subtree.Value.Tag { 1791 case 1: 1792 out.ExcludedEmailAddresses = append(out.ExcludedEmailAddresses, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1793 case 2: 1794 out.ExcludedDNSNames = append(out.ExcludedDNSNames, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1795 case 3: 1796 out.ExcludedX400Addresses = append(out.ExcludedX400Addresses, GeneralSubtreeRaw{Data: subtree.Value, Max: subtree.Max, Min: subtree.Min}) 1797 case 4: 1798 var rawdn pkix.RDNSequence 1799 if _, err := asn1.Unmarshal(subtree.Value.Bytes, &rawdn); err != nil { 1800 return out, err 1801 } 1802 var dn pkix.Name 1803 dn.FillFromRDNSequence(&rawdn) 1804 out.ExcludedDirectoryNames = append(out.ExcludedDirectoryNames, GeneralSubtreeName{Data: dn, Max: subtree.Max, Min: subtree.Min}) 1805 case 5: 1806 var ediName pkix.EDIPartyName 1807 _, err = asn1.Unmarshal(subtree.Value.Bytes, &ediName) 1808 if err != nil { 1809 return out, err 1810 } 1811 out.ExcludedEdiPartyNames = append(out.ExcludedEdiPartyNames, GeneralSubtreeEdi{Data: ediName, Max: subtree.Max, Min: subtree.Min}) 1812 case 6: 1813 out.ExcludedURIs = append(out.ExcludedURIs, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min}) 1814 case 7: 1815 switch len(subtree.Value.Bytes) { 1816 case net.IPv4len * 2: 1817 ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv4len], Mask: subtree.Value.Bytes[net.IPv4len:]} 1818 out.ExcludedIPAddresses = append(out.ExcludedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min}) 1819 case net.IPv6len * 2: 1820 ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv6len], Mask: subtree.Value.Bytes[net.IPv6len:]} 1821 out.ExcludedIPAddresses = append(out.ExcludedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min}) 1822 default: 1823 if !asn1.AllowPermissiveParsing { 1824 return out, errors.New("x509: certificate name constraint contained IP address range of length " + strconv.Itoa(len(subtree.Value.Bytes))) 1825 } 1826 } 1827 case 8: 1828 var id asn1.ObjectIdentifier 1829 _, err = asn1.Unmarshal(subtree.Value.Bytes, &id) 1830 if err != nil { 1831 return out, err 1832 } 1833 out.ExcludedRegisteredIDs = append(out.ExcludedRegisteredIDs, GeneralSubtreeOid{Data: id, Max: subtree.Max, Min: subtree.Min}) 1834 } 1835 } 1836 continue 1837 1838 case 31: 1839 // RFC 5280, 4.2.1.14 1840 1841 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 1842 // 1843 // DistributionPoint ::= SEQUENCE { 1844 // distributionPoint [0] DistributionPointName OPTIONAL, 1845 // reasons [1] ReasonFlags OPTIONAL, 1846 // cRLIssuer [2] GeneralNames OPTIONAL } 1847 // 1848 // DistributionPointName ::= CHOICE { 1849 // fullName [0] GeneralNames, 1850 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 1851 1852 var cdp []distributionPoint 1853 _, err := asn1.Unmarshal(e.Value, &cdp) 1854 if err != nil { 1855 return nil, err 1856 } 1857 1858 for _, dp := range cdp { 1859 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty. 1860 if len(dp.DistributionPoint.FullName.Bytes) == 0 { 1861 continue 1862 } 1863 1864 var n asn1.RawValue 1865 dpName := dp.DistributionPoint.FullName.Bytes 1866 // FullName is a GeneralNames, which is a SEQUENCE OF 1867 // GeneralName, which in turn is a CHOICE. 1868 // Per https://www.ietf.org/rfc/rfc5280.txt, multiple names 1869 // for a single DistributionPoint give different pointers to 1870 // the same CRL. 1871 for len(dpName) > 0 { 1872 dpName, err = asn1.Unmarshal(dpName, &n) 1873 if err != nil { 1874 return nil, err 1875 } 1876 if n.Tag == 6 { 1877 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) 1878 } 1879 } 1880 } 1881 continue 1882 1883 case 35: 1884 // RFC 5280, 4.2.1.1 1885 var a authKeyId 1886 _, err = asn1.Unmarshal(e.Value, &a) 1887 if err != nil { 1888 return nil, err 1889 } 1890 out.AuthorityKeyId = a.Id 1891 continue 1892 1893 case 37: 1894 // RFC 5280, 4.2.1.12. Extended Key Usage 1895 1896 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } 1897 // 1898 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId 1899 // 1900 // KeyPurposeId ::= OBJECT IDENTIFIER 1901 1902 var keyUsage []asn1.ObjectIdentifier 1903 _, err = asn1.Unmarshal(e.Value, &keyUsage) 1904 if err != nil { 1905 if !asn1.AllowPermissiveParsing { 1906 return nil, err 1907 } 1908 continue 1909 } 1910 1911 for _, u := range keyUsage { 1912 if extKeyUsage, ok := extKeyUsageFromOID(u); ok { 1913 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) 1914 } else { 1915 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) 1916 } 1917 } 1918 1919 continue 1920 1921 case 14: 1922 // RFC 5280, 4.2.1.2 1923 var keyid []byte 1924 _, err = asn1.Unmarshal(e.Value, &keyid) 1925 if err != nil { 1926 return nil, err 1927 } 1928 out.SubjectKeyId = keyid 1929 continue 1930 1931 case 32: 1932 // RFC 5280 4.2.1.4: Certificate Policies 1933 var policies []policyInformation 1934 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { 1935 return nil, err 1936 } 1937 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) 1938 out.QualifierId = make([][]asn1.ObjectIdentifier, len(policies)) 1939 out.ExplicitTexts = make([][]asn1.RawValue, len(policies)) 1940 out.NoticeRefOrgnization = make([][]asn1.RawValue, len(policies)) 1941 out.NoticeRefNumbers = make([][]NoticeNumber, len(policies)) 1942 out.ParsedExplicitTexts = make([][]string, len(policies)) 1943 out.ParsedNoticeRefOrganization = make([][]string, len(policies)) 1944 out.CPSuri = make([][]string, len(policies)) 1945 1946 for i, policy := range policies { 1947 out.PolicyIdentifiers[i] = policy.Policy 1948 // parse optional Qualifier for zlint 1949 for _, qualifier := range policy.Qualifiers { 1950 out.QualifierId[i] = append(out.QualifierId[i], qualifier.PolicyQualifierId) 1951 userNoticeOID := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2} 1952 cpsURIOID := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 1} 1953 if qualifier.PolicyQualifierId.Equal(userNoticeOID) { 1954 var un userNotice 1955 _, err := asn1.Unmarshal(qualifier.Qualifier.FullBytes, &un) 1956 if err != nil && !asn1.AllowPermissiveParsing { 1957 return nil, err 1958 } 1959 if err == nil { 1960 if len(un.ExplicitText.Bytes) != 0 { 1961 out.ExplicitTexts[i] = append(out.ExplicitTexts[i], un.ExplicitText) 1962 out.ParsedExplicitTexts[i] = append(out.ParsedExplicitTexts[i], string(un.ExplicitText.Bytes)) 1963 } 1964 if un.NoticeRef.Organization.Bytes != nil || un.NoticeRef.NoticeNumbers != nil { 1965 out.NoticeRefOrgnization[i] = append(out.NoticeRefOrgnization[i], un.NoticeRef.Organization) 1966 out.NoticeRefNumbers[i] = append(out.NoticeRefNumbers[i], un.NoticeRef.NoticeNumbers) 1967 out.ParsedNoticeRefOrganization[i] = append(out.ParsedNoticeRefOrganization[i], string(un.NoticeRef.Organization.Bytes)) 1968 } 1969 } 1970 } 1971 if qualifier.PolicyQualifierId.Equal(cpsURIOID) { 1972 var cpsURIRaw asn1.RawValue 1973 _, err = asn1.Unmarshal(qualifier.Qualifier.FullBytes, &cpsURIRaw) 1974 if err != nil && !asn1.AllowPermissiveParsing { 1975 return nil, err 1976 } 1977 if err == nil { 1978 out.CPSuri[i] = append(out.CPSuri[i], string(cpsURIRaw.Bytes)) 1979 } 1980 } 1981 } 1982 } 1983 if out.SelfSigned { 1984 out.ValidationLevel = UnknownValidationLevel 1985 } else { 1986 // See http://unmitigatedrisk.com/?p=203 1987 validationLevel := getMaxCertValidationLevel(out.PolicyIdentifiers) 1988 if validationLevel == UnknownValidationLevel { 1989 if (len(out.Subject.Organization) > 0 && out.Subject.Organization[0] == out.Subject.CommonName) || (len(out.Subject.OrganizationalUnit) > 0 && strings.Contains(out.Subject.OrganizationalUnit[0], "Domain Control Validated")) { 1990 if len(out.Subject.Locality) == 0 && len(out.Subject.Province) == 0 && len(out.Subject.PostalCode) == 0 { 1991 validationLevel = DV 1992 } 1993 } else if len(out.Subject.Organization) > 0 && out.Subject.Organization[0] == "Persona Not Validated" && strings.Contains(out.Issuer.CommonName, "StartCom") { 1994 validationLevel = DV 1995 } 1996 } 1997 out.ValidationLevel = validationLevel 1998 } 1999 } 2000 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { 2001 // RFC 5280 4.2.2.1: Authority Information Access 2002 var aia []authorityInfoAccess 2003 if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { 2004 return nil, err 2005 } 2006 2007 for _, v := range aia { 2008 // GeneralName: uniformResourceIdentifier [6] IA5String 2009 if v.Location.Tag != 6 { 2010 continue 2011 } 2012 if v.Method.Equal(oidAuthorityInfoAccessOcsp) { 2013 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) 2014 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { 2015 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) 2016 } 2017 } 2018 } else if e.Id.Equal(oidExtensionSignedCertificateTimestampList) { 2019 err := parseSignedCertificateTimestampList(out, e) 2020 if err != nil { 2021 return nil, err 2022 } 2023 } else if e.Id.Equal(oidExtensionCTPrecertificatePoison) { 2024 if e.Value[0] == 5 && e.Value[1] == 0 { 2025 out.IsPrecert = true 2026 continue 2027 } else { 2028 if !asn1.AllowPermissiveParsing { 2029 return nil, UnhandledCriticalExtension{e.Id, "Malformed precert poison"} 2030 } 2031 } 2032 } else if e.Id.Equal(oidBRTorServiceDescriptor) { 2033 descs, err := parseTorServiceDescriptorSyntax(e) 2034 if err != nil { 2035 return nil, err 2036 } 2037 out.TorServiceDescriptors = descs 2038 } else if e.Id.Equal(oidExtCABFOrganizationID) { 2039 cabf := CABFOrganizationIDASN{} 2040 _, err := asn1.Unmarshal(e.Value, &cabf) 2041 if err != nil { 2042 return nil, err 2043 } 2044 out.CABFOrganizationIdentifier = &CABFOrganizationIdentifier{ 2045 Scheme: cabf.RegistrationSchemeIdentifier, 2046 Country: cabf.RegistrationCountry, 2047 Reference: cabf.RegistrationReference, 2048 State: cabf.RegistrationStateOrProvince, 2049 } 2050 } else if e.Id.Equal(oidExtQCStatements) { 2051 rawStatements := QCStatementsASN{} 2052 _, err := asn1.Unmarshal(e.Value, &rawStatements.QCStatements) 2053 if err != nil { 2054 return nil, err 2055 } 2056 qcStatements := QCStatements{} 2057 if err := qcStatements.Parse(&rawStatements); err != nil { 2058 return nil, err 2059 } 2060 out.QCStatements = &qcStatements 2061 } 2062 2063 //if e.Critical { 2064 // return out, UnhandledCriticalExtension{e.Id} 2065 //} 2066 } 2067 2068 return out, nil 2069 } 2070 2071 func parseSignedCertificateTimestampList(out *Certificate, ext pkix.Extension) error { 2072 var scts []byte 2073 if _, err := asn1.Unmarshal(ext.Value, &scts); err != nil { 2074 return err 2075 } 2076 // ignore length of 2077 if len(scts) < 2 { 2078 return errors.New("malformed SCT extension: incomplete length field") 2079 } 2080 scts = scts[2:] 2081 headerLength := 2 2082 for { 2083 switch len(scts) { 2084 case 0: 2085 return nil 2086 case 1: 2087 return errors.New("malformed SCT extension: trailing data") 2088 default: 2089 sctLength := int(scts[1]) + (int(scts[0]) << 8) + headerLength 2090 if !(sctLength <= len(scts)) { 2091 return errors.New("malformed SCT extension: incomplete SCT") 2092 } 2093 sct, err := ct.DeserializeSCT(bytes.NewReader(scts[headerLength:sctLength])) 2094 if err != nil { 2095 return fmt.Errorf("malformed SCT extension: SCT parse err: %v", err) 2096 } 2097 out.SignedCertificateTimestampList = append(out.SignedCertificateTimestampList, sct) 2098 scts = scts[sctLength:] 2099 } 2100 } 2101 } 2102 2103 // ParseCertificate parses a single certificate from the given ASN.1 DER data. 2104 func ParseCertificate(asn1Data []byte) (*Certificate, error) { 2105 var cert certificate 2106 rest, err := asn1.Unmarshal(asn1Data, &cert) 2107 if err != nil { 2108 return nil, err 2109 } 2110 if len(rest) > 0 { 2111 return nil, asn1.SyntaxError{Msg: "trailing data"} 2112 } 2113 2114 return parseCertificate(&cert) 2115 } 2116 2117 // ParseCertificates parses one or more certificates from the given ASN.1 DER 2118 // data. The certificates must be concatenated with no intermediate padding. 2119 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { 2120 var v []*certificate 2121 2122 for len(asn1Data) > 0 { 2123 cert := new(certificate) 2124 var err error 2125 asn1Data, err = asn1.Unmarshal(asn1Data, cert) 2126 if err != nil { 2127 return nil, err 2128 } 2129 v = append(v, cert) 2130 } 2131 2132 ret := make([]*Certificate, len(v)) 2133 for i, ci := range v { 2134 cert, err := parseCertificate(ci) 2135 if err != nil { 2136 return nil, err 2137 } 2138 ret[i] = cert 2139 } 2140 2141 return ret, nil 2142 } 2143 2144 func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) { 2145 var tbsCert tbsCertificate 2146 rest, err := asn1.Unmarshal(asn1Data, &tbsCert) 2147 if err != nil { 2148 //log.Print("Err unmarshalling asn1Data", asn1Data, rest) 2149 return nil, err 2150 } 2151 if len(rest) > 0 { 2152 return nil, asn1.SyntaxError{Msg: "trailing data"} 2153 } 2154 return parseCertificate(&certificate{ 2155 Raw: tbsCert.Raw, 2156 TBSCertificate: tbsCert}) 2157 } 2158 2159 // SubjectAndKey represents a (subjecty, subject public key info) tuple. 2160 type SubjectAndKey struct { 2161 RawSubject []byte 2162 RawSubjectPublicKeyInfo []byte 2163 Fingerprint CertificateFingerprint 2164 PublicKey interface{} 2165 PublicKeyAlgorithm PublicKeyAlgorithm 2166 } 2167 2168 // SubjectAndKey returns a SubjectAndKey for this certificate. 2169 func (c *Certificate) SubjectAndKey() *SubjectAndKey { 2170 return &SubjectAndKey{ 2171 RawSubject: c.RawSubject, 2172 RawSubjectPublicKeyInfo: c.RawSubjectPublicKeyInfo, 2173 Fingerprint: c.SPKISubjectFingerprint, 2174 PublicKey: c.PublicKey, 2175 PublicKeyAlgorithm: c.PublicKeyAlgorithm, 2176 } 2177 } 2178 2179 func reverseBitsInAByte(in byte) byte { 2180 b1 := in>>4 | in<<4 2181 b2 := b1>>2&0x33 | b1<<2&0xcc 2182 b3 := b2>>1&0x55 | b2<<1&0xaa 2183 return b3 2184 } 2185 2186 // asn1BitLength returns the bit-length of bitString by considering the 2187 // most-significant bit in a byte to be the "first" bit. This convention 2188 // matches ASN.1, but differs from almost everything else. 2189 func asn1BitLength(bitString []byte) int { 2190 bitLen := len(bitString) * 8 2191 2192 for i := range bitString { 2193 b := bitString[len(bitString)-i-1] 2194 2195 for bit := uint(0); bit < 8; bit++ { 2196 if (b>>bit)&1 == 1 { 2197 return bitLen 2198 } 2199 bitLen-- 2200 } 2201 } 2202 2203 return 0 2204 } 2205 2206 var ( 2207 oidExtensionSubjectKeyId = []int{2, 5, 29, 14} 2208 oidExtensionKeyUsage = []int{2, 5, 29, 15} 2209 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} 2210 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} 2211 oidExtensionBasicConstraints = []int{2, 5, 29, 19} 2212 oidExtensionSubjectAltName = []int{2, 5, 29, 17} 2213 oidExtensionIssuerAltName = []int{2, 5, 29, 18} 2214 oidExtensionCertificatePolicies = []int{2, 5, 29, 32} 2215 oidExtensionNameConstraints = []int{2, 5, 29, 30} 2216 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} 2217 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} 2218 oidExtensionSignedCertificateTimestampList = []int{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2} 2219 ) 2220 2221 var ( 2222 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} 2223 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} 2224 ) 2225 2226 // oidNotInExtensions returns whether an extension with the given oid exists in 2227 // extensions. 2228 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { 2229 for _, e := range extensions { 2230 if e.Id.Equal(oid) { 2231 return true 2232 } 2233 } 2234 return false 2235 } 2236 2237 // marshalSANs marshals a list of addresses into a the contents of an X.509 2238 // SubjectAlternativeName extension. 2239 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { 2240 var rawValues []asn1.RawValue 2241 for _, name := range dnsNames { 2242 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) 2243 } 2244 for _, email := range emailAddresses { 2245 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) 2246 } 2247 for _, rawIP := range ipAddresses { 2248 // If possible, we always want to encode IPv4 addresses in 4 bytes. 2249 ip := rawIP.To4() 2250 if ip == nil { 2251 ip = rawIP 2252 } 2253 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) 2254 } 2255 return asn1.Marshal(rawValues) 2256 } 2257 2258 // NOTE ignoring authorityKeyID argument 2259 func buildExtensions(template *Certificate, _ []byte) (ret []pkix.Extension, err error) { 2260 ret = make([]pkix.Extension, 10 /* Max number of elements. */) 2261 n := 0 2262 2263 if template.KeyUsage != 0 && 2264 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { 2265 ret[n].Id = oidExtensionKeyUsage 2266 ret[n].Critical = true 2267 2268 var a [2]byte 2269 a[0] = reverseBitsInAByte(byte(template.KeyUsage)) 2270 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) 2271 2272 l := 1 2273 if a[1] != 0 { 2274 l = 2 2275 } 2276 2277 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: asn1BitLength(a[0:l])}) 2278 if err != nil { 2279 return 2280 } 2281 n++ 2282 } 2283 2284 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && 2285 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { 2286 ret[n].Id = oidExtensionExtendedKeyUsage 2287 2288 var oids []asn1.ObjectIdentifier 2289 for _, u := range template.ExtKeyUsage { 2290 if oid, ok := oidFromExtKeyUsage(u); ok { 2291 oids = append(oids, oid) 2292 } else { 2293 panic("internal error") 2294 } 2295 } 2296 2297 oids = append(oids, template.UnknownExtKeyUsage...) 2298 2299 ret[n].Value, err = asn1.Marshal(oids) 2300 if err != nil { 2301 return 2302 } 2303 n++ 2304 } 2305 2306 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { 2307 // Leaving MaxPathLen as zero indicates that no Max path 2308 // length is desired, unless MaxPathLenZero is set. A value of 2309 // -1 causes encoding/asn1 to omit the value as desired. 2310 maxPathLen := template.MaxPathLen 2311 if maxPathLen == 0 && !template.MaxPathLenZero { 2312 maxPathLen = -1 2313 } 2314 ret[n].Id = oidExtensionBasicConstraints 2315 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen}) 2316 ret[n].Critical = true 2317 if err != nil { 2318 return 2319 } 2320 n++ 2321 } 2322 2323 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { 2324 ret[n].Id = oidExtensionSubjectKeyId 2325 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) 2326 if err != nil { 2327 return 2328 } 2329 n++ 2330 } 2331 2332 if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { 2333 ret[n].Id = oidExtensionAuthorityKeyId 2334 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) 2335 if err != nil { 2336 return 2337 } 2338 n++ 2339 } 2340 2341 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && 2342 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { 2343 ret[n].Id = oidExtensionAuthorityInfoAccess 2344 var aiaValues []authorityInfoAccess 2345 for _, name := range template.OCSPServer { 2346 aiaValues = append(aiaValues, authorityInfoAccess{ 2347 Method: oidAuthorityInfoAccessOcsp, 2348 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 2349 }) 2350 } 2351 for _, name := range template.IssuingCertificateURL { 2352 aiaValues = append(aiaValues, authorityInfoAccess{ 2353 Method: oidAuthorityInfoAccessIssuers, 2354 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, 2355 }) 2356 } 2357 ret[n].Value, err = asn1.Marshal(aiaValues) 2358 if err != nil { 2359 return 2360 } 2361 n++ 2362 } 2363 2364 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 2365 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 2366 ret[n].Id = oidExtensionSubjectAltName 2367 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 2368 if err != nil { 2369 return 2370 } 2371 n++ 2372 } 2373 2374 if len(template.PolicyIdentifiers) > 0 && 2375 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { 2376 ret[n].Id = oidExtensionCertificatePolicies 2377 policies := make([]policyInformation, len(template.PolicyIdentifiers)) 2378 for i, policy := range template.PolicyIdentifiers { 2379 policies[i].Policy = policy 2380 } 2381 ret[n].Value, err = asn1.Marshal(policies) 2382 if err != nil { 2383 return 2384 } 2385 n++ 2386 } 2387 2388 // TODO: this can be cleaned up in go1.10 2389 if (len(template.PermittedEmailAddresses) > 0 || len(template.PermittedDNSNames) > 0 || len(template.PermittedDirectoryNames) > 0 || 2390 len(template.PermittedIPAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 || len(template.ExcludedDNSNames) > 0 || 2391 len(template.ExcludedDirectoryNames) > 0 || len(template.ExcludedIPAddresses) > 0) && 2392 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { 2393 ret[n].Id = oidExtensionNameConstraints 2394 if template.NameConstraintsCritical { 2395 ret[n].Critical = true 2396 } 2397 2398 var out nameConstraints 2399 2400 for _, permitted := range template.PermittedEmailAddresses { 2401 out.Permitted = append(out.Permitted, generalSubtree{Value: asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(permitted.Data)}}) 2402 } 2403 for _, excluded := range template.ExcludedEmailAddresses { 2404 out.Excluded = append(out.Excluded, generalSubtree{Value: asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(excluded.Data)}}) 2405 } 2406 for _, permitted := range template.PermittedDNSNames { 2407 out.Permitted = append(out.Permitted, generalSubtree{Value: asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(permitted.Data)}}) 2408 } 2409 for _, excluded := range template.ExcludedDNSNames { 2410 out.Excluded = append(out.Excluded, generalSubtree{Value: asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(excluded.Data)}}) 2411 } 2412 for _, permitted := range template.PermittedDirectoryNames { 2413 var dn []byte 2414 dn, err = asn1.Marshal(permitted.Data.ToRDNSequence()) 2415 if err != nil { 2416 return 2417 } 2418 out.Permitted = append(out.Permitted, generalSubtree{Value: asn1.RawValue{Tag: 4, Class: 2, IsCompound: true, Bytes: dn}}) 2419 } 2420 for _, excluded := range template.ExcludedDirectoryNames { 2421 var dn []byte 2422 dn, err = asn1.Marshal(excluded.Data.ToRDNSequence()) 2423 if err != nil { 2424 return 2425 } 2426 out.Excluded = append(out.Excluded, generalSubtree{Value: asn1.RawValue{Tag: 4, Class: 2, IsCompound: true, Bytes: dn}}) 2427 } 2428 for _, permitted := range template.PermittedIPAddresses { 2429 ip := append(permitted.Data.IP, permitted.Data.Mask...) 2430 out.Permitted = append(out.Permitted, generalSubtree{Value: asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}}) 2431 } 2432 for _, excluded := range template.ExcludedIPAddresses { 2433 ip := append(excluded.Data.IP, excluded.Data.Mask...) 2434 out.Excluded = append(out.Excluded, generalSubtree{Value: asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}}) 2435 } 2436 ret[n].Value, err = asn1.Marshal(out) 2437 if err != nil { 2438 return 2439 } 2440 n++ 2441 } 2442 2443 if len(template.CRLDistributionPoints) > 0 && 2444 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { 2445 ret[n].Id = oidExtensionCRLDistributionPoints 2446 2447 var crlDp []distributionPoint 2448 for _, name := range template.CRLDistributionPoints { 2449 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) 2450 2451 dp := distributionPoint{ 2452 DistributionPoint: distributionPointName{ 2453 FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName}, 2454 }, 2455 } 2456 crlDp = append(crlDp, dp) 2457 } 2458 2459 ret[n].Value, err = asn1.Marshal(crlDp) 2460 if err != nil { 2461 return 2462 } 2463 n++ 2464 } 2465 2466 // Adding another extension here? Remember to update the Max number 2467 // of elements in the make() at the top of the function. 2468 2469 return append(ret[:n], template.ExtraExtensions...), nil 2470 } 2471 2472 func subjectBytes(cert *Certificate) ([]byte, error) { 2473 if len(cert.RawSubject) > 0 { 2474 return cert.RawSubject, nil 2475 } 2476 2477 return asn1.Marshal(cert.Subject.ToRDNSequence()) 2478 } 2479 2480 // signingParamsForPublicKey returns the parameters to use for signing with 2481 // priv. If requestedSigAlgo is not zero then it overrides the default 2482 // signature algorithm. 2483 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { 2484 var pubType PublicKeyAlgorithm 2485 shouldHash := true 2486 2487 switch pub := pub.(type) { 2488 case *rsa.PublicKey: 2489 pubType = RSA 2490 hashFunc = crypto.SHA256 2491 sigAlgo.Algorithm = oidSignatureSHA256WithRSA 2492 sigAlgo.Parameters = asn1.NullRawValue 2493 2494 case *ecdsa.PublicKey: 2495 pubType = ECDSA 2496 2497 switch pub.Curve { 2498 case elliptic.P224(), elliptic.P256(): 2499 hashFunc = crypto.SHA256 2500 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 2501 case elliptic.P384(): 2502 hashFunc = crypto.SHA384 2503 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 2504 case elliptic.P521(): 2505 hashFunc = crypto.SHA512 2506 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 2507 default: 2508 err = errors.New("x509: unknown elliptic curve") 2509 } 2510 2511 case ed25519.PublicKey: 2512 pubType = Ed25519 2513 hashFunc = 0 2514 shouldHash = false 2515 sigAlgo.Algorithm = oidKeyEd25519 2516 2517 default: 2518 err = errors.New("x509: only RSA, ECDSA, Ed25519, and X25519 keys supported") 2519 } 2520 2521 if err != nil { 2522 return 2523 } 2524 2525 if requestedSigAlgo == 0 { 2526 return 2527 } 2528 2529 found := false 2530 for _, details := range signatureAlgorithmDetails { 2531 if details.algo == requestedSigAlgo { 2532 if details.pubKeyAlgo != pubType { 2533 err = errors.New("x509: requested SignatureAlgorithm does not match private key type") 2534 return 2535 } 2536 sigAlgo.Algorithm, hashFunc = details.oid, details.hash 2537 if hashFunc == 0 && shouldHash { 2538 err = errors.New("x509: cannot sign with hash function requested") 2539 return 2540 } 2541 if requestedSigAlgo.isRSAPSS() { 2542 sigAlgo.Parameters = rsaPSSParameters(hashFunc) 2543 } 2544 found = true 2545 break 2546 } 2547 } 2548 2549 if !found { 2550 err = errors.New("x509: unknown SignatureAlgorithm") 2551 } 2552 2553 return 2554 } 2555 2556 // CreateCertificate creates a new certificate based on a template. 2557 // The following members of template are used: AuthorityKeyId, 2558 // BasicConstraintsValid, DNSNames, ExcludedDNSDomains, ExtKeyUsage, 2559 // IsCA, KeyUsage, MaxPathLen, MaxPathLenZero, NotAfter, NotBefore, 2560 // PermittedDNSDomains, PermittedDNSDomainsCritical, SerialNumber, 2561 // SignatureAlgorithm, Subject, SubjectKeyId, and UnknownExtKeyUsage. 2562 // 2563 // The certificate is signed by parent. If parent is equal to template then the 2564 // certificate is self-signed. The parameter pub is the public key of the 2565 // signee and priv is the private key of the signer. 2566 // 2567 // The returned slice is the certificate in DER encoding. 2568 // 2569 // All keys types that are implemented via crypto.Signer are supported (This 2570 // includes *rsa.PublicKey and *ecdsa.PublicKey.) 2571 // 2572 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, 2573 // unless the resulting certificate is self-signed. Otherwise the value from 2574 // template will be used. 2575 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) { 2576 key, ok := priv.(crypto.Signer) 2577 if !ok { 2578 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2579 } 2580 2581 if template.SerialNumber == nil { 2582 return nil, errors.New("x509: no SerialNumber given") 2583 } 2584 2585 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 2586 if err != nil { 2587 return nil, err 2588 } 2589 2590 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub) 2591 if err != nil { 2592 return nil, err 2593 } 2594 2595 asn1Issuer, err := subjectBytes(parent) 2596 if err != nil { 2597 return 2598 } 2599 2600 asn1Subject, err := subjectBytes(template) 2601 if err != nil { 2602 return 2603 } 2604 2605 authorityKeyId := template.AuthorityKeyId 2606 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 { 2607 authorityKeyId = parent.SubjectKeyId 2608 } 2609 2610 extensions, err := buildExtensions(template, authorityKeyId) 2611 if err != nil { 2612 return 2613 } 2614 2615 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} 2616 c := tbsCertificate{ 2617 Version: 2, 2618 SerialNumber: template.SerialNumber, 2619 SignatureAlgorithm: signatureAlgorithm, 2620 Issuer: asn1.RawValue{FullBytes: asn1Issuer}, 2621 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, 2622 Subject: asn1.RawValue{FullBytes: asn1Subject}, 2623 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, 2624 Extensions: extensions, 2625 } 2626 2627 tbsCertContents, err := asn1.Marshal(c) 2628 if err != nil { 2629 return 2630 } 2631 c.Raw = tbsCertContents 2632 2633 digest := hash(hashFunc, c.Raw) 2634 2635 var signerOpts crypto.SignerOpts 2636 signerOpts = hashFunc 2637 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() { 2638 signerOpts = &rsa.PSSOptions{ 2639 SaltLength: rsa.PSSSaltLengthEqualsHash, 2640 Hash: hashFunc, 2641 } 2642 } 2643 2644 var signature []byte 2645 signature, err = key.Sign(rand, digest, signerOpts) 2646 if err != nil { 2647 return 2648 } 2649 2650 return asn1.Marshal(certificate{ 2651 nil, 2652 c, 2653 signatureAlgorithm, 2654 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2655 }) 2656 } 2657 2658 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded 2659 // CRL. 2660 var pemCRLPrefix = []byte("-----BEGIN X509 CRL") 2661 2662 // pemType is the type of a PEM encoded CRL. 2663 var pemType = "X509 CRL" 2664 2665 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM 2666 // encoded CRLs will appear where they should be DER encoded, so this function 2667 // will transparently handle PEM encoding as long as there isn't any leading 2668 // garbage. 2669 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) { 2670 if bytes.HasPrefix(crlBytes, pemCRLPrefix) { 2671 block, _ := pem.Decode(crlBytes) 2672 if block != nil && block.Type == pemType { 2673 crlBytes = block.Bytes 2674 } 2675 } 2676 return ParseDERCRL(crlBytes) 2677 } 2678 2679 // ParseDERCRL parses a DER encoded CRL from the given bytes. 2680 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { 2681 certList := new(pkix.CertificateList) 2682 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil { 2683 return nil, err 2684 } else if len(rest) != 0 { 2685 return nil, errors.New("x509: trailing data after CRL") 2686 } 2687 return certList, nil 2688 } 2689 2690 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that 2691 // contains the given list of revoked certificates. 2692 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { 2693 key, ok := priv.(crypto.Signer) 2694 if !ok { 2695 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2696 } 2697 2698 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0) 2699 if err != nil { 2700 return nil, err 2701 } 2702 2703 // Force revocation times to UTC per RFC 5280. 2704 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts)) 2705 for i, rc := range revokedCerts { 2706 rc.RevocationTime = rc.RevocationTime.UTC() 2707 revokedCertsUTC[i] = rc 2708 } 2709 2710 tbsCertList := pkix.TBSCertificateList{ 2711 Version: 1, 2712 Signature: signatureAlgorithm, 2713 Issuer: c.Subject.ToRDNSequence(), 2714 ThisUpdate: now.UTC(), 2715 NextUpdate: expiry.UTC(), 2716 RevokedCertificates: revokedCertsUTC, 2717 } 2718 2719 // Authority Key Id 2720 if len(c.SubjectKeyId) > 0 { 2721 var aki pkix.Extension 2722 aki.Id = oidExtensionAuthorityKeyId 2723 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId}) 2724 if err != nil { 2725 return 2726 } 2727 tbsCertList.Extensions = append(tbsCertList.Extensions, aki) 2728 } 2729 2730 tbsCertListContents, err := asn1.Marshal(tbsCertList) 2731 if err != nil { 2732 return 2733 } 2734 2735 digest := hash(hashFunc, tbsCertListContents) 2736 2737 var signature []byte 2738 signature, err = key.Sign(rand, digest, hashFunc) 2739 if err != nil { 2740 return 2741 } 2742 2743 return asn1.Marshal(pkix.CertificateList{ 2744 TBSCertList: tbsCertList, 2745 SignatureAlgorithm: signatureAlgorithm, 2746 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 2747 }) 2748 } 2749 2750 // CertificateRequest represents a PKCS #10, certificate signature request. 2751 type CertificateRequest struct { 2752 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). 2753 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. 2754 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. 2755 RawSubject []byte // DER encoded Subject. 2756 2757 Version int 2758 Signature []byte 2759 SignatureAlgorithm SignatureAlgorithm 2760 2761 PublicKeyAlgorithm PublicKeyAlgorithm 2762 PublicKey interface{} 2763 2764 Subject pkix.Name 2765 2766 // Attributes is the dried husk of a bug and shouldn't be used. 2767 Attributes []pkix.AttributeTypeAndValueSET 2768 2769 // Extensions contains raw X.509 extensions. When parsing CSRs, this 2770 // can be used to extract extensions that are not parsed by this 2771 // package. 2772 Extensions []pkix.Extension 2773 2774 // ExtraExtensions contains extensions to be copied, raw, into any 2775 // marshaled CSR. Values override any extensions that would otherwise 2776 // be produced based on the other fields but are overridden by any 2777 // extensions specified in Attributes. 2778 // 2779 // The ExtraExtensions field is not populated when parsing CSRs, see 2780 // Extensions. 2781 ExtraExtensions []pkix.Extension 2782 2783 // Subject Alternate Name values. 2784 DNSNames []string 2785 EmailAddresses []string 2786 IPAddresses []net.IP 2787 } 2788 2789 // These structures reflect the ASN.1 structure of X.509 certificate 2790 // signature requests (see RFC 2986): 2791 2792 type tbsCertificateRequest struct { 2793 Raw asn1.RawContent 2794 Version int 2795 Subject asn1.RawValue 2796 PublicKey publicKeyInfo 2797 RawAttributes []asn1.RawValue `asn1:"tag:0"` 2798 } 2799 2800 type certificateRequest struct { 2801 Raw asn1.RawContent 2802 TBSCSR tbsCertificateRequest 2803 SignatureAlgorithm pkix.AlgorithmIdentifier 2804 SignatureValue asn1.BitString 2805 } 2806 2807 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested 2808 // extensions in a CSR. 2809 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} 2810 2811 // newRawAttributes converts AttributeTypeAndValueSETs from a template 2812 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes. 2813 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) { 2814 var rawAttributes []asn1.RawValue 2815 b, err := asn1.Marshal(attributes) 2816 if err != nil { 2817 return nil, err 2818 } 2819 rest, err := asn1.Unmarshal(b, &rawAttributes) 2820 if err != nil { 2821 return nil, err 2822 } 2823 if len(rest) != 0 { 2824 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes") 2825 } 2826 return rawAttributes, nil 2827 } 2828 2829 // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs. 2830 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET { 2831 var attributes []pkix.AttributeTypeAndValueSET 2832 for _, rawAttr := range rawAttributes { 2833 var attr pkix.AttributeTypeAndValueSET 2834 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr) 2835 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET 2836 // (i.e.: challengePassword or unstructuredName). 2837 if err == nil && len(rest) == 0 { 2838 attributes = append(attributes, attr) 2839 } 2840 } 2841 return attributes 2842 } 2843 2844 // parseCSRExtensions parses the attributes from a CSR and extracts any 2845 // requested extensions. 2846 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) { 2847 // pkcs10Attribute reflects the Attribute structure from section 4.1 of 2848 // https://tools.ietf.org/html/rfc2986. 2849 type pkcs10Attribute struct { 2850 Id asn1.ObjectIdentifier 2851 Values []asn1.RawValue `asn1:"set"` 2852 } 2853 2854 var ret []pkix.Extension 2855 for _, rawAttr := range rawAttributes { 2856 var attr pkcs10Attribute 2857 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 { 2858 // Ignore attributes that don't parse. 2859 continue 2860 } 2861 2862 if !attr.Id.Equal(oidExtensionRequest) { 2863 continue 2864 } 2865 2866 var extensions []pkix.Extension 2867 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil { 2868 return nil, err 2869 } 2870 ret = append(ret, extensions...) 2871 } 2872 2873 return ret, nil 2874 } 2875 2876 // CreateCertificateRequest creates a new certificate request based on a 2877 // template. The following members of template are used: Attributes, DNSNames, 2878 // EmailAddresses, ExtraExtensions, IPAddresses, SignatureAlgorithm, and 2879 // Subject. The private key is the private key of the signer. 2880 // 2881 // The returned slice is the certificate request in DER encoding. 2882 // 2883 // All keys types that are implemented via crypto.Signer are supported (This 2884 // includes *rsa.PublicKey and *ecdsa.PublicKey.) 2885 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { 2886 key, ok := priv.(crypto.Signer) 2887 if !ok { 2888 return nil, errors.New("x509: certificate private key does not implement crypto.Signer") 2889 } 2890 2891 var hashFunc crypto.Hash 2892 var sigAlgo pkix.AlgorithmIdentifier 2893 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm) 2894 if err != nil { 2895 return nil, err 2896 } 2897 2898 var publicKeyBytes []byte 2899 var publicKeyAlgorithm pkix.AlgorithmIdentifier 2900 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public()) 2901 if err != nil { 2902 return nil, err 2903 } 2904 2905 var extensions []pkix.Extension 2906 2907 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && 2908 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { 2909 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) 2910 if err != nil { 2911 return nil, err 2912 } 2913 2914 extensions = append(extensions, pkix.Extension{ 2915 Id: oidExtensionSubjectAltName, 2916 Value: sanBytes, 2917 }) 2918 } 2919 2920 extensions = append(extensions, template.ExtraExtensions...) 2921 2922 var attributes []pkix.AttributeTypeAndValueSET 2923 attributes = append(attributes, template.Attributes...) 2924 2925 if len(extensions) > 0 { 2926 // specifiedExtensions contains all the extensions that we 2927 // found specified via template.Attributes. 2928 specifiedExtensions := make(map[string]bool) 2929 2930 for _, atvSet := range template.Attributes { 2931 if !atvSet.Type.Equal(oidExtensionRequest) { 2932 continue 2933 } 2934 2935 for _, atvs := range atvSet.Value { 2936 for _, atv := range atvs { 2937 specifiedExtensions[atv.Type.String()] = true 2938 } 2939 } 2940 } 2941 2942 atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions)) 2943 for _, e := range extensions { 2944 if specifiedExtensions[e.Id.String()] { 2945 // Attributes already contained a value for 2946 // this extension and it takes priority. 2947 continue 2948 } 2949 2950 atvs = append(atvs, pkix.AttributeTypeAndValue{ 2951 // There is no place for the critical flag in a CSR. 2952 Type: e.Id, 2953 Value: e.Value, 2954 }) 2955 } 2956 2957 // Append the extensions to an existing attribute if possible. 2958 appended := false 2959 for _, atvSet := range attributes { 2960 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { 2961 continue 2962 } 2963 2964 atvSet.Value[0] = append(atvSet.Value[0], atvs...) 2965 appended = true 2966 break 2967 } 2968 2969 // Otherwise, add a new attribute for the extensions. 2970 if !appended { 2971 attributes = append(attributes, pkix.AttributeTypeAndValueSET{ 2972 Type: oidExtensionRequest, 2973 Value: [][]pkix.AttributeTypeAndValue{ 2974 atvs, 2975 }, 2976 }) 2977 } 2978 } 2979 2980 asn1Subject := template.RawSubject 2981 if len(asn1Subject) == 0 { 2982 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) 2983 if err != nil { 2984 return 2985 } 2986 } 2987 2988 rawAttributes, err := newRawAttributes(attributes) 2989 if err != nil { 2990 return 2991 } 2992 2993 tbsCSR := tbsCertificateRequest{ 2994 Version: 0, // PKCS #10, RFC 2986 2995 Subject: asn1.RawValue{FullBytes: asn1Subject}, 2996 PublicKey: publicKeyInfo{ 2997 Algorithm: publicKeyAlgorithm, 2998 PublicKey: asn1.BitString{ 2999 Bytes: publicKeyBytes, 3000 BitLength: len(publicKeyBytes) * 8, 3001 }, 3002 }, 3003 RawAttributes: rawAttributes, 3004 } 3005 3006 tbsCSRContents, err := asn1.Marshal(tbsCSR) 3007 if err != nil { 3008 return 3009 } 3010 tbsCSR.Raw = tbsCSRContents 3011 3012 digest := hash(hashFunc, tbsCSRContents) 3013 3014 var signature []byte 3015 signature, err = key.Sign(rand, digest, hashFunc) 3016 if err != nil { 3017 return 3018 } 3019 3020 return asn1.Marshal(certificateRequest{ 3021 TBSCSR: tbsCSR, 3022 SignatureAlgorithm: sigAlgo, 3023 SignatureValue: asn1.BitString{ 3024 Bytes: signature, 3025 BitLength: len(signature) * 8, 3026 }, 3027 }) 3028 } 3029 3030 // ParseCertificateRequest parses a single certificate request from the 3031 // given ASN.1 DER data. 3032 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { 3033 var csr certificateRequest 3034 3035 rest, err := asn1.Unmarshal(asn1Data, &csr) 3036 if err != nil { 3037 return nil, err 3038 } else if len(rest) != 0 { 3039 return nil, asn1.SyntaxError{Msg: "trailing data"} 3040 } 3041 3042 return parseCertificateRequest(&csr) 3043 } 3044 3045 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { 3046 out := &CertificateRequest{ 3047 Raw: in.Raw, 3048 RawTBSCertificateRequest: in.TBSCSR.Raw, 3049 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, 3050 RawSubject: in.TBSCSR.Subject.FullBytes, 3051 3052 Signature: in.SignatureValue.RightAlign(), 3053 SignatureAlgorithm: GetSignatureAlgorithmFromAI(in.SignatureAlgorithm), 3054 3055 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), 3056 3057 Version: in.TBSCSR.Version, 3058 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes), 3059 } 3060 3061 var err error 3062 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey) 3063 if err != nil { 3064 return nil, err 3065 } 3066 3067 var subject pkix.RDNSequence 3068 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { 3069 return nil, err 3070 } else if len(rest) != 0 { 3071 return nil, errors.New("x509: trailing data after X.509 Subject") 3072 } 3073 3074 out.Subject.FillFromRDNSequence(&subject) 3075 3076 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil { 3077 return nil, err 3078 } 3079 3080 for _, extension := range out.Extensions { 3081 if extension.Id.Equal(oidExtensionSubjectAltName) { 3082 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(extension.Value) 3083 if err != nil { 3084 return nil, err 3085 } 3086 } 3087 } 3088 3089 return out, nil 3090 } 3091 3092 // CheckSignature reports whether the signature on c is valid. 3093 func (c *CertificateRequest) CheckSignature() error { 3094 return CheckSignatureFromKey(c.PublicKey, c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature) 3095 } 3096 3097 // RevocationList contains the fields used to create an X.509 v2 Certificate 3098 // Revocation list with CreateRevocationList. 3099 type RevocationList struct { 3100 // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList, 3101 // signatureAlgorithm, and signatureValue.) 3102 Raw []byte 3103 // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1 3104 // DER. 3105 RawTBSRevocationList []byte 3106 // RawIssuer contains the DER encoded Issuer. 3107 RawIssuer []byte 3108 3109 // Issuer contains the DN of the issuing certificate. 3110 Issuer pkix.Name 3111 // AuthorityKeyId is used to identify the public key associated with the 3112 // issuing certificate. It is populated from the authorityKeyIdentifier 3113 // extension when parsing a CRL. It is ignored when creating a CRL; the 3114 // extension is populated from the issuing certificate itself. 3115 AuthorityKeyId []byte 3116 3117 Signature []byte 3118 // SignatureAlgorithm is used to determine the signature algorithm to be 3119 // used when signing the CRL. If 0 the default algorithm for the signing 3120 // key will be used. 3121 SignatureAlgorithm SignatureAlgorithm 3122 3123 // RevokedCertificates is used to populate the revokedCertificates 3124 // sequence in the CRL, it may be empty. RevokedCertificates may be nil, 3125 // in which case an empty CRL will be created. 3126 RevokedCertificates []RevokedCertificate 3127 3128 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL, 3129 // which should be a monotonically increasing sequence number for a given 3130 // CRL scope and CRL issuer. It is also populated from the cRLNumber 3131 // extension when parsing a CRL. 3132 Number *big.Int 3133 3134 // ThisUpdate is used to populate the thisUpdate field in the CRL, which 3135 // indicates the issuance date of the CRL. 3136 ThisUpdate time.Time 3137 // NextUpdate is used to populate the nextUpdate field in the CRL, which 3138 // indicates the date by which the next CRL will be issued. NextUpdate 3139 // must be greater than ThisUpdate. 3140 NextUpdate time.Time 3141 3142 // Extensions contains raw X.509 extensions. When creating a CRL, 3143 // the Extensions field is ignored, see ExtraExtensions. 3144 Extensions []pkix.Extension 3145 3146 // ExtraExtensions contains any additional extensions to add directly to 3147 // the CRL. 3148 ExtraExtensions []pkix.Extension 3149 } 3150 3151 // These structures reflect the ASN.1 structure of X.509 CRLs better than 3152 // the existing crypto/x509/pkix variants do. These mirror the existing 3153 // certificate structs in this file. 3154 // 3155 // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of 3156 // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly. 3157 type certificateList struct { 3158 TBSCertList tbsCertificateList 3159 SignatureAlgorithm pkix.AlgorithmIdentifier 3160 SignatureValue asn1.BitString 3161 } 3162 3163 type tbsCertificateList struct { 3164 Raw asn1.RawContent 3165 Version int `asn1:"optional,default:0"` 3166 Signature pkix.AlgorithmIdentifier 3167 Issuer asn1.RawValue 3168 ThisUpdate time.Time 3169 NextUpdate time.Time `asn1:"optional"` 3170 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"` 3171 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"` 3172 } 3173 3174 func isIA5String(s string) error { 3175 for _, r := range s { 3176 // Per RFC5280 "IA5String is limited to the set of ASCII characters" 3177 if r > unicode.MaxASCII { 3178 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s) 3179 } 3180 } 3181 3182 return nil 3183 } 3184 3185 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm { 3186 if ai.Algorithm.Equal(oidSignatureEd25519) { 3187 // RFC 8410, Section 3 3188 // > For all of the OIDs, the parameters MUST be absent. 3189 if len(ai.Parameters.FullBytes) != 0 { 3190 return UnknownSignatureAlgorithm 3191 } 3192 } 3193 3194 if !ai.Algorithm.Equal(oidSignatureRSAPSS) { 3195 for _, details := range signatureAlgorithmDetails { 3196 if ai.Algorithm.Equal(details.oid) { 3197 return details.algo 3198 } 3199 } 3200 return UnknownSignatureAlgorithm 3201 } 3202 3203 // RSA PSS is special because it encodes important parameters 3204 // in the Parameters. 3205 3206 var params pssParameters 3207 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil { 3208 return UnknownSignatureAlgorithm 3209 } 3210 3211 var mgf1HashFunc pkix.AlgorithmIdentifier 3212 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil { 3213 return UnknownSignatureAlgorithm 3214 } 3215 3216 // PSS is greatly overburdened with options. This code forces them into 3217 // three buckets by requiring that the MGF1 hash function always match the 3218 // message hash function (as recommended in RFC 3447, Section 8.1), that the 3219 // salt length matches the hash length, and that the trailer field has the 3220 // default value. 3221 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) || 3222 !params.MGF.Algorithm.Equal(oidMGF1) || 3223 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) || 3224 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) || 3225 params.TrailerField != 1 { 3226 return UnknownSignatureAlgorithm 3227 } 3228 3229 switch { 3230 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32: 3231 return SHA256WithRSAPSS 3232 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48: 3233 return SHA384WithRSAPSS 3234 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64: 3235 return SHA512WithRSAPSS 3236 } 3237 3238 return UnknownSignatureAlgorithm 3239 } 3240 3241 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List, 3242 // according to RFC 5280, based on template. 3243 // 3244 // The CRL is signed by priv which should be the private key associated with 3245 // the public key in the issuer certificate. 3246 // 3247 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in 3248 // order to use it as a CRL issuer. 3249 // 3250 // The issuer distinguished name CRL field and authority key identifier 3251 // extension are populated using the issuer certificate. issuer must have 3252 // SubjectKeyId set. 3253 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) { 3254 if template == nil { 3255 return nil, errors.New("x509: template can not be nil") 3256 } 3257 if issuer == nil { 3258 return nil, errors.New("x509: issuer can not be nil") 3259 } 3260 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 { 3261 return nil, errors.New("x509: issuer must have the crlSign key usage bit set") 3262 } 3263 if len(issuer.SubjectKeyId) == 0 { 3264 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier") 3265 } 3266 if template.NextUpdate.Before(template.ThisUpdate) { 3267 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate") 3268 } 3269 if template.Number == nil { 3270 return nil, errors.New("x509: template contains nil Number field") 3271 } 3272 3273 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm) 3274 if err != nil { 3275 return nil, err 3276 } 3277 3278 // Convert the ReasonCode field to a proper extension, and force revocation 3279 // times to UTC per RFC 5280. 3280 // STARTBLOCK: This block differs from upstream. Upstream: revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates)) 3281 revokedCerts := make([]pkix.RevokedCertificate, len(template.RevokedCertificates)) 3282 for i, rc := range template.RevokedCertificates { 3283 prc := pkix.RevokedCertificate{ 3284 SerialNumber: rc.SerialNumber, 3285 RevocationTime: rc.RevocationTime.UTC(), 3286 } 3287 3288 // Copy over any extra extensions, except for a Reason Code extension, 3289 // because we'll synthesize that ourselves to ensure it is correct. 3290 exts := make([]pkix.Extension, 0) 3291 for _, ext := range rc.ExtraExtensions { 3292 if ext.Id.Equal(oidExtensionReasonCode) { 3293 continue 3294 } 3295 exts = append(exts, ext) 3296 } 3297 3298 // Only add a reasonCode extension if the reason is non-zero, as per 3299 // RFC 5280 Section 5.3.1. 3300 if rc.ReasonCode != nil && *rc.ReasonCode != 0 { 3301 reasonBytes, err := asn1.Marshal(asn1.Enumerated(*rc.ReasonCode)) 3302 if err != nil { 3303 return nil, err 3304 } 3305 3306 exts = append(exts, pkix.Extension{ 3307 Id: oidExtensionReasonCode, 3308 Value: reasonBytes, 3309 }) 3310 } 3311 3312 if len(exts) > 0 { 3313 prc.Extensions = exts 3314 } 3315 revokedCerts[i] = prc 3316 } 3317 // ENDBLOCK 3318 3319 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId}) 3320 if err != nil { 3321 return nil, err 3322 } 3323 3324 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) { 3325 return nil, errors.New("x509: CRL number exceeds 20 octets") 3326 } 3327 crlNum, err := asn1.Marshal(template.Number) 3328 if err != nil { 3329 return nil, err 3330 } 3331 3332 // Correctly use the issuer's subject sequence if one is specified. 3333 issuerSubject, err := subjectBytes(issuer) 3334 if err != nil { 3335 return nil, err 3336 } 3337 3338 tbsCertList := tbsCertificateList{ 3339 Version: 1, // v2 3340 Signature: signatureAlgorithm, 3341 Issuer: asn1.RawValue{FullBytes: issuerSubject}, 3342 ThisUpdate: template.ThisUpdate.UTC(), 3343 NextUpdate: template.NextUpdate.UTC(), 3344 Extensions: []pkix.Extension{ 3345 { 3346 Id: oidExtensionAuthorityKeyId, 3347 Value: aki, 3348 }, 3349 { 3350 Id: oidExtensionCRLNumber, 3351 Value: crlNum, 3352 }, 3353 }, 3354 } 3355 if len(revokedCerts) > 0 { 3356 tbsCertList.RevokedCertificates = revokedCerts 3357 } 3358 3359 if len(template.ExtraExtensions) > 0 { 3360 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...) 3361 } 3362 3363 tbsCertListContents, err := asn1.Marshal(tbsCertList) 3364 if err != nil { 3365 return nil, err 3366 } 3367 3368 // Optimization to only marshal this struct once, when signing and 3369 // then embedding in certificateList below. 3370 tbsCertList.Raw = tbsCertListContents 3371 3372 input := tbsCertListContents 3373 if hashFunc != 0 { 3374 h := hashFunc.New() 3375 h.Write(tbsCertListContents) 3376 input = h.Sum(nil) 3377 } 3378 var signerOpts crypto.SignerOpts = hashFunc 3379 if template.SignatureAlgorithm.isRSAPSS() { 3380 signerOpts = &rsa.PSSOptions{ 3381 SaltLength: rsa.PSSSaltLengthEqualsHash, 3382 Hash: hashFunc, 3383 } 3384 } 3385 3386 signature, err := priv.Sign(rand, input, signerOpts) 3387 if err != nil { 3388 return nil, err 3389 } 3390 3391 return asn1.Marshal(certificateList{ 3392 TBSCertList: tbsCertList, 3393 SignatureAlgorithm: signatureAlgorithm, 3394 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, 3395 }) 3396 } 3397 3398 // CheckSignatureFrom verifies that the signature on rl is a valid signature 3399 // from issuer. 3400 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error { 3401 if parent.Version == 3 && !parent.BasicConstraintsValid || 3402 parent.BasicConstraintsValid && !parent.IsCA { 3403 return ConstraintViolationError{} 3404 } 3405 3406 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 { 3407 return ConstraintViolationError{} 3408 } 3409 3410 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { 3411 return ErrUnsupportedAlgorithm 3412 } 3413 3414 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature) 3415 }