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