github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/core/comm/creds.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package comm 8 9 import ( 10 "crypto/tls" 11 "errors" 12 "net" 13 14 "golang.org/x/net/context" 15 "google.golang.org/grpc/credentials" 16 ) 17 18 var ( 19 ClientHandshakeNotImplError = errors.New("core/comm: Client handshakes" + 20 "are not implemented with serverCreds") 21 OverrrideHostnameNotSupportedError = errors.New( 22 "core/comm: OverrideServerName is " + 23 "not supported") 24 MissingServerConfigError = errors.New( 25 "core/comm: `serverConfig` cannot be nil") 26 // alpnProtoStr are the specified application level protocols for gRPC. 27 alpnProtoStr = []string{"h2"} 28 ) 29 30 // NewServerTransportCredentials returns a new initialized 31 // grpc/credentials.TransportCredentials 32 func NewServerTransportCredentials(serverConfig *tls.Config) credentials.TransportCredentials { 33 // NOTE: unlike the default grpc/credentials implementation, we do not 34 // clone the tls.Config which allows us to update it dynamically 35 serverConfig.NextProtos = alpnProtoStr 36 // override TLS version and ensure it is 1.2 37 serverConfig.MinVersion = tls.VersionTLS12 38 serverConfig.MaxVersion = tls.VersionTLS12 39 return &serverCreds{serverConfig} 40 } 41 42 // serverCreds is an implementation of grpc/credentials.TransportCredentials. 43 type serverCreds struct { 44 serverConfig *tls.Config 45 } 46 47 // ClientHandShake is not implemented for `serverCreds`. 48 func (sc *serverCreds) ClientHandshake(context.Context, 49 string, net.Conn) (net.Conn, credentials.AuthInfo, error) { 50 return nil, nil, ClientHandshakeNotImplError 51 } 52 53 // ServerHandshake does the authentication handshake for servers. 54 func (sc *serverCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { 55 conn := tls.Server(rawConn, sc.serverConfig) 56 if err := conn.Handshake(); err != nil { 57 return nil, nil, err 58 } 59 return conn, credentials.TLSInfo{conn.ConnectionState()}, nil 60 } 61 62 // Info provides the ProtocolInfo of this TransportCredentials. 63 func (sc *serverCreds) Info() credentials.ProtocolInfo { 64 return credentials.ProtocolInfo{ 65 SecurityProtocol: "tls", 66 SecurityVersion: "1.2", 67 } 68 } 69 70 // Clone makes a copy of this TransportCredentials. 71 func (sc *serverCreds) Clone() credentials.TransportCredentials { 72 creds := NewServerTransportCredentials(sc.serverConfig) 73 return creds 74 } 75 76 // OverrideServerName overrides the server name used to verify the hostname 77 // on the returned certificates from the server. 78 func (sc *serverCreds) OverrideServerName(string) error { 79 return OverrrideHostnameNotSupportedError 80 }