forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 11
/
connection.go
215 lines (187 loc) · 6.18 KB
/
connection.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package comm
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"sync"
"time"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/core/config"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
const defaultTimeout = time.Second * 3
var commLogger = flogging.MustGetLogger("comm")
var caSupport *CASupport
var once sync.Once
// CASupport type manages certificate authorities scoped by channel
type CASupport struct {
sync.RWMutex
AppRootCAsByChain map[string][][]byte
OrdererRootCAsByChain map[string][][]byte
ClientRootCAs [][]byte
ServerRootCAs [][]byte
}
// GetCASupport returns the signleton CASupport instance
func GetCASupport() *CASupport {
once.Do(func() {
caSupport = &CASupport{
AppRootCAsByChain: make(map[string][][]byte),
OrdererRootCAsByChain: make(map[string][][]byte),
}
})
return caSupport
}
// GetServerRootCAs returns the PEM-encoded root certificates for all of the
// application and orderer organizations defined for all chains. The root
// certificates returned should be used to set the trusted server roots for
// TLS clients.
func (cas *CASupport) GetServerRootCAs() (appRootCAs, ordererRootCAs [][]byte) {
cas.RLock()
defer cas.RUnlock()
appRootCAs = [][]byte{}
ordererRootCAs = [][]byte{}
for _, appRootCA := range cas.AppRootCAsByChain {
appRootCAs = append(appRootCAs, appRootCA...)
}
for _, ordererRootCA := range cas.OrdererRootCAsByChain {
ordererRootCAs = append(ordererRootCAs, ordererRootCA...)
}
// also need to append statically configured root certs
appRootCAs = append(appRootCAs, cas.ServerRootCAs...)
return appRootCAs, ordererRootCAs
}
// GetDeliverServiceCredentials returns GRPC transport credentials for given channel to be used by GRPC
// clients which communicate with ordering service endpoints.
// If the channel isn't found, error is returned.
func (cas *CASupport) GetDeliverServiceCredentials(channelID string) (credentials.TransportCredentials, error) {
cas.RLock()
defer cas.RUnlock()
var creds credentials.TransportCredentials
var tlsConfig = &tls.Config{}
var certPool = x509.NewCertPool()
rootCACerts, exists := cas.OrdererRootCAsByChain[channelID]
if !exists {
commLogger.Errorf("Attempted to obtain root CA certs of a non existent channel: %s", channelID)
return nil, fmt.Errorf("didn't find any root CA certs for channel %s", channelID)
}
for _, cert := range rootCACerts {
block, _ := pem.Decode(cert)
if block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err == nil {
certPool.AddCert(cert)
} else {
commLogger.Warningf("Failed to add root cert to credentials (%s)", err)
}
} else {
commLogger.Warning("Failed to add root cert to credentials")
}
}
tlsConfig.RootCAs = certPool
creds = credentials.NewTLS(tlsConfig)
return creds, nil
}
// GetPeerCredentials returns GRPC transport credentials for use by GRPC
// clients which communicate with remote peer endpoints.
func (cas *CASupport) GetPeerCredentials(tlsCert tls.Certificate) credentials.TransportCredentials {
var creds credentials.TransportCredentials
var tlsConfig = &tls.Config{
Certificates: []tls.Certificate{tlsCert},
}
var certPool = x509.NewCertPool()
// loop through the orderer CAs
roots, _ := cas.GetServerRootCAs()
for _, root := range roots {
block, _ := pem.Decode(root)
if block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err == nil {
certPool.AddCert(cert)
} else {
commLogger.Warningf("Failed to add root cert to credentials (%s)", err)
}
} else {
commLogger.Warning("Failed to add root cert to credentials")
}
}
tlsConfig.RootCAs = certPool
creds = credentials.NewTLS(tlsConfig)
return creds
}
// GetClientRootCAs returns the PEM-encoded root certificates for all of the
// application and orderer organizations defined for all chains. The root
// certificates returned should be used to set the trusted client roots for
// TLS servers.
func (cas *CASupport) GetClientRootCAs() (appRootCAs, ordererRootCAs [][]byte) {
cas.RLock()
defer cas.RUnlock()
appRootCAs = [][]byte{}
ordererRootCAs = [][]byte{}
for _, appRootCA := range cas.AppRootCAsByChain {
appRootCAs = append(appRootCAs, appRootCA...)
}
for _, ordererRootCA := range cas.OrdererRootCAsByChain {
ordererRootCAs = append(ordererRootCAs, ordererRootCA...)
}
// also need to append statically configured root certs
appRootCAs = append(appRootCAs, cas.ClientRootCAs...)
return appRootCAs, ordererRootCAs
}
func getEnv(key, def string) string {
val := os.Getenv(key)
if len(val) > 0 {
return val
} else {
return def
}
}
func GetPeerTestingAddress(port string) string {
return getEnv("UNIT_TEST_PEER_IP", "localhost") + ":" + port
}
// NewClientConnectionWithAddress Returns a new grpc.ClientConn to the given address.
func NewClientConnectionWithAddress(peerAddress string, block bool, tslEnabled bool, creds credentials.TransportCredentials) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
if tslEnabled {
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
opts = append(opts, grpc.WithTimeout(defaultTimeout))
if block {
opts = append(opts, grpc.WithBlock())
}
opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(MaxRecvMsgSize()),
grpc.MaxCallSendMsgSize(MaxSendMsgSize())))
conn, err := grpc.Dial(peerAddress, opts...)
if err != nil {
return nil, err
}
return conn, err
}
// InitTLSForPeer returns TLS credentials for peer
func InitTLSForPeer() credentials.TransportCredentials {
var sn string
if viper.GetString("peer.tls.serverhostoverride") != "" {
sn = viper.GetString("peer.tls.serverhostoverride")
}
var creds credentials.TransportCredentials
if config.GetPath("peer.tls.rootcert.file") != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(config.GetPath("peer.tls.rootcert.file"), sn)
if err != nil {
grpclog.Fatalf("Failed to create TLS credentials %v", err)
}
} else {
creds = credentials.NewClientTLSFromCert(nil, sn)
}
return creds
}