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