IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[C# TLS V1.2] Problème SslStream fonction AuthenticateAsClient


Sujet :

C#

  1. #1
    Candidat au Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2022
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Juillet 2022
    Messages : 2
    Points : 2
    Points
    2
    Par défaut [C# TLS V1.2] Problème SslStream fonction AuthenticateAsClient
    Bonjour,

    Je développe un client qui communique avec un server en TCP TLS 1.2. Cependant, le serveur pour autoriser la connexion demande à ce que le client lui renvoie un certificat. Or pour une raison que j'ignore, le client ne renvoie pas de certificat et du coup le serveur rompt la connexion. Le message d'erreur du serveur est "tls_process_client_certificate: peer did not return a certificate"
    C'est comme si lors de l'appel à la méthode AuthenticateAsClient, on ne tenait pas compte de la collection de certificats passée en paramètre. Je ne comprend pas pourquoi.
    L'exception côté client est :
    Exception: Échec d'un appel à SSPI, consultez l'exception interne.
    Inner exception: Le message reçu était inattendu ou formaté de façon incorrecte

    Le client est développez en C# .NET Framework 4.6.1 et tourne sur Windows 10. Le serveur tourne sur du ALMA LINUX 8.5. Je n'ai pas la main sur le développement du serveur.
    Les certificats client qui m'ont été fournis sont correcte, et installé sur la machine.

    Le code client est le suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
        /// <summary>
        /// Client pour une connexion TLS
        /// </summary>
        public class ClientTLS
        {
     
            // The following method is invoked by the RemoteCertificateValidationDelegate.
            public static bool ValidateServerCertificate(
                  object sender,
                  X509Certificate certificate,
                  X509Chain chain,
                  SslPolicyErrors sslPolicyErrors)
            {
                try
                {
                    Console.WriteLine("[ValidateServerCertificate] Begin");
     
                    if (sslPolicyErrors == SslPolicyErrors.None)
                        return true;
     
                    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
     
                    return false;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ValidateServerCertificate] Exception {ex.Message}");
                    // Do not allow this client to communicate with unauthenticated servers.
                    return false;
                }
            }      
     
     
            public static void RunClient(string machineName, string serverName)
            {
                try
                {
                    using (TcpClient client = new TcpClient(machineName, 8501))
                    {
                        using (var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                        {
                            Console.WriteLine("Client connected.");
     
                            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                            store.Open(OpenFlags.ReadOnly);
     
                            sslStream.AuthenticateAsClient(serverName, store.Certificates, SslProtocols.Tls12, false);
     
                            Console.WriteLine("SSL authentication completed.");
                            Console.WriteLine("SSL using local certificate {0}.", sslStream.LocalCertificate.Subject);
                            Console.WriteLine("SSL using remote certificate {0}.", sslStream.RemoteCertificate.Subject);
     
                            var outputMessage = "Hello from the client " + Process.GetCurrentProcess().Id.ToString() + ".";
                            var outputBuffer = Encoding.UTF8.GetBytes(outputMessage);
                            sslStream.Write(outputBuffer);
                            Console.WriteLine("Sent: {0}", outputMessage);
     
                            var inputBuffer = new byte[4096];
                            var inputBytes = 0;
                            while (inputBytes == 0)
                            {
                                inputBytes = sslStream.Read(inputBuffer, 0, inputBuffer.Length);
                            }
                            var inputMessage = Encoding.UTF8.GetString(inputBuffer, 0, inputBytes);
                            Console.WriteLine("Received: {0}", inputMessage);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: {0}", e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                    }
                    Console.WriteLine("Authentication failed - closing the connection.");
                    //client.Close();
                    return;
                }
            }
     
            static string ReadMessage(SslStream sslStream)
            {
                // Read the  message sent by the server.
                // The end of the message is signaled using the
                // "<EOF>" marker.
                byte[] buffer = new byte[2048];
                StringBuilder messageData = new StringBuilder();
                int bytes = -1;
                do
                {
                    bytes = sslStream.Read(buffer, 0, buffer.Length);
     
                    // Use Decoder class to convert from bytes to UTF8
                    // in case a character spans two buffers.
                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                    decoder.GetChars(buffer, 0, bytes, chars, 0);
                    messageData.Append(chars);
                    // Check for EOF.
                    if (messageData.ToString().IndexOf("<EOF>") != -1)
                    {
                        break;
                    }
                } while (bytes != 0);
     
                return messageData.ToString();
            }
     
            private static void DisplayUsage()
            {
                Console.WriteLine("To start the client specify:");
                Console.WriteLine("clientSync machineName [serverName]");
                Environment.Exit(1);
            }
     
            public static int Main(string[] args)
            {
                string serverCertificateName = null;
                string machineName = null;
                if (args == null || args.Length < 1)
                {
                    DisplayUsage();
                }
                // User can specify the machine name and server name.
                // Server name must match the name on the server's certificate.
                machineName = args[0];
                if (args.Length < 2)
                {
                    serverCertificateName = machineName;
                }
                else
                {
                    serverCertificateName = args[1];
                }
     
                RunClient(machineName, serverCertificateName);
                return 0;
            }
     
            #endregion
        }
    Images attachées Images attachées  

  2. #2
    Candidat au Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2022
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Juillet 2022
    Messages : 2
    Points : 2
    Points
    2
    Par défaut Resolution
    Bonjour,

    J'ai résolu mon problème.
    Le soucis venait du format du certificat client qu'on m'a transmis.
    En effet, il était au format PEM avec à l'intérieur la clé privée.
    J'ai ainsi extrait le clé privée du fichier et l'ai mise dans un fichier .key
    Avec OpenSsl j'ai transformé mon certificat PEM et la clé privée en .pfx au format DER.
    La fonction n'accepte que les formats DER

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. C++ Problème de fonctions et pointeurs
    Par zmatz dans le forum C++
    Réponses: 3
    Dernier message: 01/10/2005, 16h20
  2. [MFC][WINSOCK] Problème avec fonction recv
    Par Le Farfadet dans le forum MFC
    Réponses: 4
    Dernier message: 23/09/2005, 11h00
  3. Problème de fonction
    Par Anduriel dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 26/05/2005, 20h30
  4. Problème avec fonction d'envoie de mail
    Par zyg dans le forum Réseau/Web
    Réponses: 1
    Dernier message: 23/02/2005, 08h48
  5. [Requête] Problème avec fonction "DATE_FORMAT()"
    Par sekiryou dans le forum Requêtes
    Réponses: 4
    Dernier message: 11/01/2005, 21h52

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo