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