forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsp_test.go
1617 lines (1317 loc) · 47.7 KB
/
msp_test.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. 2017 All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package msp
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"math/big"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/hyperledger/fabric-lib-go/bccsp"
"github.com/hyperledger/fabric-lib-go/bccsp/factory"
"github.com/hyperledger/fabric-lib-go/bccsp/sw"
"github.com/hyperledger/fabric-lib-go/bccsp/utils"
"github.com/hyperledger/fabric-protos-go-apiv2/msp"
"github.com/hyperledger/fabric/core/config/configtest"
"github.com/hyperledger/fabric/protoutil"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
var notACert = `-----BEGIN X509 CRL-----
MIIBYzCCAQgCAQEwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMCVVMxEzARBgNVBAgT
CkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xHzAdBgNVBAoTFklu
dGVybmV0IFdpZGdldHMsIEluYy4xDDAKBgNVBAsTA1dXVzEUMBIGA1UEAxMLZXhh
bXBsZS5jb20XDTE3MDEyMzIwNTYyMFoXDTE3MDEyNjIwNTYyMFowJzAlAhQERXCx
LHROap1vM3CV40EHOghPTBcNMTcwMTIzMjA0NzMxWqAvMC0wHwYDVR0jBBgwFoAU
F2dCPaqegj/ExR2fW8OZ0bWcSBAwCgYDVR0UBAMCAQgwCgYIKoZIzj0EAwIDSQAw
RgIhAOTTpQYkGO+gwVe1LQOcNMD5fzFViOwBUraMrk6dRMlmAiEA8z2dpXKGwHrj
FRBbKkDnSpaVcZgjns+mLdHV2JkF0gk=
-----END X509 CRL-----`
func TestMSPParsers(t *testing.T) {
_, _, err := localMsp.(*bccspmsp).getIdentityFromConf(nil)
require.Error(t, err)
_, _, err = localMsp.(*bccspmsp).getIdentityFromConf([]byte("barf"))
require.Error(t, err)
_, _, err = localMsp.(*bccspmsp).getIdentityFromConf([]byte(notACert))
require.Error(t, err)
_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(nil)
require.Error(t, err)
sigid := &msp.SigningIdentityInfo{PublicSigner: []byte("barf"), PrivateSigner: nil}
_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(sigid)
require.Error(t, err)
keyinfo := &msp.KeyInfo{KeyIdentifier: "PEER", KeyMaterial: nil}
sigid = &msp.SigningIdentityInfo{PublicSigner: []byte("barf"), PrivateSigner: keyinfo}
_, err = localMsp.(*bccspmsp).getSigningIdentityFromConf(sigid)
require.Error(t, err)
}
func TestGetSigningIdentityFromConfWithWrongPrivateCert(t *testing.T) {
// Temporary Replace root certs
oldRoots := localMsp.(*bccspmsp).opts.Roots
defer func() {
// Restore original root certs
localMsp.(*bccspmsp).opts.Roots = oldRoots
}()
_, cert := generateSelfSignedCert(t, time.Now())
localMsp.(*bccspmsp).opts.Roots = x509.NewCertPool()
localMsp.(*bccspmsp).opts.Roots.AddCert(cert)
// Use self signed cert as public key. Convert DER to PEM format
pem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
// Use wrong formatted private cert
keyinfo := &msp.KeyInfo{
KeyMaterial: []byte("wrong encoding"),
KeyIdentifier: "MyPrivateKey",
}
sigid := &msp.SigningIdentityInfo{PublicSigner: pem, PrivateSigner: keyinfo}
_, err := localMsp.(*bccspmsp).getSigningIdentityFromConf(sigid)
require.EqualError(t, err, "MyPrivateKey: wrong PEM encoding")
}
func TestMSPSetupNoCryptoConf(t *testing.T) {
mspDir := configtest.GetDevMspDir()
conf, err := GetLocalMspConfig(mspDir, nil, "SampleOrg")
if err != nil {
fmt.Printf("Setup should have succeeded, got err %s instead", err)
os.Exit(-1)
}
mspconf := &msp.FabricMSPConfig{}
err = proto.Unmarshal(conf.Config, mspconf)
require.NoError(t, err)
// here we test the case of an MSP configuration
// where the hash function to be used to obtain
// the identity identifier is unspecified - a
// sane default should be picked
mspconf.CryptoConfig.IdentityIdentifierHashFunction = ""
b, err := proto.Marshal(mspconf)
require.NoError(t, err)
conf.Config = b
newmsp, err := newBccspMsp(MSPv1_0, factory.GetDefault())
require.NoError(t, err)
err = newmsp.Setup(conf)
require.NoError(t, err)
// here we test the case of an MSP configuration
// where the hash function to be used to compute
// signatures is unspecified - a sane default
// should be picked
mspconf.CryptoConfig.SignatureHashFamily = ""
b, err = proto.Marshal(mspconf)
require.NoError(t, err)
conf.Config = b
newmsp, err = newBccspMsp(MSPv1_0, factory.GetDefault())
require.NoError(t, err)
err = newmsp.Setup(conf)
require.NoError(t, err)
// here we test the case of an MSP configuration
// that has NO crypto configuration specified;
// the code will use appropriate defaults
mspconf.CryptoConfig = nil
b, err = proto.Marshal(mspconf)
require.NoError(t, err)
conf.Config = b
newmsp, err = newBccspMsp(MSPv1_0, factory.GetDefault())
require.NoError(t, err)
err = newmsp.Setup(conf)
require.NoError(t, err)
}
func TestGetters(t *testing.T) {
typ := localMsp.GetType()
require.Equal(t, typ, FABRIC)
require.NotNil(t, localMsp.GetTLSRootCerts())
require.NotNil(t, localMsp.GetTLSIntermediateCerts())
}
func TestMSPSetupBad(t *testing.T) {
_, err := GetLocalMspConfig("barf", nil, "SampleOrg")
if err == nil {
t.Fatalf("Setup should have failed on an invalid config file")
return
}
mgr := NewMSPManager()
err = mgr.Setup(nil)
require.NoError(t, err)
err = mgr.Setup([]MSP{})
require.NoError(t, err)
}
func TestDoubleSetup(t *testing.T) {
// note that we've already called setup once on this
err := mspMgr.Setup(nil)
require.NoError(t, err)
}
type bccspNoKeyLookupKS struct {
bccsp.BCCSP
}
func (*bccspNoKeyLookupKS) GetKey(ski []byte) (k bccsp.Key, err error) {
return nil, errors.New("not found")
}
func TestNotFoundInBCCSP(t *testing.T) {
cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())
require.NoError(t, err)
dir := configtest.GetDevMspDir()
conf, err := GetLocalMspConfig(dir, nil, "SampleOrg")
require.NoError(t, err)
thisMSP, err := newBccspMsp(MSPv1_0, cryptoProvider)
require.NoError(t, err)
ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join(dir, "keystore"), true)
require.NoError(t, err)
csp, err := sw.NewWithParams(256, "SHA2", ks)
require.NoError(t, err)
thisMSP.(*bccspmsp).bccsp = &bccspNoKeyLookupKS{csp}
err = thisMSP.Setup(conf)
require.Error(t, err)
require.Contains(t, "KeyMaterial not found in SigningIdentityInfo", err.Error())
}
func TestGetIdentities(t *testing.T) {
_, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity failed with err %s", err)
return
}
}
func TestDeserializeIdentityFails(t *testing.T) {
_, err := localMsp.DeserializeIdentity([]byte("barf"))
require.Error(t, err)
id := &msp.SerializedIdentity{Mspid: "SampleOrg", IdBytes: []byte("barfr")}
b, err := proto.Marshal(id)
require.NoError(t, err)
_, err = localMsp.DeserializeIdentity(b)
require.Error(t, err)
id = &msp.SerializedIdentity{Mspid: "SampleOrg", IdBytes: []byte(notACert)}
b, err = proto.Marshal(id)
require.NoError(t, err)
_, err = localMsp.DeserializeIdentity(b)
require.Error(t, err)
}
func TestGetSigningIdentityFromVerifyingMSP(t *testing.T) {
cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())
require.NoError(t, err)
mspDir := configtest.GetDevMspDir()
conf, err = GetVerifyingMspConfig(mspDir, "SampleOrg", ProviderTypeToString(FABRIC))
if err != nil {
fmt.Printf("Setup should have succeeded, got err %s instead", err)
os.Exit(-1)
}
newmsp, err := newBccspMsp(MSPv1_0, cryptoProvider)
require.NoError(t, err)
err = newmsp.Setup(conf)
require.NoError(t, err)
_, err = newmsp.GetDefaultSigningIdentity()
require.Error(t, err)
}
func TestValidateDefaultSigningIdentity(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
err = localMsp.Validate(id.GetPublicVersion())
require.NoError(t, err)
}
func TestSerializeIdentities(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded, got err %s", err)
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded, got err %s", err)
return
}
idBack, err := localMsp.DeserializeIdentity(serializedID)
if err != nil {
t.Fatalf("DeserializeIdentity should have succeeded, got err %s", err)
return
}
err = localMsp.Validate(idBack)
if err != nil {
t.Fatalf("The identity should be valid, got err %s", err)
return
}
if !reflect.DeepEqual(id.GetPublicVersion(), idBack) {
t.Fatalf("Identities should be equal (%s) (%s)", id, idBack)
return
}
}
func computeSKI(key *ecdsa.PublicKey) ([]byte, error) {
ecdhPk, err := key.ECDH()
if err != nil {
return nil, fmt.Errorf("public key transition failed: %w", err)
}
hash := sha256.Sum256(ecdhPk.Bytes())
return hash[:], nil
}
func TestValidHostname(t *testing.T) {
tests := []struct {
name string
valid bool
}{
{"", false},
{".", false},
{"example.com", true},
{"example.com.", true},
{"*.example.com", true},
{".example.com", false},
{"host.*.example.com", false},
{"localhost", true},
{"-localhost", false},
{"Not_Quite.example.com", true},
{"weird:colon.example.com", true},
{"1-2-3.example.com", true},
}
for _, tt := range tests {
if tt.valid {
require.True(t, validHostname(tt.name), "expected %s to be a valid hostname", tt.name)
} else {
require.False(t, validHostname(tt.name), "expected %s to be an invalid hostname", tt.name)
}
}
}
func TestValidateCANameConstraintsMitigation(t *testing.T) {
// Prior to Go 1.15, if a signing certificate contains a name constraint, the
// leaf certificate does not include a SAN, and the leaf common name looks
// like a valid hostname, the certificate chain would fail to validate.
// (This behavior may have been introduced with Go 1.10.)
//
// In Go 1.15, the behavior has changed and, by default, the same structure
// will validate. This test asserts on the old behavior.
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
caSki, err := computeSKI(caKey.Public().(*ecdsa.PublicKey))
require.NoError(t, err)
caKeyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign | x509.KeyUsageCRLSign
caTemplate := x509.Certificate{
Subject: pkix.Name{CommonName: "TestCA"},
SerialNumber: big.NewInt(1),
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().Add(2 * time.Hour),
ExcludedDNSDomains: []string{"example.com"},
PermittedDNSDomainsCritical: true,
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: caKeyUsage,
SubjectKeyId: caSki,
}
caCertBytes, err := x509.CreateCertificate(rand.Reader, &caTemplate, &caTemplate, caKey.Public(), caKey)
require.NoError(t, err)
ca, err := x509.ParseCertificate(caCertBytes)
require.NoError(t, err)
leafSki, err := computeSKI(leafKey.Public().(*ecdsa.PublicKey))
require.NoError(t, err)
leafTemplate := x509.Certificate{
Subject: pkix.Name{CommonName: "localhost"},
SerialNumber: big.NewInt(2),
NotBefore: time.Now().Add(-1 * time.Hour),
NotAfter: time.Now().Add(2 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
SubjectKeyId: leafSki,
}
leafCertBytes, err := x509.CreateCertificate(rand.Reader, &leafTemplate, ca, leafKey.Public(), caKey)
require.NoError(t, err)
keyBytes, err := x509.MarshalPKCS8PrivateKey(leafKey)
require.NoError(t, err)
caCertPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCertBytes})
leafCertPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leafCertBytes})
leafKeyPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})
t.Run("VerifyNameConstraintsSingleCert", func(t *testing.T) {
for _, der := range [][]byte{caCertBytes, leafCertBytes} {
cert, err := x509.ParseCertificate(der)
require.NoError(t, err, "failed to parse certificate")
err = verifyLegacyNameConstraints([]*x509.Certificate{cert})
require.NoError(t, err, "single certificate should not trigger legacy constraints")
}
})
t.Run("VerifyNameConstraints", func(t *testing.T) {
var certs []*x509.Certificate
for _, der := range [][]byte{leafCertBytes, caCertBytes} {
cert, err := x509.ParseCertificate(der)
require.NoError(t, err, "failed to parse certificate")
certs = append(certs, cert)
}
err = verifyLegacyNameConstraints(certs)
require.Error(t, err, "certificate chain should trigger legacy constraints")
var cie x509.CertificateInvalidError
require.True(t, errors.As(err, &cie))
require.Equal(t, x509.NameConstraintsWithoutSANs, cie.Reason)
})
t.Run("VerifyNameConstraintsWithSAN", func(t *testing.T) {
caCert, err := x509.ParseCertificate(caCertBytes)
require.NoError(t, err)
leafTemplate := leafTemplate
leafTemplate.DNSNames = []string{"localhost"}
leafCertBytes, err := x509.CreateCertificate(rand.Reader, &leafTemplate, caCert, leafKey.Public(), caKey)
require.NoError(t, err)
leafCert, err := x509.ParseCertificate(leafCertBytes)
require.NoError(t, err)
err = verifyLegacyNameConstraints([]*x509.Certificate{leafCert, caCert})
require.NoError(t, err, "signer with name constraints and leaf with SANs should be valid")
})
t.Run("ValidationAtSetup", func(t *testing.T) {
fabricMSPConfig := &msp.FabricMSPConfig{
Name: "ConstraintsMSP",
RootCerts: [][]byte{caCertPem},
SigningIdentity: &msp.SigningIdentityInfo{
PublicSigner: leafCertPem,
PrivateSigner: &msp.KeyInfo{
KeyIdentifier: "Certificate Without SAN",
KeyMaterial: leafKeyPem,
},
},
}
mspConfig := &msp.MSPConfig{
Config: protoutil.MarshalOrPanic(fabricMSPConfig),
}
ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join(configtest.GetDevMspDir(), "keystore"), true)
require.NoError(t, err)
cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(ks)
require.NoError(t, err)
testMSP, err := NewBccspMspWithKeyStore(MSPv1_0, ks, cryptoProvider)
require.NoError(t, err)
err = testMSP.Setup(mspConfig)
require.Error(t, err)
var cie x509.CertificateInvalidError
require.True(t, errors.As(err, &cie))
require.Equal(t, x509.NameConstraintsWithoutSANs, cie.Reason)
})
}
func TestIsWellFormed(t *testing.T) {
mspMgr := NewMSPManager()
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded, got err %s", err)
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded, got err %s", err)
return
}
sId := &msp.SerializedIdentity{}
err = proto.Unmarshal(serializedID, sId)
require.NoError(t, err)
// An MSP Manager without any MSPs should not recognize the identity since
// not providers are registered
err = mspMgr.IsWellFormed(sId)
require.Error(t, err)
require.Equal(t, "no MSP provider recognizes the identity", err.Error())
// Add the MSP to the MSP Manager
mspMgr.Setup([]MSP{localMsp})
err = localMsp.IsWellFormed(sId)
require.NoError(t, err)
err = mspMgr.IsWellFormed(sId)
require.NoError(t, err)
bl, _ := pem.Decode(sId.IdBytes)
require.Equal(t, "CERTIFICATE", bl.Type)
// Now, strip off the type from the PEM block. It should still be valid
bl.Type = ""
sId.IdBytes = pem.EncodeToMemory(bl)
err = localMsp.IsWellFormed(sId)
require.NoError(t, err)
// Now, corrupt the type of the PEM block.
// make sure it isn't considered well formed by both an MSP and an MSP Manager
bl.Type = "foo"
sId.IdBytes = pem.EncodeToMemory(bl)
err = localMsp.IsWellFormed(sId)
require.Error(t, err)
require.Contains(t, err.Error(), "pem type is")
require.Contains(t, err.Error(), "should be 'CERTIFICATE' or missing")
err = mspMgr.IsWellFormed(sId)
require.Error(t, err)
require.Equal(t, "no MSP provider recognizes the identity", err.Error())
// Restore the identity to what it was
sId = &msp.SerializedIdentity{}
err = proto.Unmarshal(serializedID, sId)
require.NoError(t, err)
// Append some trailing junk at the end
sId.IdBytes = append(sId.IdBytes, []byte{1, 2, 3}...)
// And ensure it is deemed invalid
err = localMsp.IsWellFormed(sId)
require.Error(t, err)
require.Contains(t, err.Error(), "for MSP SampleOrg has trailing bytes")
// Parse the certificate of the identity
cert, err := x509.ParseCertificate(bl.Bytes)
require.NoError(t, err)
// Obtain the ECDSA signature
r, s, err := utils.UnmarshalECDSASignature(cert.Signature)
require.NoError(t, err)
// Modify it by appending some bytes to its end.
modifiedSig, err := asn1.Marshal(rst{
R: r,
S: s,
T: big.NewInt(100),
})
require.NoError(t, err)
newCert, err := certFromX509Cert(cert)
require.NoError(t, err)
newCert.SignatureValue.Bytes = modifiedSig
newCert.SignatureValue.BitLength = len(newCert.SignatureValue.Bytes) * 8
newCert.Raw = nil
// Pour it back into the identity
rawCert, err := asn1.Marshal(newCert)
require.NoError(t, err)
sId.IdBytes = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rawCert})
// Ensure it is invalid now and the signature modification is detected
err = localMsp.IsWellFormed(sId)
require.Error(t, err)
require.Contains(t, err.Error(), "for MSP SampleOrg has a non canonical signature")
}
type rst struct {
R, S, T *big.Int
}
func TestValidateCAIdentity(t *testing.T) {
caID := getIdentity(t, cacerts)
err := localMsp.Validate(caID)
require.Error(t, err)
}
func TestBadAdminIdentity(t *testing.T) {
cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())
require.NoError(t, err)
conf, err := GetLocalMspConfig("testdata/badadmin", nil, "SampleOrg")
require.NoError(t, err)
thisMSP, err := newBccspMsp(MSPv1_0, cryptoProvider)
require.NoError(t, err)
ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join("testdata/badadmin", "keystore"), true)
require.NoError(t, err)
csp, err := sw.NewWithParams(256, "SHA2", ks)
require.NoError(t, err)
thisMSP.(*bccspmsp).bccsp = csp
err = thisMSP.Setup(conf)
require.Error(t, err)
}
func TestValidateAdminIdentity(t *testing.T) {
caID := getIdentity(t, admincerts)
err := localMsp.Validate(caID)
require.NoError(t, err)
}
func TestSerializeIdentitiesWithWrongMSP(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded, got err %s", err)
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded, got err %s", err)
return
}
sid := &msp.SerializedIdentity{}
err = proto.Unmarshal(serializedID, sid)
require.NoError(t, err)
sid.Mspid += "BARF"
serializedID, err = proto.Marshal(sid)
require.NoError(t, err)
_, err = localMsp.DeserializeIdentity(serializedID)
require.Error(t, err)
}
func TestSerializeIdentitiesWithMSPManager(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded, got err %s", err)
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded, got err %s", err)
return
}
_, err = mspMgr.DeserializeIdentity(serializedID)
require.NoError(t, err)
sid := &msp.SerializedIdentity{}
err = proto.Unmarshal(serializedID, sid)
require.NoError(t, err)
sid.Mspid += "BARF"
serializedID, err = proto.Marshal(sid)
require.NoError(t, err)
_, err = mspMgr.DeserializeIdentity(serializedID)
require.Error(t, err)
require.Contains(t, err.Error(), fmt.Sprintf("MSP %s is not defined on channel", sid.Mspid))
_, err = mspMgr.DeserializeIdentity([]byte("barf"))
require.Error(t, err)
require.Contains(t, err.Error(), "could not deserialize")
}
func TestIdentitiesGetters(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded, got err %s", err)
return
}
idid := id.GetIdentifier()
require.NotNil(t, idid)
mspid := id.GetMSPIdentifier()
require.NotNil(t, mspid)
require.False(t, id.Anonymous())
}
func TestSignAndVerify(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded")
return
}
idBack, err := localMsp.DeserializeIdentity(serializedID)
if err != nil {
t.Fatalf("DeserializeIdentity should have succeeded")
return
}
msg := []byte("foo")
sig, err := id.Sign(msg)
if err != nil {
t.Fatalf("Sign should have succeeded")
return
}
err = id.Verify(msg, sig)
if err != nil {
t.Fatalf("The signature should be valid")
return
}
err = idBack.Verify(msg, sig)
if err != nil {
t.Fatalf("The signature should be valid")
return
}
err = id.Verify(msg[1:], sig)
require.Error(t, err)
err = id.Verify(msg, sig[1:])
require.Error(t, err)
}
func TestSignAndVerifyFailures(t *testing.T) {
msg := []byte("foo")
id, err := localMspBad.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
hash := id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = "barf"
_, err = id.Sign(msg)
require.Error(t, err)
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
sig, err := id.Sign(msg)
if err != nil {
t.Fatalf("Sign should have succeeded")
return
}
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = "barf"
err = id.Verify(msg, sig)
require.Error(t, err)
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
}
func TestSignAndVerifyOtherHash(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
hash := id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = bccsp.SHA3
msg := []byte("foo")
sig, err := id.Sign(msg)
if err != nil {
t.Fatalf("Sign should have succeeded")
return
}
err = id.Verify(msg, sig)
require.NoError(t, err)
id.(*signingidentity).msp.cryptoConfig.SignatureHashFamily = hash
}
func TestSignAndVerify_longMessage(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
serializedID, err := id.Serialize()
if err != nil {
t.Fatalf("Serialize should have succeeded")
return
}
idBack, err := localMsp.DeserializeIdentity(serializedID)
if err != nil {
t.Fatalf("DeserializeIdentity should have succeeded")
return
}
msg := []byte("ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFG")
sig, err := id.Sign(msg)
if err != nil {
t.Fatalf("Sign should have succeeded")
return
}
err = id.Verify(msg, sig)
if err != nil {
t.Fatalf("The signature should be valid")
return
}
err = idBack.Verify(msg, sig)
if err != nil {
t.Fatalf("The signature should be valid")
return
}
}
func TestGetOU(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
require.Equal(t, "COP", id.GetOrganizationalUnits()[0].OrganizationalUnitIdentifier)
}
func TestGetOUFail(t *testing.T) {
id, err := localMspBad.GetDefaultSigningIdentity()
if err != nil {
t.Fatalf("GetDefaultSigningIdentity should have succeeded")
return
}
certTmp := id.(*signingidentity).cert
id.(*signingidentity).cert = nil
ou := id.GetOrganizationalUnits()
require.Nil(t, ou)
id.(*signingidentity).cert = certTmp
opts := id.(*signingidentity).msp.opts
id.(*signingidentity).msp.opts = nil
ou = id.GetOrganizationalUnits()
require.Nil(t, ou)
id.(*signingidentity).msp.opts = opts
}
func TestCertificationIdentifierComputation(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
chain, err := localMsp.(*bccspmsp).getCertificationChain(id.GetPublicVersion())
require.NoError(t, err)
// Hash the chain
// Use the hash of the identity's certificate as id in the IdentityIdentifier
hashOpt, err := bccsp.GetHashOpt(localMsp.(*bccspmsp).cryptoConfig.IdentityIdentifierHashFunction)
require.NoError(t, err)
hf, err := localMsp.(*bccspmsp).bccsp.GetHash(hashOpt)
require.NoError(t, err)
// Skipping first cert because it belongs to the identity
for i := 1; i < len(chain); i++ {
hf.Write(chain[i].Raw)
}
sum := hf.Sum(nil)
require.Equal(t, sum, id.GetOrganizationalUnits()[0].CertifiersIdentifier)
}
func TestOUPolicyPrincipal(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
cid, err := localMsp.(*bccspmsp).getCertificationChainIdentifier(id.GetPublicVersion())
require.NoError(t, err)
ou := &msp.OrganizationUnit{
OrganizationalUnitIdentifier: "COP",
MspIdentifier: "SampleOrg",
CertifiersIdentifier: cid,
}
bytes, err := proto.Marshal(ou)
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
Principal: bytes,
}
err = id.SatisfiesPrincipal(principal)
require.NoError(t, err)
}
func TestOUPolicyPrincipalBadPrincipal(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
Principal: []byte("barf"),
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestOUPolicyPrincipalBadMSPID(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
cid, err := localMsp.(*bccspmsp).getCertificationChainIdentifier(id.GetPublicVersion())
require.NoError(t, err)
ou := &msp.OrganizationUnit{
OrganizationalUnitIdentifier: "COP",
MspIdentifier: "SampleOrgbarfbarf",
CertifiersIdentifier: cid,
}
bytes, err := proto.Marshal(ou)
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
Principal: bytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestOUPolicyPrincipalBadPath(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
ou := &msp.OrganizationUnit{
OrganizationalUnitIdentifier: "COP",
MspIdentifier: "SampleOrg",
CertifiersIdentifier: nil,
}
bytes, err := proto.Marshal(ou)
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
Principal: bytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
ou = &msp.OrganizationUnit{
OrganizationalUnitIdentifier: "COP",
MspIdentifier: "SampleOrg",
CertifiersIdentifier: []byte{0, 1, 2, 3, 4},
}
bytes, err = proto.Marshal(ou)
require.NoError(t, err)
principal = &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ORGANIZATION_UNIT,
Principal: bytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestPolicyPrincipalBogusType(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
principalBytes, err := proto.Marshal(&msp.MSPRole{Role: 35, MspIdentifier: "SampleOrg"})
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: 35,
Principal: principalBytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestPolicyPrincipalBogusRole(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
principalBytes, err := proto.Marshal(&msp.MSPRole{Role: 35, MspIdentifier: "SampleOrg"})
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ROLE,
Principal: principalBytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestPolicyPrincipalWrongMSPID(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()
require.NoError(t, err)
principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_MEMBER, MspIdentifier: "SampleOrgBARFBARF"})
require.NoError(t, err)
principal := &msp.MSPPrincipal{
PrincipalClassification: msp.MSPPrincipal_ROLE,
Principal: principalBytes,
}
err = id.SatisfiesPrincipal(principal)
require.Error(t, err)
}
func TestMemberPolicyPrincipal(t *testing.T) {
id, err := localMsp.GetDefaultSigningIdentity()