github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/msp/mspimpl.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package msp 8 9 import ( 10 "bytes" 11 "crypto/x509" 12 "crypto/x509/pkix" 13 "encoding/asn1" 14 "encoding/hex" 15 "encoding/pem" 16 "errors" 17 "fmt" 18 "math/big" 19 "reflect" 20 "time" 21 22 "github.com/golang/protobuf/proto" 23 "github.com/hyperledger/fabric/bccsp" 24 "github.com/hyperledger/fabric/bccsp/factory" 25 "github.com/hyperledger/fabric/bccsp/signer" 26 m "github.com/hyperledger/fabric/protos/msp" 27 ) 28 29 // This is an instantiation of an MSP that 30 // uses BCCSP for its cryptographic primitives. 31 type bccspmsp struct { 32 // list of CA certs we trust 33 rootCerts []Identity 34 35 // list of intermediate certs we trust 36 intermediateCerts []Identity 37 38 // list of CA TLS certs we trust 39 tlsRootCerts [][]byte 40 41 // list of intermediate TLS certs we trust 42 tlsIntermediateCerts [][]byte 43 44 // certificationTreeInternalNodesMap whose keys correspond to the raw material 45 // (DER representation) of a certificate casted to a string, and whose values 46 // are boolean. True means that the certificate is an internal node of the certification tree. 47 // False means that the certificate corresponds to a leaf of the certification tree. 48 certificationTreeInternalNodesMap map[string]bool 49 50 // list of signing identities 51 signer SigningIdentity 52 53 // list of admin identities 54 admins []Identity 55 56 // the crypto provider 57 bccsp bccsp.BCCSP 58 59 // the provider identifier for this MSP 60 name string 61 62 // verification options for MSP members 63 opts *x509.VerifyOptions 64 65 // list of certificate revocation lists 66 CRL []*pkix.CertificateList 67 68 // list of OUs 69 ouIdentifiers map[string][][]byte 70 71 // cryptoConfig contains 72 cryptoConfig *m.FabricCryptoConfig 73 } 74 75 // NewBccspMsp returns an MSP instance backed up by a BCCSP 76 // crypto provider. It handles x.509 certificates and can 77 // generate identities and signing identities backed by 78 // certificates and keypairs 79 func NewBccspMsp() (MSP, error) { 80 mspLogger.Debugf("Creating BCCSP-based MSP instance") 81 82 bccsp := factory.GetDefault() 83 theMsp := &bccspmsp{} 84 theMsp.bccsp = bccsp 85 86 return theMsp, nil 87 } 88 89 func (msp *bccspmsp) getCertFromPem(idBytes []byte) (*x509.Certificate, error) { 90 if idBytes == nil { 91 return nil, fmt.Errorf("getIdentityFromConf error: nil idBytes") 92 } 93 94 // Decode the pem bytes 95 pemCert, _ := pem.Decode(idBytes) 96 if pemCert == nil { 97 return nil, fmt.Errorf("getIdentityFromBytes error: could not decode pem bytes [%v]", idBytes) 98 } 99 100 // get a cert 101 var cert *x509.Certificate 102 cert, err := x509.ParseCertificate(pemCert.Bytes) 103 if err != nil { 104 return nil, fmt.Errorf("getIdentityFromBytes error: failed to parse x509 cert, err %s", err) 105 } 106 107 return cert, nil 108 } 109 110 func (msp *bccspmsp) getIdentityFromConf(idBytes []byte) (Identity, bccsp.Key, error) { 111 // get a cert 112 cert, err := msp.getCertFromPem(idBytes) 113 if err != nil { 114 return nil, nil, err 115 } 116 117 // get the public key in the right format 118 certPubK, err := msp.bccsp.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: true}) 119 120 // Use the hash of the identity's certificate as id in the IdentityIdentifier 121 hashOpt, err := bccsp.GetHashOpt(msp.cryptoConfig.IdentityIdentifierHashFunction) 122 if err != nil { 123 return nil, nil, fmt.Errorf("getIdentityFromConf failed getting hash function options [%s]", err) 124 } 125 126 digest, err := msp.bccsp.Hash(cert.Raw, hashOpt) 127 if err != nil { 128 return nil, nil, fmt.Errorf("getIdentityFromConf failed hashing raw certificate to compute the id of the IdentityIdentifier [%s]", err) 129 } 130 131 id := &IdentityIdentifier{ 132 Mspid: msp.name, 133 Id: hex.EncodeToString(digest)} 134 135 mspId, err := newIdentity(id, cert, certPubK, msp) 136 if err != nil { 137 return nil, nil, err 138 } 139 140 return mspId, certPubK, nil 141 } 142 143 func (msp *bccspmsp) getSigningIdentityFromConf(sidInfo *m.SigningIdentityInfo) (SigningIdentity, error) { 144 if sidInfo == nil { 145 return nil, fmt.Errorf("getIdentityFromBytes error: nil sidInfo") 146 } 147 148 // Extract the public part of the identity 149 idPub, pubKey, err := msp.getIdentityFromConf(sidInfo.PublicSigner) 150 if err != nil { 151 return nil, err 152 } 153 154 // Find the matching private key in the BCCSP keystore 155 privKey, err := msp.bccsp.GetKey(pubKey.SKI()) 156 // Less Secure: Attempt to import Private Key from KeyInfo, if BCCSP was not able to find the key 157 if err != nil { 158 mspLogger.Debugf("Could not find SKI [%s], trying KeyMaterial field: %s\n", hex.EncodeToString(pubKey.SKI()), err) 159 if sidInfo.PrivateSigner == nil || sidInfo.PrivateSigner.KeyMaterial == nil { 160 return nil, fmt.Errorf("KeyMaterial not found in SigningIdentityInfo") 161 } 162 163 pemKey, _ := pem.Decode(sidInfo.PrivateSigner.KeyMaterial) 164 privKey, err = msp.bccsp.KeyImport(pemKey.Bytes, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: true}) 165 if err != nil { 166 return nil, fmt.Errorf("getIdentityFromBytes error: Failed to import EC private key, err %s", err) 167 } 168 } 169 170 // get the peer signer 171 peerSigner, err := signer.New(msp.bccsp, privKey) 172 if err != nil { 173 return nil, fmt.Errorf("getIdentityFromBytes error: Failed initializing bccspCryptoSigner, err %s", err) 174 } 175 176 // Use the hash of the identity's certificate as id in the IdentityIdentifier 177 hashOpt, err := bccsp.GetHashOpt(msp.cryptoConfig.IdentityIdentifierHashFunction) 178 if err != nil { 179 return nil, fmt.Errorf("getIdentityFromBytes failed getting hash function options [%s]", err) 180 } 181 182 digest, err := msp.bccsp.Hash(idPub.(*identity).cert.Raw, hashOpt) 183 if err != nil { 184 return nil, fmt.Errorf("Failed hashing raw certificate to compute the id of the IdentityIdentifier [%s]", err) 185 } 186 187 id := &IdentityIdentifier{ 188 Mspid: msp.name, 189 Id: hex.EncodeToString(digest)} 190 191 return newSigningIdentity(id, idPub.(*identity).cert, idPub.(*identity).pk, peerSigner, msp) 192 } 193 194 /* 195 This is the definition of the ASN.1 marshalling of AuthorityKeyIdentifier 196 from https://www.ietf.org/rfc/rfc5280.txt 197 198 AuthorityKeyIdentifier ::= SEQUENCE { 199 keyIdentifier [0] KeyIdentifier OPTIONAL, 200 authorityCertIssuer [1] GeneralNames OPTIONAL, 201 authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } 202 203 KeyIdentifier ::= OCTET STRING 204 205 CertificateSerialNumber ::= INTEGER 206 207 */ 208 209 type authorityKeyIdentifier struct { 210 KeyIdentifier []byte `asn1:"optional,tag:0"` 211 AuthorityCertIssuer []byte `asn1:"optional,tag:1"` 212 AuthorityCertSerialNumber big.Int `asn1:"optional,tag:2"` 213 } 214 215 // getAuthorityKeyIdentifierFromCrl returns the Authority Key Identifier 216 // for the supplied CRL. The authority key identifier can be used to identify 217 // the public key corresponding to the private key which was used to sign the CRL. 218 func getAuthorityKeyIdentifierFromCrl(crl *pkix.CertificateList) ([]byte, error) { 219 aki := authorityKeyIdentifier{} 220 221 for _, ext := range crl.TBSCertList.Extensions { 222 // Authority Key Identifier is identified by the following ASN.1 tag 223 // authorityKeyIdentifier (2 5 29 35) (see https://tools.ietf.org/html/rfc3280.html) 224 if reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 35}) { 225 _, err := asn1.Unmarshal(ext.Value, &aki) 226 if err != nil { 227 return nil, fmt.Errorf("Failed to unmarshal AKI, error %s", err) 228 } 229 230 return aki.KeyIdentifier, nil 231 } 232 } 233 234 return nil, errors.New("authorityKeyIdentifier not found in certificate") 235 } 236 237 // getSubjectKeyIdentifierFromCert returns the Subject Key Identifier for the supplied certificate 238 // Subject Key Identifier is an identifier of the public key of this certificate 239 func getSubjectKeyIdentifierFromCert(cert *x509.Certificate) ([]byte, error) { 240 var SKI []byte 241 242 for _, ext := range cert.Extensions { 243 // Subject Key Identifier is identified by the following ASN.1 tag 244 // subjectKeyIdentifier (2 5 29 14) (see https://tools.ietf.org/html/rfc3280.html) 245 if reflect.DeepEqual(ext.Id, asn1.ObjectIdentifier{2, 5, 29, 14}) { 246 _, err := asn1.Unmarshal(ext.Value, &SKI) 247 if err != nil { 248 return nil, fmt.Errorf("Failed to unmarshal Subject Key Identifier, err %s", err) 249 } 250 251 return SKI, nil 252 } 253 } 254 255 return nil, errors.New("subjectKeyIdentifier not found in certificate") 256 } 257 258 // isCACert does a few checks on the certificate, 259 // assuming it's a CA; it returns true if all looks good 260 // and false otherwise 261 func isCACert(cert *x509.Certificate) bool { 262 _, err := getSubjectKeyIdentifierFromCert(cert) 263 if err != nil { 264 return false 265 } 266 267 if !cert.IsCA { 268 return false 269 } 270 271 return true 272 } 273 274 // Setup sets up the internal data structures 275 // for this MSP, given an MSPConfig ref; it 276 // returns nil in case of success or an error otherwise 277 func (msp *bccspmsp) Setup(conf1 *m.MSPConfig) error { 278 if conf1 == nil { 279 return fmt.Errorf("Setup error: nil conf reference") 280 } 281 282 // given that it's an msp of type fabric, extract the MSPConfig instance 283 conf := &m.FabricMSPConfig{} 284 err := proto.Unmarshal(conf1.Config, conf) 285 if err != nil { 286 return fmt.Errorf("Failed unmarshalling fabric msp config, err %s", err) 287 } 288 289 // set the name for this msp 290 msp.name = conf.Name 291 mspLogger.Debugf("Setting up MSP instance %s", msp.name) 292 293 // setup crypto config 294 if err := msp.setupCrypto(conf); err != nil { 295 return err 296 } 297 298 // Setup CAs 299 if err := msp.setupCAs(conf); err != nil { 300 return err 301 } 302 303 // Setup Admins 304 if err := msp.setupAdmins(conf); err != nil { 305 return err 306 } 307 308 // Setup CRLs 309 if err := msp.setupCRLs(conf); err != nil { 310 return err 311 } 312 313 // Finalize setup of the CAs 314 if err := msp.finalizeSetupCAs(conf); err != nil { 315 return err 316 } 317 318 // setup the signer (if present) 319 if err := msp.setupSigningIdentity(conf); err != nil { 320 return err 321 } 322 323 // setup the OUs 324 if err := msp.setupOUs(conf); err != nil { 325 return err 326 } 327 328 // setup TLS CAs 329 if err := msp.setupTLSCAs(conf); err != nil { 330 return err 331 } 332 333 // make sure that admins are valid members as well 334 // this way, when we validate an admin MSP principal 335 // we can simply check for exact match of certs 336 for i, admin := range msp.admins { 337 err = admin.Validate() 338 if err != nil { 339 return fmt.Errorf("admin %d is invalid, validation error %s", i, err) 340 } 341 } 342 343 return nil 344 } 345 346 // GetType returns the type for this MSP 347 func (msp *bccspmsp) GetType() ProviderType { 348 return FABRIC 349 } 350 351 // GetIdentifier returns the MSP identifier for this instance 352 func (msp *bccspmsp) GetIdentifier() (string, error) { 353 return msp.name, nil 354 } 355 356 // GetTLSRootCerts returns the root certificates for this MSP 357 func (msp *bccspmsp) GetTLSRootCerts() [][]byte { 358 return msp.tlsRootCerts 359 } 360 361 // GetTLSIntermediateCerts returns the intermediate root certificates for this MSP 362 func (msp *bccspmsp) GetTLSIntermediateCerts() [][]byte { 363 return msp.tlsIntermediateCerts 364 } 365 366 // GetDefaultSigningIdentity returns the 367 // default signing identity for this MSP (if any) 368 func (msp *bccspmsp) GetDefaultSigningIdentity() (SigningIdentity, error) { 369 mspLogger.Debugf("Obtaining default signing identity") 370 371 if msp.signer == nil { 372 return nil, fmt.Errorf("This MSP does not possess a valid default signing identity") 373 } 374 375 return msp.signer, nil 376 } 377 378 // GetSigningIdentity returns a specific signing 379 // identity identified by the supplied identifier 380 func (msp *bccspmsp) GetSigningIdentity(identifier *IdentityIdentifier) (SigningIdentity, error) { 381 // TODO 382 return nil, fmt.Errorf("No signing identity for %#v", identifier) 383 } 384 385 // Validate attempts to determine whether 386 // the supplied identity is valid according 387 // to this MSP's roots of trust; it returns 388 // nil in case the identity is valid or an 389 // error otherwise 390 func (msp *bccspmsp) Validate(id Identity) error { 391 mspLogger.Debugf("MSP %s validating identity", msp.name) 392 393 switch id := id.(type) { 394 // If this identity is of this specific type, 395 // this is how I can validate it given the 396 // root of trust this MSP has 397 case *identity: 398 return msp.validateIdentity(id) 399 default: 400 return fmt.Errorf("Identity type not recognized") 401 } 402 } 403 404 // DeserializeIdentity returns an Identity given the byte-level 405 // representation of a SerializedIdentity struct 406 func (msp *bccspmsp) DeserializeIdentity(serializedID []byte) (Identity, error) { 407 mspLogger.Infof("Obtaining identity") 408 409 // We first deserialize to a SerializedIdentity to get the MSP ID 410 sId := &m.SerializedIdentity{} 411 err := proto.Unmarshal(serializedID, sId) 412 if err != nil { 413 return nil, fmt.Errorf("Could not deserialize a SerializedIdentity, err %s", err) 414 } 415 416 if sId.Mspid != msp.name { 417 return nil, fmt.Errorf("Expected MSP ID %s, received %s", msp.name, sId.Mspid) 418 } 419 420 return msp.deserializeIdentityInternal(sId.IdBytes) 421 } 422 423 // deserializeIdentityInternal returns an identity given its byte-level representation 424 func (msp *bccspmsp) deserializeIdentityInternal(serializedIdentity []byte) (Identity, error) { 425 // This MSP will always deserialize certs this way 426 bl, _ := pem.Decode(serializedIdentity) 427 if bl == nil { 428 return nil, fmt.Errorf("Could not decode the PEM structure") 429 } 430 cert, err := x509.ParseCertificate(bl.Bytes) 431 if err != nil { 432 return nil, fmt.Errorf("ParseCertificate failed %s", err) 433 } 434 435 // Now we have the certificate; make sure that its fields 436 // (e.g. the Issuer.OU or the Subject.OU) match with the 437 // MSP id that this MSP has; otherwise it might be an attack 438 // TODO! 439 // We can't do it yet because there is no standardized way 440 // (yet) to encode the MSP ID into the x.509 body of a cert 441 442 // Use the hash of the identity's certificate as id in the IdentityIdentifier 443 hashOpt, err := bccsp.GetHashOpt(msp.cryptoConfig.IdentityIdentifierHashFunction) 444 if err != nil { 445 return nil, fmt.Errorf("Failed getting hash function options [%s]", err) 446 } 447 448 digest, err := msp.bccsp.Hash(cert.Raw, hashOpt) 449 if err != nil { 450 return nil, fmt.Errorf("Failed hashing raw certificate to compute the id of the IdentityIdentifier [%s]", err) 451 } 452 453 id := &IdentityIdentifier{ 454 Mspid: msp.name, 455 Id: hex.EncodeToString(digest)} 456 457 pub, err := msp.bccsp.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: true}) 458 if err != nil { 459 return nil, fmt.Errorf("Failed to import certitifacate's public key [%s]", err) 460 } 461 462 return newIdentity(id, cert, pub, msp) 463 } 464 465 // SatisfiesPrincipal returns null if the identity matches the principal or an error otherwise 466 func (msp *bccspmsp) SatisfiesPrincipal(id Identity, principal *m.MSPPrincipal) error { 467 switch principal.PrincipalClassification { 468 // in this case, we have to check whether the 469 // identity has a role in the msp - member or admin 470 case m.MSPPrincipal_ROLE: 471 // Principal contains the msp role 472 mspRole := &m.MSPRole{} 473 err := proto.Unmarshal(principal.Principal, mspRole) 474 if err != nil { 475 return fmt.Errorf("Could not unmarshal MSPRole from principal, err %s", err) 476 } 477 478 // at first, we check whether the MSP 479 // identifier is the same as that of the identity 480 if mspRole.MspIdentifier != msp.name { 481 return fmt.Errorf("The identity is a member of a different MSP (expected %s, got %s)", mspRole.MspIdentifier, id.GetMSPIdentifier()) 482 } 483 484 // now we validate the different msp roles 485 switch mspRole.Role { 486 case m.MSPRole_MEMBER: 487 // in the case of member, we simply check 488 // whether this identity is valid for the MSP 489 mspLogger.Debugf("Checking if identity satisfies MEMBER role for %s", msp.name) 490 return msp.Validate(id) 491 case m.MSPRole_ADMIN: 492 mspLogger.Debugf("Checking if identity satisfies ADMIN role for %s", msp.name) 493 // in the case of admin, we check that the 494 // id is exactly one of our admins 495 for _, admincert := range msp.admins { 496 if bytes.Equal(id.(*identity).cert.Raw, admincert.(*identity).cert.Raw) { 497 // we do not need to check whether the admin is a valid identity 498 // according to this MSP, since we already check this at Setup time 499 // if there is a match, we can just return 500 return nil 501 } 502 } 503 504 return errors.New("This identity is not an admin") 505 default: 506 return fmt.Errorf("Invalid MSP role type %d", int32(mspRole.Role)) 507 } 508 case m.MSPPrincipal_IDENTITY: 509 // in this case we have to deserialize the principal's identity 510 // and compare it byte-by-byte with our cert 511 principalId, err := msp.DeserializeIdentity(principal.Principal) 512 if err != nil { 513 return fmt.Errorf("Invalid identity principal, not a certificate. Error %s", err) 514 } 515 516 if bytes.Equal(id.(*identity).cert.Raw, principalId.(*identity).cert.Raw) { 517 return principalId.Validate() 518 } 519 520 return errors.New("The identities do not match") 521 case m.MSPPrincipal_ORGANIZATION_UNIT: 522 // Principal contains the OrganizationUnit 523 OU := &m.OrganizationUnit{} 524 err := proto.Unmarshal(principal.Principal, OU) 525 if err != nil { 526 return fmt.Errorf("Could not unmarshal OrganizationUnit from principal, err %s", err) 527 } 528 529 // at first, we check whether the MSP 530 // identifier is the same as that of the identity 531 if OU.MspIdentifier != msp.name { 532 return fmt.Errorf("The identity is a member of a different MSP (expected %s, got %s)", OU.MspIdentifier, id.GetMSPIdentifier()) 533 } 534 535 // we then check if the identity is valid with this MSP 536 // and fail if it is not 537 err = msp.Validate(id) 538 if err != nil { 539 return err 540 } 541 542 // now we check whether any of this identity's OUs match the requested one 543 for _, ou := range id.GetOrganizationalUnits() { 544 if ou.OrganizationalUnitIdentifier == OU.OrganizationalUnitIdentifier && 545 bytes.Equal(ou.CertifiersIdentifier, OU.CertifiersIdentifier) { 546 return nil 547 } 548 } 549 550 // if we are here, no match was found, return an error 551 return errors.New("The identities do not match") 552 default: 553 return fmt.Errorf("Invalid principal type %d", int32(principal.PrincipalClassification)) 554 } 555 } 556 557 // getCertificationChain returns the certification chain of the passed identity within this msp 558 func (msp *bccspmsp) getCertificationChain(id Identity) ([]*x509.Certificate, error) { 559 mspLogger.Debugf("MSP %s getting certification chain", msp.name) 560 561 switch id := id.(type) { 562 // If this identity is of this specific type, 563 // this is how I can validate it given the 564 // root of trust this MSP has 565 case *identity: 566 return msp.getCertificationChainForBCCSPIdentity(id) 567 default: 568 return nil, fmt.Errorf("Identity type not recognized") 569 } 570 } 571 572 // getCertificationChainForBCCSPIdentity returns the certification chain of the passed bccsp identity within this msp 573 func (msp *bccspmsp) getCertificationChainForBCCSPIdentity(id *identity) ([]*x509.Certificate, error) { 574 if id == nil { 575 return nil, errors.New("Invalid bccsp identity. Must be different from nil.") 576 } 577 578 // we expect to have a valid VerifyOptions instance 579 if msp.opts == nil { 580 return nil, errors.New("Invalid msp instance") 581 } 582 583 // CAs cannot be directly used as identities.. 584 if id.cert.IsCA { 585 return nil, errors.New("A CA certificate cannot be used directly by this MSP") 586 } 587 588 return msp.getValidationChain(id.cert, false) 589 } 590 591 func (msp *bccspmsp) getUniqueValidationChain(cert *x509.Certificate, opts x509.VerifyOptions) ([]*x509.Certificate, error) { 592 // ask golang to validate the cert for us based on the options that we've built at setup time 593 if msp.opts == nil { 594 return nil, fmt.Errorf("The supplied identity has no verify options") 595 } 596 validationChains, err := cert.Verify(opts) 597 if err != nil { 598 return nil, fmt.Errorf("The supplied identity is not valid, Verify() returned %s", err) 599 } 600 601 // we only support a single validation chain; 602 // if there's more than one then there might 603 // be unclarity about who owns the identity 604 if len(validationChains) != 1 { 605 return nil, fmt.Errorf("This MSP only supports a single validation chain, got %d", len(validationChains)) 606 } 607 608 return validationChains[0], nil 609 } 610 611 func (msp *bccspmsp) getValidationChain(cert *x509.Certificate, isIntermediateChain bool) ([]*x509.Certificate, error) { 612 validationChain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) 613 if err != nil { 614 return nil, fmt.Errorf("Failed getting validation chain %s", err) 615 } 616 617 // we expect a chain of length at least 2 618 if len(validationChain) < 2 { 619 return nil, fmt.Errorf("Expected a chain of length at least 2, got %d", len(validationChain)) 620 } 621 622 // check that the parent is a leaf of the certification tree 623 // if validating an intermediate chain, the first certificate will the parent 624 parentPosition := 1 625 if isIntermediateChain { 626 parentPosition = 0 627 } 628 if msp.certificationTreeInternalNodesMap[string(validationChain[parentPosition].Raw)] { 629 return nil, fmt.Errorf("Invalid validation chain. Parent certificate should be a leaf of the certification tree [%v].", cert.Raw) 630 } 631 return validationChain, nil 632 } 633 634 // getCertificationChainIdentifier returns the certification chain identifier of the passed identity within this msp. 635 // The identifier is computes as the SHA256 of the concatenation of the certificates in the chain. 636 func (msp *bccspmsp) getCertificationChainIdentifier(id Identity) ([]byte, error) { 637 chain, err := msp.getCertificationChain(id) 638 if err != nil { 639 return nil, fmt.Errorf("Failed getting certification chain for [%v]: [%s]", id, err) 640 } 641 642 // chain[0] is the certificate representing the identity. 643 // It will be discarded 644 return msp.getCertificationChainIdentifierFromChain(chain[1:]) 645 } 646 647 func (msp *bccspmsp) getCertificationChainIdentifierFromChain(chain []*x509.Certificate) ([]byte, error) { 648 // Hash the chain 649 // Use the hash of the identity's certificate as id in the IdentityIdentifier 650 hashOpt, err := bccsp.GetHashOpt(msp.cryptoConfig.IdentityIdentifierHashFunction) 651 if err != nil { 652 return nil, fmt.Errorf("Failed getting hash function options [%s]", err) 653 } 654 655 hf, err := msp.bccsp.GetHash(hashOpt) 656 if err != nil { 657 return nil, fmt.Errorf("Failed getting hash function when computing certification chain identifier: [%s]", err) 658 } 659 for i := 0; i < len(chain); i++ { 660 hf.Write(chain[i].Raw) 661 } 662 return hf.Sum(nil), nil 663 } 664 665 func (msp *bccspmsp) setupCrypto(conf *m.FabricMSPConfig) error { 666 msp.cryptoConfig = conf.CryptoConfig 667 if msp.cryptoConfig == nil { 668 // Move to defaults 669 msp.cryptoConfig = &m.FabricCryptoConfig{ 670 SignatureHashFamily: bccsp.SHA2, 671 IdentityIdentifierHashFunction: bccsp.SHA256, 672 } 673 mspLogger.Debugf("CryptoConfig was nil. Move to defaults.") 674 } 675 if msp.cryptoConfig.SignatureHashFamily == "" { 676 msp.cryptoConfig.SignatureHashFamily = bccsp.SHA2 677 mspLogger.Debugf("CryptoConfig.SignatureHashFamily was nil. Move to defaults.") 678 } 679 if msp.cryptoConfig.IdentityIdentifierHashFunction == "" { 680 msp.cryptoConfig.IdentityIdentifierHashFunction = bccsp.SHA256 681 mspLogger.Debugf("CryptoConfig.IdentityIdentifierHashFunction was nil. Move to defaults.") 682 } 683 684 return nil 685 } 686 687 func (msp *bccspmsp) setupCAs(conf *m.FabricMSPConfig) error { 688 // make and fill the set of CA certs - we expect them to be there 689 if len(conf.RootCerts) == 0 { 690 return errors.New("Expected at least one CA certificate") 691 } 692 693 // pre-create the verify options with roots and intermediates. 694 // This is needed to make certificate sanitation working. 695 // Recall that sanitization is applied also to root CA and intermediate 696 // CA certificates. After their sanitization is done, the opts 697 // will be recreated using the sanitized certs. 698 msp.opts = &x509.VerifyOptions{Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool()} 699 for _, v := range conf.RootCerts { 700 cert, err := msp.getCertFromPem(v) 701 if err != nil { 702 return err 703 } 704 msp.opts.Roots.AddCert(cert) 705 } 706 for _, v := range conf.IntermediateCerts { 707 cert, err := msp.getCertFromPem(v) 708 if err != nil { 709 return err 710 } 711 msp.opts.Intermediates.AddCert(cert) 712 } 713 714 // Load root and intermediate CA identities 715 // Recall that when an identity is created, its certificate gets sanitized 716 msp.rootCerts = make([]Identity, len(conf.RootCerts)) 717 for i, trustedCert := range conf.RootCerts { 718 id, _, err := msp.getIdentityFromConf(trustedCert) 719 if err != nil { 720 return err 721 } 722 723 msp.rootCerts[i] = id 724 } 725 726 // make and fill the set of intermediate certs (if present) 727 msp.intermediateCerts = make([]Identity, len(conf.IntermediateCerts)) 728 for i, trustedCert := range conf.IntermediateCerts { 729 id, _, err := msp.getIdentityFromConf(trustedCert) 730 if err != nil { 731 return err 732 } 733 734 msp.intermediateCerts[i] = id 735 } 736 737 // root CA and intermediate CA certificates are sanitized, they can be reimported 738 msp.opts = &x509.VerifyOptions{Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool()} 739 for _, id := range msp.rootCerts { 740 msp.opts.Roots.AddCert(id.(*identity).cert) 741 } 742 for _, id := range msp.intermediateCerts { 743 msp.opts.Intermediates.AddCert(id.(*identity).cert) 744 } 745 746 // make and fill the set of admin certs (if present) 747 msp.admins = make([]Identity, len(conf.Admins)) 748 for i, admCert := range conf.Admins { 749 id, _, err := msp.getIdentityFromConf(admCert) 750 if err != nil { 751 return err 752 } 753 754 msp.admins[i] = id 755 } 756 757 return nil 758 } 759 760 func (msp *bccspmsp) setupAdmins(conf *m.FabricMSPConfig) error { 761 // make and fill the set of admin certs (if present) 762 msp.admins = make([]Identity, len(conf.Admins)) 763 for i, admCert := range conf.Admins { 764 id, _, err := msp.getIdentityFromConf(admCert) 765 if err != nil { 766 return err 767 } 768 769 msp.admins[i] = id 770 } 771 772 return nil 773 } 774 775 func (msp *bccspmsp) setupCRLs(conf *m.FabricMSPConfig) error { 776 // setup the CRL (if present) 777 msp.CRL = make([]*pkix.CertificateList, len(conf.RevocationList)) 778 for i, crlbytes := range conf.RevocationList { 779 crl, err := x509.ParseCRL(crlbytes) 780 if err != nil { 781 return fmt.Errorf("Could not parse RevocationList, err %s", err) 782 } 783 784 // TODO: pre-verify the signature on the CRL and create a map 785 // of CA certs to respective CRLs so that later upon 786 // validation we can already look up the CRL given the 787 // chain of the certificate to be validated 788 789 msp.CRL[i] = crl 790 } 791 792 return nil 793 } 794 795 func (msp *bccspmsp) finalizeSetupCAs(config *m.FabricMSPConfig) error { 796 // ensure that our CAs are properly formed and that they are valid 797 for _, id := range append(append([]Identity{}, msp.rootCerts...), msp.intermediateCerts...) { 798 if !isCACert(id.(*identity).cert) { 799 return fmt.Errorf("CA Certificate did not have the Subject Key Identifier extension, (SN: %s)", id.(*identity).cert.SerialNumber) 800 } 801 802 if err := msp.validateCAIdentity(id.(*identity)); err != nil { 803 return fmt.Errorf("CA Certificate is not valid, (SN: %s) [%s]", id.(*identity).cert.SerialNumber, err) 804 } 805 } 806 807 // populate certificationTreeInternalNodesMap to mark the internal nodes of the 808 // certification tree 809 msp.certificationTreeInternalNodesMap = make(map[string]bool) 810 for _, id := range append([]Identity{}, msp.intermediateCerts...) { 811 chain, err := msp.getUniqueValidationChain(id.(*identity).cert, msp.getValidityOptsForCert(id.(*identity).cert)) 812 if err != nil { 813 return fmt.Errorf("Failed getting validation chain, (SN: %s)", id.(*identity).cert.SerialNumber) 814 } 815 816 // Recall chain[0] is id.(*identity).id so it does not count as a parent 817 for i := 1; i < len(chain); i++ { 818 msp.certificationTreeInternalNodesMap[string(chain[i].Raw)] = true 819 } 820 } 821 822 return nil 823 } 824 825 func (msp *bccspmsp) setupSigningIdentity(conf *m.FabricMSPConfig) error { 826 if conf.SigningIdentity != nil { 827 sid, err := msp.getSigningIdentityFromConf(conf.SigningIdentity) 828 if err != nil { 829 return err 830 } 831 832 msp.signer = sid 833 } 834 835 return nil 836 } 837 838 func (msp *bccspmsp) setupOUs(conf *m.FabricMSPConfig) error { 839 msp.ouIdentifiers = make(map[string][][]byte) 840 for _, ou := range conf.OrganizationalUnitIdentifiers { 841 842 // 1. check that certificate is registered in msp.rootCerts or msp.intermediateCerts 843 cert, err := msp.getCertFromPem(ou.Certificate) 844 if err != nil { 845 return fmt.Errorf("Failed getting certificate for [%v]: [%s]", ou, err) 846 } 847 848 // 2. Sanitize it to ensure like for like comparison 849 cert, err = msp.sanitizeCert(cert) 850 if err != nil { 851 return fmt.Errorf("sanitizeCert failed %s", err) 852 } 853 854 found := false 855 root := false 856 // Search among root certificates 857 for _, v := range msp.rootCerts { 858 if v.(*identity).cert.Equal(cert) { 859 found = true 860 root = true 861 break 862 } 863 } 864 if !found { 865 // Search among root intermediate certificates 866 for _, v := range msp.intermediateCerts { 867 if v.(*identity).cert.Equal(cert) { 868 found = true 869 break 870 } 871 } 872 } 873 if !found { 874 // Certificate not valid, reject configuration 875 return fmt.Errorf("Failed adding OU. Certificate [%v] not in root or intermediate certs.", ou.Certificate) 876 } 877 878 // 3. get the certification path for it 879 var certifiersIdentitifer []byte 880 var chain []*x509.Certificate 881 if root { 882 chain = []*x509.Certificate{cert} 883 } else { 884 chain, err = msp.getValidationChain(cert, true) 885 if err != nil { 886 return fmt.Errorf("Failed computing validation chain for [%v]. [%s]", cert, err) 887 } 888 } 889 890 // 4. compute the hash of the certification path 891 certifiersIdentitifer, err = msp.getCertificationChainIdentifierFromChain(chain) 892 if err != nil { 893 return fmt.Errorf("Failed computing Certifiers Identifier for [%v]. [%s]", ou.Certificate, err) 894 } 895 896 // Check for duplicates 897 found = false 898 for _, id := range msp.ouIdentifiers[ou.OrganizationalUnitIdentifier] { 899 if bytes.Equal(id, certifiersIdentitifer) { 900 mspLogger.Warningf("Duplicate found in ou identifiers [%s, %v]", ou.OrganizationalUnitIdentifier, id) 901 found = true 902 break 903 } 904 } 905 906 if !found { 907 // No duplicates found, add it 908 msp.ouIdentifiers[ou.OrganizationalUnitIdentifier] = append( 909 msp.ouIdentifiers[ou.OrganizationalUnitIdentifier], 910 certifiersIdentitifer, 911 ) 912 } 913 } 914 915 return nil 916 } 917 918 func (msp *bccspmsp) setupTLSCAs(conf *m.FabricMSPConfig) error { 919 920 opts := &x509.VerifyOptions{Roots: x509.NewCertPool(), Intermediates: x509.NewCertPool()} 921 922 // Load TLS root and intermediate CA identities 923 msp.tlsRootCerts = make([][]byte, len(conf.TlsRootCerts)) 924 rootCerts := make([]*x509.Certificate, len(conf.TlsRootCerts)) 925 for i, trustedCert := range conf.TlsRootCerts { 926 cert, err := msp.getCertFromPem(trustedCert) 927 if err != nil { 928 return err 929 } 930 931 rootCerts[i] = cert 932 msp.tlsRootCerts[i] = trustedCert 933 opts.Roots.AddCert(cert) 934 } 935 936 // make and fill the set of intermediate certs (if present) 937 msp.tlsIntermediateCerts = make([][]byte, len(conf.TlsIntermediateCerts)) 938 intermediateCerts := make([]*x509.Certificate, len(conf.TlsIntermediateCerts)) 939 for i, trustedCert := range conf.TlsIntermediateCerts { 940 cert, err := msp.getCertFromPem(trustedCert) 941 if err != nil { 942 return err 943 } 944 945 intermediateCerts[i] = cert 946 msp.tlsIntermediateCerts[i] = trustedCert 947 opts.Intermediates.AddCert(cert) 948 } 949 950 // ensure that our CAs are properly formed and that they are valid 951 for _, cert := range append(append([]*x509.Certificate{}, rootCerts...), intermediateCerts...) { 952 if cert == nil { 953 continue 954 } 955 956 if !isCACert(cert) { 957 return fmt.Errorf("CA Certificate did not have the Subject Key Identifier extension, (SN: %s)", cert.SerialNumber) 958 } 959 960 if err := msp.validateTLSCAIdentity(cert, opts); err != nil { 961 return fmt.Errorf("CA Certificate is not valid, (SN: %s) [%s]", cert.SerialNumber, err) 962 } 963 } 964 965 return nil 966 } 967 968 // sanitizeCert ensures that x509 certificates signed using ECDSA 969 // do have signatures in Low-S. If this is not the case, the certificate 970 // is regenerated to have a Low-S signature. 971 func (msp *bccspmsp) sanitizeCert(cert *x509.Certificate) (*x509.Certificate, error) { 972 if isECDSASignedCert(cert) { 973 // Lookup for a parent certificate to perform the sanitization 974 var parentCert *x509.Certificate 975 if cert.IsCA { 976 // at this point, cert might be a root CA certificate 977 // or an intermediate CA certificate 978 chain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) 979 if err != nil { 980 return nil, err 981 } 982 if len(chain) == 1 { 983 // cert is a root CA certificate 984 parentCert = cert 985 } else { 986 // cert is an intermediate CA certificate 987 parentCert = chain[1] 988 } 989 } else { 990 chain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) 991 if err != nil { 992 return nil, err 993 } 994 parentCert = chain[1] 995 } 996 997 // Sanitize 998 var err error 999 cert, err = sanitizeECDSASignedCert(cert, parentCert) 1000 if err != nil { 1001 return nil, err 1002 } 1003 } 1004 return cert, nil 1005 } 1006 1007 func (msp *bccspmsp) validateIdentity(id *identity) error { 1008 validationChain, err := msp.getCertificationChainForBCCSPIdentity(id) 1009 if err != nil { 1010 return fmt.Errorf("Could not obtain certification chain, err %s", err) 1011 } 1012 1013 err = msp.validateIdentityAgainstChain(id, validationChain) 1014 if err != nil { 1015 return fmt.Errorf("Could not validate identity against certification chain, err %s", err) 1016 } 1017 1018 err = msp.validateIdentityOUs(id) 1019 if err != nil { 1020 return fmt.Errorf("Could not validate identity's OUs, err %s", err) 1021 } 1022 1023 return nil 1024 } 1025 1026 func (msp *bccspmsp) validateCAIdentity(id *identity) error { 1027 if !id.cert.IsCA { 1028 return errors.New("Only CA identities can be validated") 1029 } 1030 1031 validationChain, err := msp.getUniqueValidationChain(id.cert, msp.getValidityOptsForCert(id.cert)) 1032 if err != nil { 1033 return fmt.Errorf("Could not obtain certification chain, err %s", err) 1034 } 1035 if len(validationChain) == 1 { 1036 // validationChain[0] is the root CA certificate 1037 return nil 1038 } 1039 1040 return msp.validateIdentityAgainstChain(id, validationChain) 1041 } 1042 1043 func (msp *bccspmsp) validateTLSCAIdentity(cert *x509.Certificate, opts *x509.VerifyOptions) error { 1044 if !cert.IsCA { 1045 return errors.New("Only CA identities can be validated") 1046 } 1047 1048 validationChain, err := msp.getUniqueValidationChain(cert, *opts) 1049 if err != nil { 1050 return fmt.Errorf("Could not obtain certification chain, err %s", err) 1051 } 1052 if len(validationChain) == 1 { 1053 // validationChain[0] is the root CA certificate 1054 return nil 1055 } 1056 1057 return msp.validateCertAgainstChain(cert, validationChain) 1058 } 1059 1060 func (msp *bccspmsp) validateIdentityAgainstChain(id *identity, validationChain []*x509.Certificate) error { 1061 return msp.validateCertAgainstChain(id.cert, validationChain) 1062 } 1063 1064 func (msp *bccspmsp) validateCertAgainstChain(cert *x509.Certificate, validationChain []*x509.Certificate) error { 1065 // here we know that the identity is valid; now we have to check whether it has been revoked 1066 1067 // identify the SKI of the CA that signed this cert 1068 SKI, err := getSubjectKeyIdentifierFromCert(validationChain[1]) 1069 if err != nil { 1070 return fmt.Errorf("Could not obtain Subject Key Identifier for signer cert, err %s", err) 1071 } 1072 1073 // check whether one of the CRLs we have has this cert's 1074 // SKI as its AuthorityKeyIdentifier 1075 for _, crl := range msp.CRL { 1076 aki, err := getAuthorityKeyIdentifierFromCrl(crl) 1077 if err != nil { 1078 return fmt.Errorf("Could not obtain Authority Key Identifier for crl, err %s", err) 1079 } 1080 1081 // check if the SKI of the cert that signed us matches the AKI of any of the CRLs 1082 if bytes.Equal(aki, SKI) { 1083 // we have a CRL, check whether the serial number is revoked 1084 for _, rc := range crl.TBSCertList.RevokedCertificates { 1085 if rc.SerialNumber.Cmp(cert.SerialNumber) == 0 { 1086 // We have found a CRL whose AKI matches the SKI of 1087 // the CA (root or intermediate) that signed the 1088 // certificate that is under validation. As a 1089 // precaution, we verify that said CA is also the 1090 // signer of this CRL. 1091 err = validationChain[1].CheckCRLSignature(crl) 1092 if err != nil { 1093 // the CA cert that signed the certificate 1094 // that is under validation did not sign the 1095 // candidate CRL - skip 1096 mspLogger.Warningf("Invalid signature over the identified CRL, error %s", err) 1097 continue 1098 } 1099 1100 // A CRL also includes a time of revocation so that 1101 // the CA can say "this cert is to be revoked starting 1102 // from this time"; however here we just assume that 1103 // revocation applies instantaneously from the time 1104 // the MSP config is committed and used so we will not 1105 // make use of that field 1106 return errors.New("The certificate has been revoked") 1107 } 1108 } 1109 } 1110 } 1111 1112 return nil 1113 } 1114 1115 func (msp *bccspmsp) validateIdentityOUs(id *identity) error { 1116 // Check that the identity's OUs are compatible with those recognized by this MSP, 1117 // meaning that the intersection is not empty. 1118 if len(msp.ouIdentifiers) > 0 { 1119 found := false 1120 1121 for _, OU := range id.GetOrganizationalUnits() { 1122 certificationIDs, exists := msp.ouIdentifiers[OU.OrganizationalUnitIdentifier] 1123 1124 if exists { 1125 for _, certificationID := range certificationIDs { 1126 if bytes.Equal(certificationID, OU.CertifiersIdentifier) { 1127 found = true 1128 break 1129 } 1130 } 1131 } 1132 } 1133 1134 if !found { 1135 if len(id.GetOrganizationalUnits()) == 0 { 1136 return fmt.Errorf("The identity certificate does not contain an Organizational Unit (OU)") 1137 } 1138 return fmt.Errorf("None of the identity's organizational units [%v] are in MSP %s", id.GetOrganizationalUnits(), msp.name) 1139 } 1140 } 1141 1142 return nil 1143 } 1144 1145 func (msp *bccspmsp) getValidityOptsForCert(cert *x509.Certificate) x509.VerifyOptions { 1146 // First copy the opts to override the CurrentTime field 1147 // in order to make the certificate passing the expiration test 1148 // independently from the real local current time. 1149 // This is a temporary workaround for FAB-3678 1150 1151 var tempOpts x509.VerifyOptions 1152 tempOpts.Roots = msp.opts.Roots 1153 tempOpts.DNSName = msp.opts.DNSName 1154 tempOpts.Intermediates = msp.opts.Intermediates 1155 tempOpts.KeyUsages = msp.opts.KeyUsages 1156 tempOpts.CurrentTime = cert.NotBefore.Add(time.Second) 1157 1158 return tempOpts 1159 } 1160 1161 func (msp *bccspmsp) getValidityOptsForTLSCert(cert *x509.Certificate) x509.VerifyOptions { 1162 // First copy the opts to override the CurrentTime field 1163 // in order to make the certificate passing the expiration test 1164 // independently from the real local current time. 1165 // This is a temporary workaround for FAB-3678 1166 1167 var tempOpts x509.VerifyOptions 1168 tempOpts.Roots = msp.opts.Roots 1169 tempOpts.Intermediates = msp.opts.Intermediates 1170 1171 return tempOpts 1172 }