Поддержка SSL / TSL для grpc в c # - PullRequest
0 голосов
/ 20 сентября 2018

Я пытался реализовать gRPC с использованием SSL / TLS, я прочитал документацию о том, как реализовать SSL / TLS, но это не работает, я нашел страницу stackoverflow Поддержка TLS для GRPC в C # о том, как реализовать поддержку TLS, но опять же это не работает.

Я работаю с C #, но у меня есть реализация Java, и я попытался подключить службу C # с клиентом Java и работает, ноКогда я пытаюсь подключить клиент C # к серверу C #, он не работает, даже если я пытался подключить клиент C # к серверу Java, и он не работает.

Я использую greet protos и Visualstudio 2015

в соответствии с документацией этот код должен работать

Сначала я попытался использовать это для клиента:

     SslCredentials secureChanel = new SslCredentials(File.ReadAllText("ssl/ca.crt"));
     Channel channel = new Channel("localhost", 50051, secureChanel);

, затем я изменил код для этого:

        var rootCert = File.ReadAllText("ssl/ca.crt");
        var keyCertPair = new KeyCertificatePair(
            File.ReadAllText("ssl/server.crt"),
            File.ReadAllText("ssl/server.pem"));

        var clientCredentials = new SslCredentials(rootCert, keyCertPair);

        var options = new List<ChannelOption>
        {
            new ChannelOption(ChannelOptions.SslTargetNameOverride, "DESKTOP-3HLH093")
        };

        Channel channel = new Channel("localhost", 50051, clientCredentials, options);

У кого-то есть идея или она может помочь мне узнать, что не так?или что мне нужно сделать, чтобы узнать, как решить?

может быть примером

это мой код клиента:

using System;
using Grpc.Core;
using System.IO;
using Greet;
using System.Collections.Generic;

namespace Nuxiba.Sever.Test.pruebaGrpcClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Test Server with gRPC");

            var rootCert = File.ReadAllText("ssl/ca.crt");
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText("ssl/server.crt"),
                File.ReadAllText("ssl/server.pem"));

            var clientCredentials = new SslCredentials(rootCert, keyCertPair);


            var options = new List<ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, "DESKTOP-3HLH093")
            };

            Channel channel = new Channel("localhost", 50051, clientCredentials, options);

            greet_test(channel);


            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        public static void greet_test(Channel channel)
        {
            var greetCliente = new GreetService.GreetServiceClient(channel);

            Greeting greeting = new Greeting();
            greeting.FirstName = "John";
            greeting.LastName = "XXXX";

            Console.WriteLine(greeting);

            GreetRequest callIR = new GreetRequest();
            callIR.Greeting= greeting;

            GreetResponse callResponse = greetCliente.Greet(callIR);   //, new CallOptions().WithWaitForReady(true));
            Console.WriteLine("respuesta: " + callResponse.Result);
        }


    }
}

это мой код сервера:

using System;
using Grpc.Core;
using System.IO;
using System.Collections.Generic;
using Greet;

namespace Nuxiba.Sever.Test.pruebaGrpcServer
{
    class Program
    {
    static void Main(string[] args)
    {
        Console.WriteLine("Test Server with gRPC");


        //ssl
        List<KeyCertificatePair> certificados = new List<KeyCertificatePair>();
        certificados.Add(new KeyCertificatePair(File.ReadAllText("ssl/server.crt"), File.ReadAllText("ssl/server.pem")));
        ServerCredentials servCred = new SslServerCredentials(certificados);

        Server server = new Server
        {
            //Services = { TarificadorService.BindService(new TarificadorServiceImpl()) },
            Services = { GreetService.BindService(new GreetServicesImpl()) },
            Ports = { new ServerPort("localhost", 50051, servCred) }
        };


        server.Start();

        Console.WriteLine("Greeter server listening on port: 50051 ");
        Console.WriteLine("Press any key to stop the server...");
        Console.ReadKey();

        server.ShutdownAsync().Wait();

    }
    }
}

Это мой импл-код:

using System.Threading.Tasks;
using Grpc.Core;

namespace Nuxiba.Sever.Test.pruebaGrpcServer
{
    class TarificadorServiceImpl : TarificadorService.TarificadorServiceBase
    {
    public override Task<CallInfoResponse> CallInfo(CallInfoRequest request, ServerCallContext context)
    {
        CallingInfo ci = request.CallingInfo;
        uint Cal_id = ci.Callid;

        CallInfoResponse response = new CallInfoResponse();
        response.RegsAmount = Cal_id;

        return Task.FromResult(response);
        //return Task.FromResult(new CallInfoResponse { RegsAmount = Cal_id });
    }



    }
}

ошибка приложения "отказ в соединении"

это полный журнал:

