/
util.go
1059 lines (923 loc) · 30.8 KB
/
util.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. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"bytes"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"math/big"
mrand "math/rand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"time"
"github.com/cloudflare/cfssl/log"
"github.com/hyperledger/fabric/bccsp"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/tjfoc/gmsm/sm2"
"golang.org/x/crypto/ocsp"
)
var (
rnd = mrand.NewSource(time.Now().UnixNano())
// ErrNotImplemented used to return errors for functions not implemented
ErrNotImplemented = errors.New("NOT YET IMPLEMENTED")
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// RevocationReasonCodes is a map between string reason codes to integers as defined in RFC 5280
var RevocationReasonCodes = map[string]int{
"unspecified": ocsp.Unspecified,
"keycompromise": ocsp.KeyCompromise,
"cacompromise": ocsp.CACompromise,
"affiliationchanged": ocsp.AffiliationChanged,
"superseded": ocsp.Superseded,
"cessationofoperation": ocsp.CessationOfOperation,
"certificatehold": ocsp.CertificateHold,
"removefromcrl": ocsp.RemoveFromCRL,
"privilegewithdrawn": ocsp.PrivilegeWithdrawn,
"aacompromise": ocsp.AACompromise,
}
// SecretTag to tag a field as secret as in password, token
const SecretTag = "mask"
// URLRegex is the regular expression to check if a value is an URL
var URLRegex = regexp.MustCompile("(ldap|http)s*://(\\S+):(\\S+)@")
//ECDSASignature forms the structure for R and S value for ECDSA
type ECDSASignature struct {
R, S *big.Int
}
// RandomString returns a random string
func RandomString(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, rnd.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rnd.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// RemoveQuotes removes outer quotes from a string if necessary
func RemoveQuotes(str string) string {
if str == "" {
return str
}
if (strings.HasPrefix(str, "'") && strings.HasSuffix(str, "'")) ||
(strings.HasPrefix(str, "\"") && strings.HasSuffix(str, "\"")) {
str = str[1 : len(str)-1]
}
return str
}
// ReadFile reads a file
func ReadFile(file string) ([]byte, error) {
return ioutil.ReadFile(file)
}
// WriteFile writes a file
func WriteFile(file string, buf []byte, perm os.FileMode) error {
dir := path.Dir(file)
// Create the directory if it doesn't exist
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
return errors.Wrapf(err, "Failed to create directory '%s' for file '%s'", dir, file)
}
}
return ioutil.WriteFile(file, buf, perm)
}
// FileExists checks to see if a file exists
func FileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// Marshal to bytes
func Marshal(from interface{}, what string) ([]byte, error) {
buf, err := json.Marshal(from)
if err != nil {
return nil, errors.Wrapf(err, "Failed to marshal %s", what)
}
return buf, nil
}
// Unmarshal from bytes
func Unmarshal(from []byte, to interface{}, what string) error {
err := json.Unmarshal(from, to)
if err != nil {
return errors.Wrapf(err, "Failed to unmarshal %s", what)
}
return nil
}
// CreateToken creates a JWT-like token.
// In a normal JWT token, the format of the token created is:
// <algorithm,claims,signature>
// where each part is base64-encoded string separated by a period.
// In this JWT-like token, there are two differences:
// 1) the claims section is a certificate, so the format is:
// <certificate,signature>
// 2) the signature uses the private key associated with the certificate,
// and the signature is across both the certificate and the "body" argument,
// which is the body of an HTTP request, though could be any arbitrary bytes.
// @param cert The pem-encoded certificate
// @param key The pem-encoded key
// @param method http method of the request
// @param uri URI of the request
// @param body The body of an HTTP request
func CreateToken(csp bccsp.BCCSP, cert []byte, key bccsp.Key, method, uri string, body []byte) (string, error) {
x509Cert, err := GetX509CertificateFromPEM(cert)
if err != nil {
return "", err
}
publicKey := x509Cert.PublicKey
var token string
//The RSA Key Gen is commented right now as there is bccsp does
switch publicKey.(type) {
/*
case *rsa.PublicKey:
token, err = GenRSAToken(csp, cert, key, body)
if err != nil {
return "", err
}
*/
case *ecdsa.PublicKey:
token, err = GenECDSAToken(csp, cert, key, method, uri, body)
if err != nil {
return "", err
}
case *sm2.PublicKey:
token, err = GenECDSAToken(csp, cert, key, method, uri, body)
if err != nil {
return "", err
}
}
return token, nil
}
//GenRSAToken signs the http body and cert with RSA using RSA private key
// @csp : BCCSP instance
/*
func GenRSAToken(csp bccsp.BCCSP, cert []byte, key []byte, body []byte) (string, error) {
privKey, err := GetRSAPrivateKey(key)
if err != nil {
return "", err
}
b64body := B64Encode(body)
b64cert := B64Encode(cert)
bodyAndcert := b64body + "." + b64cert
hash := sha512.New384()
hash.Write([]byte(bodyAndcert))
h := hash.Sum(nil)
RSAsignature, err := rsa.SignPKCS1v15(rand.Reader, privKey, crypto.SHA384, h[:])
if err != nil {
return "", errors.Wrap(err, "Failed to rsa.SignPKCS1v15")
}
b64sig := B64Encode(RSAsignature)
token := b64cert + "." + b64sig
return token, nil
}
*/
//GenECDSAToken signs the http body and cert with ECDSA using EC private key
func GenECDSAToken(csp bccsp.BCCSP, cert []byte, key bccsp.Key, method, uri string, body []byte) (string, error) {
b64body := B64Encode(body)
b64cert := B64Encode(cert)
b64uri := B64Encode([]byte(uri))
payload := method + "." + b64uri + "." + b64body + "." + b64cert
return genECDSAToken(csp, key, b64cert, payload)
}
func genECDSAToken(csp bccsp.BCCSP, key bccsp.Key, b64cert, payload string) (string, error) {
digest, digestError := csp.Hash([]byte(payload), &bccsp.SHAOpts{})
if digestError != nil {
return "", errors.WithMessage(digestError, fmt.Sprintf("Hash failed on '%s'", payload))
}
ecSignature, err := csp.Sign(key, digest, nil)
if err != nil {
return "", errors.WithMessage(err, "BCCSP signature generation failure")
}
if len(ecSignature) == 0 {
return "", errors.New("BCCSP signature creation failed. Signature must be different than nil")
}
b64sig := B64Encode(ecSignature)
token := b64cert + "." + b64sig
return token, nil
}
// VerifyToken verifies token signed by either ECDSA or RSA and
// returns the associated user ID
func VerifyToken(csp bccsp.BCCSP, token string, method, uri string, body []byte, compMode1_3 bool) (*x509.Certificate, error) {
if csp == nil {
return nil, errors.New("BCCSP instance is not present")
}
x509Cert, b64Cert, b64Sig, err := DecodeToken(token)
if err != nil {
return nil, err
}
sig, err := B64Decode(b64Sig)
if err != nil {
return nil, errors.WithMessage(err, "Invalid base64 encoded signature in token")
}
b64Body := B64Encode(body)
b64uri := B64Encode([]byte(uri))
sigString := method + "." + b64uri + "." + b64Body + "." + b64Cert
log.Infof("xxx before csp.KeyImport csp : %T b64Body %s", csp, sigString)
sm2Cert := ParseX509Certificate2Sm2(x509Cert)
pk2, err := csp.KeyImport(sm2Cert, &bccsp.X509PublicKeyImportOpts{Temporary: true})
log.Infof("xxx end csp.KeyImport pk2: %T", pk2)
if err != nil {
return nil, errors.WithMessage(err, "Public Key import into BCCSP failed with error")
}
if pk2 == nil {
return nil, errors.New("Public Key Cannot be imported into BCCSP")
}
//bccsp.X509PublicKeyImportOpts
//Using default hash algo
digest, digestError := csp.Hash([]byte(sigString), &bccsp.SHA256Opts{})
if digestError != nil {
return nil, errors.WithMessage(digestError, "Message digest failed")
}
log.Debugf("pk2 %T \n sig %T\n digest %s\n", pk2, sig, B64Encode(digest))
valid, validErr := csp.Verify(pk2, sig, digest, nil)
if compMode1_3 && !valid {
log.Debugf("Failed to verify token based on new authentication header requirements: %s", err)
sigString := b64Body + "." + b64Cert
digest, digestError := csp.Hash([]byte(sigString), &bccsp.SHA256Opts{})
if digestError != nil {
return nil, errors.WithMessage(digestError, "Message digest failed")
}
valid, validErr = csp.Verify(pk2, sig, digest, nil)
}
if validErr != nil {
return nil, errors.WithMessage(validErr, "Token signature validation failure")
}
if !valid {
return nil, errors.New("Token signature validation failed")
}
return x509Cert, nil
}
// X509证书格式转换为 SM2证书格式
func ParseX509Certificate2Sm2(x509Cert *x509.Certificate) *sm2.Certificate {
sm2cert := &sm2.Certificate{
Raw: x509Cert.Raw,
RawTBSCertificate: x509Cert.RawTBSCertificate,
RawSubjectPublicKeyInfo: x509Cert.RawSubjectPublicKeyInfo,
RawSubject: x509Cert.RawSubject,
RawIssuer: x509Cert.RawIssuer,
Signature: x509Cert.Signature,
SignatureAlgorithm: sm2.SignatureAlgorithm(x509Cert.SignatureAlgorithm),
PublicKeyAlgorithm: sm2.PublicKeyAlgorithm(x509Cert.PublicKeyAlgorithm),
PublicKey: x509Cert.PublicKey,
Version: x509Cert.Version,
SerialNumber: x509Cert.SerialNumber,
Issuer: x509Cert.Issuer,
Subject: x509Cert.Subject,
NotBefore: x509Cert.NotBefore,
NotAfter: x509Cert.NotAfter,
KeyUsage: sm2.KeyUsage(x509Cert.KeyUsage),
Extensions: x509Cert.Extensions,
ExtraExtensions: x509Cert.ExtraExtensions,
UnhandledCriticalExtensions: x509Cert.UnhandledCriticalExtensions,
//ExtKeyUsage: []x509.ExtKeyUsage(x509Cert.ExtKeyUsage) ,
UnknownExtKeyUsage: x509Cert.UnknownExtKeyUsage,
BasicConstraintsValid: x509Cert.BasicConstraintsValid,
IsCA: x509Cert.IsCA,
MaxPathLen: x509Cert.MaxPathLen,
// MaxPathLenZero indicates that BasicConstraintsValid==true and
// MaxPathLen==0 should be interpreted as an actual maximum path length
// of zero. Otherwise, that combination is interpreted as MaxPathLen
// not being set.
MaxPathLenZero: x509Cert.MaxPathLenZero,
SubjectKeyId: x509Cert.SubjectKeyId,
AuthorityKeyId: x509Cert.AuthorityKeyId,
// RFC 5280, 4.2.2.1 (Authority Information Access)
OCSPServer: x509Cert.OCSPServer,
IssuingCertificateURL: x509Cert.IssuingCertificateURL,
// Subject Alternate Name values
DNSNames: x509Cert.DNSNames,
EmailAddresses: x509Cert.EmailAddresses,
IPAddresses: x509Cert.IPAddresses,
// Name constraints
PermittedDNSDomainsCritical: x509Cert.PermittedDNSDomainsCritical,
PermittedDNSDomains: x509Cert.PermittedDNSDomains,
// CRL Distribution Points
CRLDistributionPoints: x509Cert.CRLDistributionPoints,
PolicyIdentifiers: x509Cert.PolicyIdentifiers,
}
for _, val := range x509Cert.ExtKeyUsage {
sm2cert.ExtKeyUsage = append(sm2cert.ExtKeyUsage, sm2.ExtKeyUsage(val))
}
return sm2cert
}
// DecodeToken extracts an X509 certificate and base64 encoded signature from a token
func DecodeToken(token string) (*x509.Certificate, string, string, error) {
if token == "" {
return nil, "", "", errors.New("Invalid token; it is empty")
}
parts := strings.Split(token, ".")
if len(parts) != 2 {
return nil, "", "", errors.New("Invalid token format; expecting 2 parts separated by '.'")
}
b64cert := parts[0]
certDecoded, err := B64Decode(b64cert)
if err != nil {
return nil, "", "", errors.WithMessage(err, "Failed to decode base64 encoded x509 cert")
}
x509Cert, err := GetX509CertificateFromPEM(certDecoded)
if err != nil {
return nil, "", "", errors.WithMessage(err, "Error in parsing x509 certificate given block bytes")
}
return x509Cert, b64cert, parts[1], nil
}
//GetECPrivateKey get *ecdsa.PrivateKey from key pem
func GetECPrivateKey(raw []byte) (*ecdsa.PrivateKey, error) {
decoded, _ := pem.Decode(raw)
if decoded == nil {
return nil, errors.New("Failed to decode the PEM-encoded ECDSA key")
}
ECprivKey, err := x509.ParseECPrivateKey(decoded.Bytes)
if err == nil {
return ECprivKey, nil
}
key, err2 := x509.ParsePKCS8PrivateKey(decoded.Bytes)
if err2 == nil {
switch key.(type) {
case *ecdsa.PrivateKey:
return key.(*ecdsa.PrivateKey), nil
case *rsa.PrivateKey:
return nil, errors.New("Expecting EC private key but found RSA private key")
default:
return nil, errors.New("Invalid private key type in PKCS#8 wrapping")
}
}
return nil, errors.Wrap(err2, "Failed parsing EC private key")
}
//GetRSAPrivateKey get *rsa.PrivateKey from key pem
func GetRSAPrivateKey(raw []byte) (*rsa.PrivateKey, error) {
decoded, _ := pem.Decode(raw)
if decoded == nil {
return nil, errors.New("Failed to decode the PEM-encoded RSA key")
}
RSAprivKey, err := x509.ParsePKCS1PrivateKey(decoded.Bytes)
if err == nil {
return RSAprivKey, nil
}
key, err2 := x509.ParsePKCS8PrivateKey(raw)
if err2 == nil {
switch key.(type) {
case *ecdsa.PrivateKey:
return nil, errors.New("Expecting RSA private key but found EC private key")
case *rsa.PrivateKey:
return key.(*rsa.PrivateKey), nil
default:
return nil, errors.New("Invalid private key type in PKCS#8 wrapping")
}
}
return nil, errors.Wrap(err, "Failed parsing RSA private key")
}
//GetSM2PrivateKey get *sm2.PrivateKey from key pem
func GetSM2PrivateKey(raw []byte) (*sm2.PrivateKey, error) {
decoded, _ := pem.Decode(raw)
if decoded == nil {
return nil, errors.New("Failed to decode the PEM-encoded RSA key")
}
if key, err := sm2.ParsePKCS8UnecryptedPrivateKey(decoded.Bytes); err == nil {
return key, nil
} else {
return nil, fmt.Errorf("tls: failed to parse private key %v", err)
}
}
// B64Encode base64 encodes bytes
func B64Encode(buf []byte) string {
return base64.StdEncoding.EncodeToString(buf)
}
// B64Decode base64 decodes a string
func B64Decode(str string) (buf []byte, err error) {
return base64.StdEncoding.DecodeString(str)
}
// StrContained returns true if 'str' is in 'strs'; otherwise return false
func StrContained(str string, strs []string) bool {
for _, s := range strs {
if strings.ToLower(s) == strings.ToLower(str) {
return true
}
}
return false
}
// IsSubsetOf returns an error if there is something in 'small' that
// is not in 'big'. Both small and big are assumed to be comma-separated
// strings. All string comparisons are case-insensitive.
// Examples:
// 1) IsSubsetOf('a,B', 'A,B,C') returns nil
// 2) IsSubsetOf('A,B,C', 'B,C') returns an error because A is not in the 2nd set.
func IsSubsetOf(small, big string) error {
bigSet := strings.Split(big, ",")
smallSet := strings.Split(small, ",")
for _, s := range smallSet {
if s != "" && !StrContained(s, bigSet) {
return errors.Errorf("'%s' is not a member of '%s'", s, big)
}
}
return nil
}
// HTTPRequestToString returns a string for an HTTP request for debuggging
func HTTPRequestToString(req *http.Request) string {
body, _ := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewReader(body))
return fmt.Sprintf("%s %s\n%s",
req.Method, req.URL, string(body))
}
// HTTPResponseToString returns a string for an HTTP response for debuggging
func HTTPResponseToString(resp *http.Response) string {
body, _ := ioutil.ReadAll(resp.Body)
resp.Body = ioutil.NopCloser(bytes.NewReader(body))
return fmt.Sprintf("statusCode=%d (%s)\n%s",
resp.StatusCode, resp.Status, string(body))
}
// CreateClientHome will create a home directory if it does not exist
func CreateClientHome() (string, error) {
log.Debug("CreateHome")
home := filepath.Dir(GetDefaultConfigFile("fabric-ca-client"))
if _, err := os.Stat(home); err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(home, 0755)
if err != nil {
return "", err
}
}
}
return home, nil
}
// GetDefaultConfigFile gets the default path for the config file to display in usage message
func GetDefaultConfigFile(cmdName string) string {
if cmdName == "fabric-ca-server" {
var fname = fmt.Sprintf("%s-config.yaml", cmdName)
// First check home env variables
home := "."
envs := []string{"FABRIC_CA_SERVER_HOME", "FABRIC_CA_HOME", "CA_CFG_PATH"}
for _, env := range envs {
envVal := os.Getenv(env)
if envVal != "" {
home = envVal
break
}
}
return path.Join(home, fname)
}
var fname = fmt.Sprintf("%s-config.yaml", cmdName)
// First check home env variables
var home string
envs := []string{"FABRIC_CA_CLIENT_HOME", "FABRIC_CA_HOME", "CA_CFG_PATH"}
for _, env := range envs {
envVal := os.Getenv(env)
if envVal != "" {
home = envVal
return path.Join(home, fname)
}
}
return path.Join(os.Getenv("HOME"), ".fabric-ca-client", fname)
}
// GetX509CertificateFromPEMFile gets an X509 certificate from a file
func GetX509CertificateFromPEMFile(file string) (*x509.Certificate, error) {
pemBytes, err := ReadFile(file)
if err != nil {
return nil, err
}
x509Cert, err := GetX509CertificateFromPEM(pemBytes)
if err != nil {
return nil, errors.Wrapf(err, "Invalid certificate in '%s'", file)
}
return x509Cert, nil
}
// GetX509CertificateFromPEM get an X509 certificate from bytes in PEM format
func GetX509CertificateFromPEM(cert []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(cert)
if block == nil {
return nil, errors.New("Failed to PEM decode certificate")
}
var x509Cert *x509.Certificate
var err error
if IsGMConfig() {
sm2x509Cert, err := sm2.ParseCertificate(block.Bytes)
if err == nil {
x509Cert = ParseSm2Certificate2X509(sm2x509Cert)
}
} else {
x509Cert, err = x509.ParseCertificate(block.Bytes)
}
if err != nil {
return nil, errors.Wrap(err, "Error parsing certificate1212121")
}
return x509Cert, nil
}
//sm2 证书转换 x509 证书
func ParseSm2Certificate2X509(sm2Cert *sm2.Certificate) *x509.Certificate {
x509cert := &x509.Certificate{
Raw: sm2Cert.Raw,
RawTBSCertificate: sm2Cert.RawTBSCertificate,
RawSubjectPublicKeyInfo: sm2Cert.RawSubjectPublicKeyInfo,
RawSubject: sm2Cert.RawSubject,
RawIssuer: sm2Cert.RawIssuer,
Signature: sm2Cert.Signature,
SignatureAlgorithm: x509.SignatureAlgorithm(sm2Cert.SignatureAlgorithm),
PublicKeyAlgorithm: x509.PublicKeyAlgorithm(sm2Cert.PublicKeyAlgorithm),
PublicKey: sm2Cert.PublicKey,
Version: sm2Cert.Version,
SerialNumber: sm2Cert.SerialNumber,
Issuer: sm2Cert.Issuer,
Subject: sm2Cert.Subject,
NotBefore: sm2Cert.NotBefore,
NotAfter: sm2Cert.NotAfter,
KeyUsage: x509.KeyUsage(sm2Cert.KeyUsage),
Extensions: sm2Cert.Extensions,
ExtraExtensions: sm2Cert.ExtraExtensions,
UnhandledCriticalExtensions: sm2Cert.UnhandledCriticalExtensions,
//ExtKeyUsage: []x509.ExtKeyUsage(sm2Cert.ExtKeyUsage) ,
UnknownExtKeyUsage: sm2Cert.UnknownExtKeyUsage,
BasicConstraintsValid: sm2Cert.BasicConstraintsValid,
IsCA: sm2Cert.IsCA,
MaxPathLen: sm2Cert.MaxPathLen,
// MaxPathLenZero indicates that BasicConstraintsValid==true and
// MaxPathLen==0 should be interpreted as an actual maximum path length
// of zero. Otherwise, that combination is interpreted as MaxPathLen
// not being set.
MaxPathLenZero: sm2Cert.MaxPathLenZero,
SubjectKeyId: sm2Cert.SubjectKeyId,
AuthorityKeyId: sm2Cert.AuthorityKeyId,
// RFC 5280, 4.2.2.1 (Authority Information Access)
OCSPServer: sm2Cert.OCSPServer,
IssuingCertificateURL: sm2Cert.IssuingCertificateURL,
// Subject Alternate Name values
DNSNames: sm2Cert.DNSNames,
EmailAddresses: sm2Cert.EmailAddresses,
IPAddresses: sm2Cert.IPAddresses,
// Name constraints
PermittedDNSDomainsCritical: sm2Cert.PermittedDNSDomainsCritical,
PermittedDNSDomains: sm2Cert.PermittedDNSDomains,
// CRL Distribution Points
CRLDistributionPoints: sm2Cert.CRLDistributionPoints,
PolicyIdentifiers: sm2Cert.PolicyIdentifiers,
}
for _, val := range sm2Cert.ExtKeyUsage {
x509cert.ExtKeyUsage = append(x509cert.ExtKeyUsage, x509.ExtKeyUsage(val))
}
return x509cert
}
// GetX509CertificatesFromPEM returns X509 certificates from bytes in PEM format
func GetX509CertificatesFromPEM(pemBytes []byte) ([]*x509.Certificate, error) {
chain := pemBytes
var certs []*x509.Certificate
for len(chain) > 0 {
var block *pem.Block
block, chain = pem.Decode(chain)
if block == nil {
break
}
var x509Cert *x509.Certificate
var err error
if IsGMConfig() {
sm2x509Cert, err := sm2.ParseCertificate(block.Bytes)
if err == nil {
x509Cert = ParseSm2Certificate2X509(sm2x509Cert)
}
} else {
x509Cert, err = x509.ParseCertificate(block.Bytes)
}
// cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "Error parsing certificate")
}
certs = append(certs, x509Cert)
}
return certs, nil
}
// GetCertificateDurationFromFile returns the validity duration for a certificate
// in a file.
func GetCertificateDurationFromFile(file string) (time.Duration, error) {
cert, err := GetX509CertificateFromPEMFile(file)
if err != nil {
return 0, err
}
return GetCertificateDuration(cert), nil
}
// GetCertificateDuration returns the validity duration for a certificate
func GetCertificateDuration(cert *x509.Certificate) time.Duration {
return cert.NotAfter.Sub(cert.NotBefore)
}
// GetEnrollmentIDFromPEM returns the EnrollmentID from a PEM buffer
func GetEnrollmentIDFromPEM(cert []byte) (string, error) {
x509Cert, err := GetX509CertificateFromPEM(cert)
if err != nil {
return "", err
}
return GetEnrollmentIDFromX509Certificate(x509Cert), nil
}
// GetEnrollmentIDFromX509Certificate returns the EnrollmentID from the X509 certificate
func GetEnrollmentIDFromX509Certificate(cert *x509.Certificate) string {
return cert.Subject.CommonName
}
// MakeFileAbs makes 'file' absolute relative to 'dir' if not already absolute
func MakeFileAbs(file, dir string) (string, error) {
if file == "" {
return "", nil
}
if filepath.IsAbs(file) {
return file, nil
}
path, err := filepath.Abs(filepath.Join(dir, file))
if err != nil {
return "", errors.Wrapf(err, "Failed making '%s' absolute based on '%s'", file, dir)
}
return path, nil
}
// MakeFileNamesAbsolute makes all file names in the list absolute, relative to home
func MakeFileNamesAbsolute(files []*string, home string) error {
for _, filePtr := range files {
abs, err := MakeFileAbs(*filePtr, home)
if err != nil {
return err
}
*filePtr = abs
}
return nil
}
// Fatal logs a fatal message and exits
func Fatal(format string, v ...interface{}) {
log.Fatalf(format, v...)
os.Exit(1)
}
// GetUser returns username and password from CLI input
func GetUser(v *viper.Viper) (string, string, error) {
var fabricCAServerURL string
fabricCAServerURL = v.GetString("url")
URL, err := url.Parse(fabricCAServerURL)
if err != nil {
return "", "", err
}
user := URL.User
if user == nil {
return "", "", errors.New("No username and password provided as part of the Fabric CA server URL")
}
eid := user.Username()
if eid == "" {
return "", "", errors.New("No username provided as part of URL")
}
pass, _ := user.Password()
if pass == "" {
return "", "", errors.New("No password provided as part of URL")
}
return eid, pass, nil
}
// GetSerialAsHex returns the serial number from certificate as hex format
func GetSerialAsHex(serial *big.Int) string {
hex := fmt.Sprintf("%x", serial)
return hex
}
// StructToString converts a struct to a string. If a field
// has a 'secret' tag, it is masked in the returned string
func StructToString(si interface{}) string {
rval := reflect.ValueOf(si).Elem()
tipe := rval.Type()
var buffer bytes.Buffer
buffer.WriteString("{ ")
for i := 0; i < rval.NumField(); i++ {
tf := tipe.Field(i)
if !rval.FieldByName(tf.Name).CanSet() {
continue // skip unexported fields
}
var fStr string
tagv := tf.Tag.Get(SecretTag)
if tagv == "password" || tagv == "username" {
fStr = fmt.Sprintf("%s:**** ", tf.Name)
} else if tagv == "url" {
val, ok := rval.Field(i).Interface().(string)
if ok {
val = GetMaskedURL(val)
fStr = fmt.Sprintf("%s:%v ", tf.Name, val)
} else {
fStr = fmt.Sprintf("%s:%v ", tf.Name, rval.Field(i).Interface())
}
} else {
fStr = fmt.Sprintf("%s:%v ", tf.Name, rval.Field(i).Interface())
}
buffer.WriteString(fStr)
}
buffer.WriteString(" }")
return buffer.String()
}
// GetMaskedURL returns masked URL. It masks username and password from the URL
// if present
func GetMaskedURL(url string) string {
matches := URLRegex.FindStringSubmatch(url)
// If there is a match, there should be four entries: 1 for
// the match and 3 for submatches
if len(matches) == 4 {
matchIdxs := URLRegex.FindStringSubmatchIndex(url)
matchStr := url[matchIdxs[0]:matchIdxs[1]]
for idx := 2; idx < len(matches); idx++ {
if matches[idx] != "" {
matchStr = strings.Replace(matchStr, matches[idx], "****", 1)
}
}
url = url[:matchIdxs[0]] + matchStr + url[matchIdxs[1]:len(url)]
}
return url
}
// NormalizeStringSlice checks for seperators
func NormalizeStringSlice(slice []string) []string {
var normalizedSlice []string
for _, item := range slice {
// Remove surrounding brackets "[]" if specified
if strings.HasPrefix(item, "[") && strings.HasSuffix(item, "]") {
item = item[1 : len(item)-1]
}
// Split elements based on comma and add to normalized slice
elems := strings.Split(item, ",")
for _, elem := range elems {
normalizedSlice = append(normalizedSlice, strings.TrimSpace(elem))
}
}
return normalizedSlice
}
// NormalizeFileList provides absolute pathing for the list of files
func NormalizeFileList(files []string, homeDir string) ([]string, error) {
var err error
files = NormalizeStringSlice(files)
for i, file := range files {
files[i], err = MakeFileAbs(file, homeDir)
if err != nil {
return nil, err
}
}
return files, nil
}
// CheckHostsInCert checks to see if host correctly inserted into certificate
func CheckHostsInCert(certFile string, hosts ...string) error {
certBytes, err := ioutil.ReadFile(certFile)
if err != nil {
return errors.Wrapf(err, "Failed to read certificate file at '%s'", certFile)
}
cert, err := GetX509CertificateFromPEM(certBytes)
if err != nil {
return errors.Wrap(err, "Failed to get certificate")
}
// combine DNSNames and IPAddresses from cert
sans := cert.DNSNames
for _, ip := range cert.IPAddresses {
sans = append(sans, ip.String())
}
for _, host := range hosts {
if !containsString(sans, host) {
return errors.Errorf("Host '%s' was not found in the certificate in file '%s'", host, certFile)
}
}
return nil
}
func containsString(list []string, item string) bool {
for _, elem := range list {
if elem == item {
return true
}
}
return false
}
// Read reads from Reader into a byte array
func Read(r io.Reader, data []byte) ([]byte, error) {
j := 0
for {
n, err := r.Read(data[j:])
j = j + n
if err != nil {
if err == io.EOF {
break
}
return nil, errors.Wrapf(err, "Read failure")
}
if (n == 0 && j == len(data)) || j > len(data) {
return nil, errors.New("Size of requested data is too large")
}
}
return data[:j], nil
}
// Hostname name returns the hostname of the machine
func Hostname() string {
hostname, _ := os.Hostname()
if hostname == "" {
hostname = "localhost"
}
return hostname
}
// ValidateAndReturnAbsConf checks to see that there are no conflicts between the
// configuration file path and home directory. If no conflicts, returns back the absolute
// path for the configuration file and home directory.
func ValidateAndReturnAbsConf(configFilePath, homeDir, cmdName string) (string, string, error) {
var err error
var homeDirSet bool
var configFileSet bool
defaultConfig := GetDefaultConfigFile(cmdName) // Get the default configuration
if configFilePath == "" {
configFilePath = defaultConfig // If no config file path specified, use the default configuration file
} else {
configFileSet = true
}
if homeDir == "" {
homeDir = filepath.Dir(defaultConfig) // If no home directory specified, use the default directory
} else {
homeDirSet = true
}
// Make the home directory absolute
homeDir, err = filepath.Abs(homeDir)
if err != nil {
return "", "", errors.Wrap(err, "Failed to get full path of config file")
}
homeDir = strings.TrimRight(homeDir, "/")
if configFileSet && homeDirSet {
log.Warning("Using both --config and --home CLI flags; --config will take precedence")
}
if configFileSet {
configFilePath, err = filepath.Abs(configFilePath)
if err != nil {
return "", "", errors.Wrap(err, "Failed to get full path of configuration file")
}
return configFilePath, filepath.Dir(configFilePath), nil
}