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