D0924 14:26:24.375269 Grpc.Core.Internal.UnmanagedLibrary Attempting to load native library "X:\desarrollos\pruebaGrpc\pruebaGrpcClient\bin\Debug\grpc_csharp_ext.x86.dll"
D0924 14:26:24.554956 Grpc.Core.Internal.NativeExtension gRPC native library loaded successfully.
D0924 14:26:24.634740 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\resolver\dns\native\dns_resolver.cc:348: Using native dns resolver
{ "firstName": "Armando", "lastName": "Rodriguez" }
I0924 14:26:25.100637 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\surface\call.cc:642: OP[client-channel:05DBD400]:  SEND_INITIAL_METADATA{key=3a 70 61 74 68 ':path' value=2f 67 72 65 65 74 2e 47 72 65 65 74 53 65 72 76 69 63 65 2f 47 72 65 65 74 '/greet.GreetService/Greet'} SEND_MESSAGE:flags=0x00000000:len=22 SEND_TRAILING_METADATA{} RECV_INITIAL_METADATA RECV_MESSAGE RECV_TRAILING_METADATA
D0924 14:26:25.101644 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\resolver\dns\native\dns_resolver.cc:289: Start resolving.
E0924 14:26:25.340996 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\tsi\ssl_transport_security.cc:1229: Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
D0924 14:26:25.340996 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc:129: Security handshake failed: {"created":"@1537817185.341000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
I0924 14:26:25.342000 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:668: Connect failed: {"created":"@1537817185.341000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
E0924 14:26:25.407816 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\tsi\ssl_transport_security.cc:1229: Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
D0924 14:26:25.407816 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc:129: Security handshake failed: {"created":"@1537817185.408000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
I0924 14:26:25.408815 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:668: Connect failed: {"created":"@1537817185.408000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
I0924 14:26:25.408815 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:492: Subchannel 013E3B50: Retry in 767 milliseconds
D0924 14:26:25.409810 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\resolver\dns\native\dns_resolver.cc:265: In cooldown from last resolution (from 307 ms ago). Will resolve again in 693 ms
D0924 14:26:25.409810 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\resolver\dns\native\dns_resolver.cc:289: Start resolving.
I0924 14:26:25.423798 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\surface\call.cc:642: OP[client-channel:05DBD400]:  CANCEL:{"created":"@1537817185.424000000","description":"Failed to create subchannel","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\client_channel.cc","file_line":2636,"referenced_errors":[{"created":"@1537817185.410000000","description":"Pick Cancelled","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\lb_policy\pick_first\pick_first.cc","file_line":241,"referenced_errors":[{"created":"@1537817185.408000000","description":"Connect Failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc","file_line":663,"grpc_status":14,"referenced_errors":[{"created":"@1537817185.408000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}]}]}]}
I0924 14:26:25.426771 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\surface\call.cc:642: OP[client-channel:05DBD400]:  CANCEL:{"created":"@1537817185.424000000","description":"Failed to create subchannel","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\client_channel.cc","file_line":2636,"referenced_errors":[{"created":"@1537817185.410000000","description":"Pick Cancelled","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\lb_policy\pick_first\pick_first.cc","file_line":241,"referenced_errors":[{"created":"@1537817185.408000000","description":"Connect Failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc","file_line":663,"grpc_status":14,"referenced_errors":[{"created":"@1537817185.408000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}]}]}]}
I0924 14:26:28.737748 98788968 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:452: Failed to connect to channel, retrying
E0924 14:26:29.479174 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\tsi\ssl_transport_security.cc:1229: Handshake failed with fatal error SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED.
D0924 14:26:29.480172 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc:129: Security handshake failed: {"created":"@1537817189.480000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
I0924 14:26:29.481170 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:668: Connect failed: {"created":"@1537817189.480000000","description":"Handshake failed","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\lib\security\transport\security_handshaker.cc","file_line":248,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}
I0924 14:26:29.482166 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:490: Subchannel 05DC3678: Retry immediately
I0924 14:26:29.482166 0 T:\src\github\grpc\workspace_csharp_ext_windows_x86\src\core\ext\filters\client_channel\subchannel.cc:452: Failed to connect to channel, retrying

1 Ответ

0 голосов
/ 26 сентября 2018

Я нашел решение, согласно реестру, проблема была в том, что когда клиент пытался проверить сертификат, я нашел эту ссылку о похожей проблеме, и она дала мне представление о том, как решить мою проблему https://groups.google.com/forum/#!topic/grpc-io/pJnoc_MHkfc

наконец, это код клиента:

        SslCredentials secureChanel = new SslCredentials(File.ReadAllText("ssl/server.crt"));
        Channel channel = new Channel("localhost", 50051, secureChanel);

и это код сервера:

        List<KeyCertificatePair> certificados = new List<KeyCertificatePair>();
        certificados.Add(new KeyCertificatePair(File.ReadAllText("ssl/server.crt"), File.ReadAllText("ssl/server.pem")));
        ServerCredentials servCred = new SslServerCredentials(certificados);
        //ServerCredentials servCred = new SslServerCredentials(certificados, File.ReadAllText("ssl/ca.crt"),true);

        Server server = new Server
        {
            //Services = { TarificadorService.BindService(new TarificadorServiceImpl()) },
            Services = { GreetService.BindService(new GreetServicesImpl()) },
            Ports = { new ServerPort("localhost", 50051, servCred) }
        };
...