SSL Socket Server -> Private Key

  • VB.NET

Es gibt 1 Antwort in diesem Thema. Der letzte Beitrag () ist von tScheckSn.

    SSL Socket Server -> Private Key

    Hallo,

    Ich bin mittlerweile am verzweifeln. Ich versuche einen SSL Socket Server zum laufen zu bringen, scheitere aber am Zertifikat. Fehlermeldung: "Servermodus-SSL muss ein Zertifikat mit dem verknüpften privaten Schlüssel verwenden.".
    Mein Zertifikatsfile enthält aber zu 100% einen Privten schlüssel.
    Habt ihr einen Tipp für mich was das sein könnte?

    Server:

    VB.NET-Quellcode

    1. Imports System.Collections
    2. Imports System.Net
    3. Imports System.Net.Sockets
    4. Imports System.Net.Security
    5. Imports System.Security.Authentication
    6. Imports System.Text
    7. Imports System.Security.Cryptography.X509Certificates
    8. Imports System.IO
    9. Imports System.Threading
    10. Public NotInheritable Class SignServerSSL
    11. Private Shared serverCertificate As New X509Certificate
    12. ' The certificate parameter specifies the name of the file
    13. ' containing the machine certificate.
    14. Private Shared Sub initCertificate()
    15. ' serverCertificate = New X509Certificate(GlobalSettings.CertFile, "fidus")
    16. serverCertificate.Import(GlobalSettings.CertFile, "geheim", X509KeyStorageFlags.MachineKeySet)
    17. End Sub
    18. Public Shared Sub ListenForClients()
    19. initCertificate()
    20. ' Create a TCP/IP (IPv4) socket and listen for incoming connections.
    21. 'Dim ip As System.Net.IPAddress = New IPAddress("192.168.1.1")
    22. Dim ipAddress As System.Net.IPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList(0)
    23. 'Dim ipAddress As System.Net.IPAddress = IPAddress.Any
    24. Dim Port As Integer = 8080
    25. Dim listener As New TcpListener(ipAddress, Port)
    26. log.entry("Starting Server on " & ipAddress.ToString & ":" & Port)
    27. listener.Start()
    28. While True
    29. log.entry("Waiting for a client to connect...")
    30. ' Application blocks while waiting for an incoming connection.
    31. ' Type CNTL-C to terminate the server.
    32. Dim client As TcpClient = listener.AcceptTcpClient()
    33. log.entry("StartListener")
    34. Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf ProcessClient))
    35. clientThread.Start(client)
    36. End While
    37. End Sub
    38. Private Shared Sub ProcessClient(client As TcpClient)
    39. log.entry("Incoming Client ...")
    40. ' A client has connected. Create the
    41. ' SslStream using the client's network stream.
    42. Dim sslStream As New SslStream(client.GetStream(), False)
    43. ' Authenticate the server but don't require the client to authenticate.
    44. Try
    45. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    46. 'Hier wird die Exception geworfen: Servermodus-SSL muss ein Zertifikat mit dem verknüpften privaten Schlüssel verwenden."}
    47. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    48. sslStream.AuthenticateAsServer(serverCertificate, False, SslProtocols.Tls, True) '<--- ?(
    49. ' Display the properties and settings for the authenticated stream.
    50. DisplaySecurityLevel(sslStream)
    51. DisplaySecurityServices(sslStream)
    52. DisplayCertificateInformation(sslStream)
    53. DisplayStreamProperties(sslStream)
    54. ' Set timeouts for the read and write to 5 seconds.
    55. sslStream.ReadTimeout = 5000
    56. sslStream.WriteTimeout = 5000
    57. ' Read a message from the client.
    58. log.entry("Waiting for client message...")
    59. Dim messageData As String = ReadMessage(sslStream)
    60. log.entry("Received: " & messageData & "")
    61. ' Write a message to the client.
    62. Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the server.<EOF>")
    63. log.entry("Sending hello message.")
    64. sslStream.Write(message)
    65. Catch e As AuthenticationException
    66. log.entry("Exception: " & e.Message & "")
    67. If e.InnerException IsNot Nothing Then
    68. log.entry("Inner exception: " & e.InnerException.Message & "")
    69. End If
    70. log.entry("Authentication failed - closing the connection.")
    71. sslStream.Close()
    72. client.Close()
    73. Return
    74. Finally
    75. ' The client stream will be closed with the sslStream
    76. ' because we specified this behavior when creating
    77. ' the sslStream.
    78. sslStream.Close()
    79. client.Close()
    80. End Try
    81. End Sub
    82. Private Shared Function ReadMessage(sslStream As SslStream) As String
    83. Try
    84. log.entry("Start reading Message")
    85. ' Read the message sent by the client.
    86. ' The client signals the end of the message using the
    87. ' "<EOF>" marker.
    88. Dim buffer As Byte() = New Byte(2047) {}
    89. Dim messageData As New StringBuilder()
    90. Dim bytes As Integer = -1
    91. Do
    92. ' Read the client's test message.
    93. bytes = sslStream.Read(buffer, 0, buffer.Length)
    94. ' Use Decoder class to convert from bytes to UTF8
    95. ' in case a character spans two buffers.
    96. Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
    97. Dim chars As Char() = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
    98. decoder.GetChars(buffer, 0, bytes, chars, 0)
    99. messageData.Append(chars)
    100. ' Check for EOF or an empty message.
    101. If messageData.ToString().IndexOf("<EOF>") <> -1 Then
    102. Exit Do
    103. End If
    104. Loop While bytes <> 0
    105. Return messageData.ToString()
    106. Catch ex As Exception
    107. log.entry(ex)
    108. Return "<KEINE DATEN EMPFANGEN>"
    109. End Try
    110. End Function
    111. Private Shared Sub DisplaySecurityLevel(stream As SslStream)
    112. log.entry("Cipher: " & stream.CipherAlgorithm & " strength " & stream.CipherStrength)
    113. log.entry("Hash: " & stream.HashAlgorithm & " strength " & stream.HashStrength & "")
    114. log.entry("Key exchange: " & stream.KeyExchangeAlgorithm & " strength " & stream.KeyExchangeStrength & "")
    115. log.entry("Protocol: " & stream.SslProtocol & "")
    116. End Sub
    117. Private Shared Sub DisplaySecurityServices(stream As SslStream)
    118. log.entry("Is authenticated: " & stream.IsAuthenticated & " as server? " & stream.IsServer & "")
    119. log.entry("IsSigned: " & stream.IsSigned & "")
    120. log.entry("Is Encrypted: " & stream.IsEncrypted & "")
    121. End Sub
    122. Private Shared Sub DisplayStreamProperties(stream As SslStream)
    123. log.entry("Can read: " & stream.CanRead & ", write " & stream.CanWrite & "")
    124. log.entry("Can timeout: " & stream.CanTimeout & "")
    125. End Sub
    126. Private Shared Sub DisplayCertificateInformation(stream As SslStream)
    127. log.entry("Certificate revocation list checked: " & stream.CheckCertRevocationStatus & "")
    128. Dim localCertificate As X509Certificate = stream.LocalCertificate
    129. If stream.LocalCertificate IsNot Nothing Then
    130. log.entry("Local cert was issued to " & localCertificate.Subject & " and is valid from " & localCertificate.GetEffectiveDateString() & " until " & localCertificate.GetExpirationDateString() & ".")
    131. Else
    132. log.entry("Local certificate is null.")
    133. End If
    134. ' Display the properties of the client's certificate.
    135. Dim remoteCertificate As X509Certificate = stream.RemoteCertificate
    136. If stream.RemoteCertificate IsNot Nothing Then
    137. log.entry("Remote cert was issued to " & remoteCertificate.Subject & " and is valid from " & remoteCertificate.GetEffectiveDateString() & " until " & remoteCertificate.GetExpirationDateString() & ".")
    138. Else
    139. log.entry("Remote certificate is null.")
    140. End If
    141. End Sub
    142. Private Shared Sub DisplayUsage()
    143. log.entry("To start the server specify:")
    144. log.entry("serverSync certificateFile.cer")
    145. Environment.[Exit](1)
    146. End Sub
    147. End Class


    Aufruf im Windows Form zum testen:

    VB.NET-Quellcode

    1. Private Sub frmSignServer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2. Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf RunServer))
    3. clientThread.Start()
    4. Init()
    5. End Sub
    6. Private Sub RunServer()
    7. SignServerSSL.ListenForClients()
    8. End Sub


    Client:

    VB.NET-Quellcode

    1. Imports System.Collections
    2. Imports System.Net
    3. Imports System.Net.Security
    4. Imports System.Net.Sockets
    5. Imports System.Security.Authentication
    6. Imports System.Text
    7. Imports System.Security.Cryptography.X509Certificates
    8. Imports System.IO
    9. Public Class ATSignClient
    10. Private client As TcpClient
    11. Private sslStream As SslStream
    12. Private certificateErrors As New Hashtable()
    13. ' The following method is invoked by the RemoteCertificateValidationDelegate.
    14. Public Function ValidateServerCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors__1 As SslPolicyErrors) As Boolean
    15. ' Return True
    16. If sslPolicyErrors__1 = SslPolicyErrors.None Then
    17. Return True
    18. End If
    19. If sslPolicyErrors__1 = SslPolicyErrors.RemoteCertificateNameMismatch Then
    20. MsgBox("Der Servername stimmt mit dem angegebenen Zertifikat nicht überein: " & sslPolicyErrors__1)
    21. Return True
    22. End If
    23. MsgBox("Certificate error: " & sslPolicyErrors__1.ToString)
    24. ' Do not allow this client to communicate with unauthenticated servers.
    25. Return False
    26. End Function
    27. Public Function Connect(machineName As String, serverName As String)
    28. ' Create a TCP/IP client socket.
    29. ' machineName is the host running the server application.
    30. client = New TcpClient(machineName, 8080)
    31. ' Create an SSL stream that will close the client's stream.
    32. sslStream = New SslStream(client.GetStream(), False, New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), Nothing)
    33. ' The server name must match the name on the server certificate.
    34. ' MsgBox("Stream erstellt")
    35. Try
    36. sslStream.AuthenticateAsClient(serverName)
    37. ' MsgBox("Authentifiziert!")
    38. Catch e As AuthenticationException
    39. Dim msg As String = ""
    40. msg &= "Exception: " & e.Message
    41. If e.InnerException IsNot Nothing Then
    42. msg &= "Inner exception: " & e.InnerException.Message
    43. End If
    44. msg &= "Authentication failed - closing the connection."
    45. client.Close()
    46. Return msg
    47. End Try
    48. ' MsgBox("Warten")
    49. ' Encode a test message into a byte array.
    50. ' Signal the end of the message using the "<EOF>".
    51. 'SendMessage("test123")
    52. Dim messsage As Byte() = Encoding.UTF8.GetBytes("Test123456789123456789123456789getInfo")
    53. ' Send hello message to the server.
    54. sslStream.Write(messsage)
    55. sslStream.Flush()
    56. ' Read message from the server.
    57. Dim serverMessage As String = ReadMessage(sslStream)
    58. ' Send hello message to the server.
    59. sslStream.Write(Encoding.UTF8.GetBytes("Zweiter versuch etwas zu senden"))
    60. sslStream.Flush()
    61. Return serverMessage
    62. ' Close the client connection.
    63. '
    64. End Function
    65. Public Function isConnected()
    66. If IsNothing(client) Then Return False
    67. Return client.Connected
    68. End Function
    69. Public Function SendMessage(ByRef p_msg As String)
    70. If Not client.Connected Then
    71. Return "not connected"
    72. End If
    73. Dim messsage As Byte() = Encoding.UTF8.GetBytes(p_msg)
    74. ' Send hello message to the server.
    75. sslStream.Write(messsage)
    76. sslStream.Flush()
    77. ' Read message from the server.
    78. Dim serverMessage As String = ReadMessage(sslStream)
    79. sslStream.Flush()
    80. Return serverMessage
    81. End Function
    82. Public Sub disconnect()
    83. client.Close()
    84. End Sub
    85. Private Function ReadMessage(sslStream As SslStream) As String
    86. ' Read the message sent by the server.
    87. ' The end of the message is signaled using the
    88. ' "<EOF>" marker.
    89. Dim buffer As Byte() = New Byte(2047) {}
    90. Dim messageData As New StringBuilder()
    91. Dim bytes As Integer = -1
    92. Do
    93. bytes = sslStream.Read(buffer, 0, buffer.Length)
    94. ' Use Decoder class to convert from bytes to UTF8
    95. ' in case a character spans two buffers.
    96. Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
    97. Dim chars As Char() = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
    98. decoder.GetChars(buffer, 0, bytes, chars, 0)
    99. messageData.Append(chars)
    100. ' Check for EOF.
    101. If messageData.ToString().IndexOf("<EOF>") <> -1 Then
    102. Exit Do
    103. End If
    104. Loop While bytes <> 0
    105. Return messageData.ToString()
    106. End Function
    107. End Class


    Ich bin euch dankbar für jede Hilfe!
    lg