EldoS | Feel safer!

Software components for data protection, secure storage and transfer

X11 Forwarding

Also by EldoS: BizCrypto
Components for BizTalk® and SQL Server® Integration Services that let you securely store and transfer information in your business automation solutions.
#11438
Posted: 10/23/2009 11:10:18
by Sergio Perelli (Basic support level)
Joined: 10/23/2009
Posts: 2

I'm trying to create a VB program to connect to our linux server using TElX11ForwardSSHTunnel, starting from SophisticatedSSHClient example.

I changed the example as described hereafter:

1) I used Private SSHTunnel As TElX11ForwardSSHTunnel instead of Private SSHTunnel As TElShellSSHTunnel
2) I have added in the init() method the following lines:
SSHTunnel = New TElX11ForwardSSHTunnel
SSHTunnel.AuthenticationProtocol = System.Text.Encoding.UTF8.GetBytes("'MIT-MAGIC-COOKIE-1'")
SSHTunnel.Environment.Add("my_magick_number=`mcookie`")
SSHTunnel.ScreenNumber = 0

But when I try to execute the program, I receive an error after the connection to the server, the error is (see figure):

Exception : Indice oltre i limiti della matrice. (translation Index exceeds matrix limits)
Stack trace : in SBSSHClient.TElSSHClient.SSH2SendChannelRequestX11(UInt32 Channel, Byte[] AuthProto, Int32 ScreenNumber)
in SBSSHClient.TElSSHClient.SSH2ParseServerChannelSuccess(Byte[] Buffer, Int32 Size)
in SBSSHClient.TElSSHClient.SSH2ParseOnConnectionLayer(Byte[] Buffer, Int32 Size)
in SBSSHClient.TElSSHClient.SSH2ParseOnTransportLayer(Byte[] Buffer, Int32 Size)
in SBSSHClient.TElSSHClient.AnalyseBuffer()
in SBSSHClient.TElSSHClient.DataAvailable()
in SSHDemo.frmMain.clientSocket_OnReceive(IAsyncResult ar)

I supposed that the problem was the ClientSocketReceiveBuf buffer, I'm tried to grow the size, but in this case the program hangs.

What's' wrong? Taking into account that the X11 connection work fine using any SSH client program (in particular we use Putty and as X-emulator X-Win32).
I'm very frustrated, we want to buy your package but we want to solve the problem before.

Code
Source code:

Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports SBSSHClient
Imports SBSSHCommon
Imports SBSSHConstants
Imports SBSSHKeyStorage
Imports SBUtils

Public Class frmMain
    Inherits System.Windows.Forms.Form

    Private ClientSocket As Socket
    Private SSHClient As TElSSHClient
    
' Start Changed code
    'Comment Private SSHTunnel As TElShellSSHTunnel
    Private SSHTunnel As TElX11ForwardSSHTunnel
    Private SSHTunnelList As TElSSHTunnelList
' End Changed code
    
    Private SSHTunnelConnection As TElSSHTunnelConnection
    Private boolConnected As Boolean
    Private KeyStorage As TElSSHMemoryKeyStorage
    Private ClientSocketReceiveBuf(8192) As Byte
    Private ClientSocketReceiveLen As Integer

    ' The main entry point for the application.
    <STAThread()> _
    Shared Sub Main()
        SBUtils.Unit.SetLicenseKey(SBUtils.Unit.BytesOfString("7576...C51E") )
        Application.Run(New frmMain)
    End Sub

    Private Sub Init()
        SSHClient = New TElSSHClient
        AddHandler SSHClient.OnSend, AddressOf sshClient_OnSend
        AddHandler SSHClient.OnReceive, AddressOf sshClient_OnReceive
        AddHandler SSHClient.OnOpenConnection, AddressOf sshClient_OnOpenConnection
        AddHandler SSHClient.OnCloseConnection, AddressOf sshClient_OnCloseConnection
        AddHandler SSHClient.OnDebugData, AddressOf sshClient_OnDebugData
        AddHandler SSHClient.OnError, AddressOf sshClient_OnError
        AddHandler SSHClient.OnAuthenticationSuccess, AddressOf sshClient_OnAuthenticationSuccess
        AddHandler SSHClient.OnAuthenticationFailed, AddressOf sshClient_OnAuthenticationFailed
        AddHandler SSHClient.OnKeyValidate, AddressOf sshClient_OnKeyValidate
        AddHandler SSHClient.OnAuthenticationKeyboard, AddressOf sshClient_OnAuthenticationKeyboard

' Start Changed code
        ' Comment SSHTunnel = New TElShellSSHTunnel
        SSHTunnel = New TElX11ForwardSSHTunnel
        SSHTunnel.AuthenticationProtocol = System.Text.Encoding.UTF8.GetBytes("'MIT-MAGIC-COOKIE-1'")
        SSHTunnel.Environment.Add("my_magick_number=`mcookie`")
        SSHTunnel.ScreenNumber = 0
' End Changed code

        AddHandler SSHTunnel.OnOpen, AddressOf sshTunnel_OnOpen
        AddHandler SSHTunnel.OnClose, AddressOf sshTunnel_OnClose
        AddHandler SSHTunnel.OnError, AddressOf sshTunnel_OnError

        SSHTunnelList = New TElSSHTunnelList
        SSHTunnel.TunnelList = SSHTunnelList
        SSHClient.TunnelList = SSHTunnelList




        KeyStorage = New TElSSHMemoryKeyStorage
        SSHClient.KeyStorage = KeyStorage
    End Sub

    Delegate Sub SetControlTextCallback(ByVal Ctrl As Control, ByVal Text As String)
    Private Sub SetControlText(ByVal Ctrl As Control, ByVal Text As String)
        If Ctrl.InvokeRequired Then
            Dim d As New SetControlTextCallback(AddressOf SetControlText)
            Me.Invoke(d, New Object() {Ctrl, Text})
        Else
            Ctrl.Text = Text
        End If
    End Sub

    Delegate Sub AppendTextCallback(ByVal tb As TextBox, ByVal Text As String)
    Private Sub AppendText(ByVal tb As TextBox, ByVal Text As String)
        If tb.InvokeRequired Then
            Dim d As New AppendTextCallback(AddressOf AppendText)
            Me.Invoke(d, New Object() {tb, Text})
        Else
            tb.AppendText(Text)
        End If
    End Sub

    Private Sub cmdConnect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
        If Not boolConnected Then
            txtLog.Clear()
            Try
                SSHTunnelConnection = Nothing
                SSHClient.Versions = 0
                If chkSSH1.Checked Then
                    SSHClient.Versions = SSHClient.Versions Or CShort(SBSSHCommon.Unit.sbSSH1)
                End If
                If chkSSH2.Checked Then
                    SSHClient.Versions = SSHClient.Versions Or CShort(SBSSHCommon.Unit.sbSSH2)
                End If
                SSHClient.UserName = txtUserName.Text
                SSHClient.Password = txtPassword.Text
                KeyStorage.Clear()
                Dim key As New TElSSHKey
                Dim privateKeyAdded As Boolean = False
                If txtPrivateKey.TextLength > 0 Then
                    Dim pwd As String
                    pwd = ""
                    If PromptForm.Prompt("Enter password for private key:", False, pwd) Then
                        Dim err As Integer
                        err = key.LoadPrivateKey(txtPrivateKey.Text, pwd)
                        If err = 0 Then
                            KeyStorage.Add(key)
                            SSHClient.AuthenticationTypes = SSHClient.AuthenticationTypes Or SBSSHConstants.Unit.SSH_AUTH_TYPE_PUBLICKEY
                            privateKeyAdded = True
                        Else
                            Log("Private key file could not be loaded due to error " + err.ToString)
                        End If
                    End If
                End If

                If Not privateKeyAdded Then
                    SSHClient.AuthenticationTypes = SSHClient.AuthenticationTypes And Not SBSSHConstants.Unit.SSH_AUTH_TYPE_PUBLICKEY
                End If
                Dim hostadd As IPAddress = Dns.Resolve(txtHost.Text).AddressList(0)
                Dim epHost As New IPEndPoint(hostadd, Convert.ToInt32(txtPort.Text, 10))
                ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                ClientSocket.BeginConnect(epHost, New AsyncCallback(AddressOf clientSocket_OnOpenConnection), Nothing)

                cmdConnect.Text = "Disconnect"
            Catch ex As Exception

                ShowErrorMessage(ex)
                Reset()
            End Try
        Else
            Reset()
        End If

    End Sub

    Private Sub Reset()
        If Not boolConnected Then
            Return
        End If
        boolConnected = False

        SetControlText(cmdConnect, "Connect")

        If SSHClient.Active Then
            SSHClient.Close(False)
        End If
        If Not (ClientSocket Is Nothing) Then
            Try
                ClientSocket.Close()
            Catch
            Finally
                ClientSocket = Nothing
            End Try
        End If
        txtTerm.Clear()
        Log("Connection closed")
    End Sub


    Private Sub cmdSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSend.Click
        Try
            If Not (SSHTunnelConnection Is Nothing) Then
                Dim s As String = txtSend.Text + vbCr + vbTab
                Dim buf As Byte() = Encoding.ASCII.GetBytes(s)
                SSHTunnelConnection.SendData(buf)
                txtSend.Clear()
            End If
        Catch ex As Exception
            ShowErrorMessage(ex)
        End Try
    End Sub


    Private Sub cmdOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOpen.Click
        If openFileDialog1.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            txtPrivateKey.Text = openFileDialog1.FileName
        End If
    End Sub

    Private Sub ShowErrorMessage(ByVal ex As Exception)
        Dim str As String = ""
        If boolConnected Then
            Console.WriteLine(ex.StackTrace)
            If ex.InnerException IsNot Nothing Then
                If Not String.IsNullOrEmpty(ex.InnerException.Message) Then
                    If Not String.IsNullOrEmpty(ex.StackTrace) Then
                        str = "Exception      : " & ex.Message & vbNewLine & "Inner exception: " & ex.InnerException.Message & vbNewLine & "Stack trace    : " & ex.StackTrace
                        MessageBox.Show(str, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

                    Else
                        str = "Exception      : " & ex.Message & vbNewLine & "Inner exception: " & ex.InnerException.Message
                        MessageBox.Show(str, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End If
                Else
                    str = "Exception      : " & ex.Message
                    MessageBox.Show(str, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            Else
                If Not String.IsNullOrEmpty(ex.StackTrace) Then
                    str = "Exception      : " & ex.Message & vbNewLine & "Stack trace    : " & ex.StackTrace
                    MessageBox.Show(str, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
                Else
                    str = "Exception      : " & ex.Message
                    MessageBox.Show(str, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If
            Dim fp As IO.StreamWriter = New IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "SSHDEMOERROR.txt")
            fp.Write(str)
            fp.Close()
            fp.Dispose()
        End If
    End Sub


    Private Sub Log(ByVal s As String)
        AppendText(txtLog, s + vbCr + vbLf)
    End Sub

#Region "SSHClient Callbacks"

    Private Sub sshClient_OnSend(ByVal Sender As Object, ByVal Buffer() As Byte)
        Try
            ClientSocket.BeginSend(Buffer, 0, Buffer.Length, 0, New AsyncCallback(AddressOf clientSocket_OnSend), Nothing)
        Catch ex As Exception
            ShowErrorMessage(ex)
            Reset()
        End Try
    End Sub


    Private Sub sshClient_OnReceive(ByVal Sender As Object, ByRef Buffer() As Byte, ByVal MaxSize As Integer, ByRef Written As Integer)
        Written = Math.Min(MaxSize, ClientSocketReceiveLen)
        If Written > 0 Then
            Array.Copy(ClientSocketReceiveBuf, 0, Buffer, 0, Written)
            Array.Copy(ClientSocketReceiveBuf, Written, ClientSocketReceiveBuf, 0, ClientSocketReceiveLen - Written)
            ClientSocketReceiveLen = ClientSocketReceiveLen - Written
        End If
    End Sub


    Private Sub sshClient_OnOpenConnection(ByVal Sender As Object)
        Log("Connection started")
        Log(("Server: " + SSHClient.ServerSoftwareName))
        If (SSHClient.Version And SBSSHCommon.Unit.sbSSH1) > 0 Then
            Log("Version: SSHv1")
        End If
        If (SSHClient.Version And SBSSHCommon.Unit.sbSSH2) > 0 Then
            Log("Version: SSHv2")
        End If
        Log("PublicKey algorithm: " + SSHClient.PublicKeyAlgorithm.ToString)
        Log("Kex algorithm: " + SSHClient.KexAlgorithm.ToString)
        Log("Block algorithm: " + SSHClient.EncryptionAlgorithmServerToClient.ToString)
        Log("Compression algorithm: " + SSHClient.CompressionAlgorithmServerToClient.ToString)
        Log("MAC algorithm: " + SSHClient.MacAlgorithmServerToClient.ToString)

        boolConnected = True
    End Sub


    Private Sub sshClient_OnCloseConnection(ByVal Sender As Object)
        Log("SSH connection closed")
        Reset()
    End Sub


    Private Sub sshClient_OnDebugData(ByVal Sender As Object, ByVal Buffer() As Byte)
        Log(("[Debug data] " + Encoding.Default.GetString(Buffer)))
    End Sub


    Private Sub sshClient_OnError(ByVal Sender As Object, ByVal ErrorCode As Integer)
        Log(("Error " + Convert.ToString(ErrorCode, 10)))
        Log("If you have ensured that all connection parameters are correct and you still can't connect,")
        Log("please contact EldoS support as described on http://www.eldos.com/sbb/support.php")
        Log("Remember to provide details about the error that happened.")
        If SSHClient.ServerSoftwareName.Length > 0 Then
            Log("Server software identified itself as: " + SSHClient.ServerSoftwareName)
        End If
    End Sub


    Private Sub sshClient_OnAuthenticationSuccess(ByVal Sender As Object)
        Log("Authentication succeeded")
    End Sub


    Private Sub sshClient_OnAuthenticationFailed(ByVal Sender As Object, ByVal AuthenticationType As Integer)
        Log(("Authentication failed for type " + Convert.ToString(AuthenticationType, 10)))
    End Sub

    Delegate Sub AuthKeyboardHandler(ByVal Sender As Object, ByVal Prompts As SBStringList.TElStringList, ByVal Echo() As Boolean, ByVal Responses As SBStringList.TElStringList)
    Private Sub sshClient_OnAuthenticationKeyboard(ByVal Sender As Object, ByVal Prompts As SBStringList.TElStringList, ByVal Echo() As Boolean, ByVal Responses As SBStringList.TElStringList)
        If Me.InvokeRequired Then
            Dim d As AuthKeyboardHandler = CType(AddressOf sshClient_OnAuthenticationKeyboard, AuthKeyboardHandler)
            Me.Invoke(d, New Object() {Sender, Prompts, Echo, Responses})
        Else
            Responses.Clear()
            Dim i As Integer = 0
            For i = 0 To Prompts.Count - 1
                Dim Response As String = ""
                If PromptForm.Prompt(Prompts(i), Echo(i), Response) Then
                    Responses.Add(Response)
                Else
                    Responses.Add("")
                End If
            Next
        End If
    End Sub

    Private Sub sshClient_OnKeyValidate(ByVal Sender As Object, ByVal ServerKey As SBSSHKeyStorage.TElSSHKey, ByRef Validate As Boolean)
        Dim AlgLine As String
        If (ServerKey.Algorithm() = SBSSHKeyStorage.Unit.ALGORITHM_RSA) Then
            AlgLine = "RSA"
        Else
            If (ServerKey.Algorithm() = SBSSHKeyStorage.Unit.ALGORITHM_DSS) Then
                AlgLine = "DSA"
            Else
                AlgLine = "unknown"
            End If
        End If
        Log("Server key received (" + AlgLine + "). Fingerprint is " + SBUtils.Unit.BeautifyBinaryString((SBUtils.Unit.DigestToStr128(ServerKey.FingerprintMD5, True)), ":"c))
        Validate = True
    End Sub

#End Region

#Region "SSHTunnel Callbacks"

    Private Sub sshTunnel_OnOpen(ByVal Sender As Object, ByVal TunnelConnection As TElSSHTunnelConnection)
        SSHTunnelConnection = TunnelConnection
        AddHandler SSHTunnelConnection.OnData, AddressOf sshTunnelConnection_OnData
        AddHandler SSHTunnelConnection.OnError, AddressOf sshTunnelConnection_OnError
        AddHandler SSHTunnelConnection.OnClose, AddressOf sshTunnelConnection_OnClose
    End Sub


    Private Sub sshTunnel_OnClose(ByVal Sender As Object, ByVal TunnelConnection As TElSSHTunnelConnection)
    End Sub


    Private Sub sshTunnel_OnError(ByVal Sender As Object, ByVal ErrorCode As Integer, ByVal Data As Object)
        Log("Tunnel error: " + ErrorCode.ToString)
    End Sub

#End Region

#Region "SSHTunnelConnection Callbacks"

    Private Sub sshTunnelConnection_OnData(ByVal Sender As Object, ByVal Buffer() As Byte)
        Dim s As String = Encoding.ASCII.GetString(Buffer)
        AppendText(txtTerm, s)
    End Sub


    Private Sub sshTunnelConnection_OnError(ByVal Sender As Object, ByVal ErrorCode As Integer)
        Log(("Connection error: " + ErrorCode.ToString))
    End Sub


    Private Sub sshTunnelConnection_OnClose(ByVal Sender As Object, ByVal CloseType As SBSSHCommon.TSSHCloseType)
        Log("Shell connection closed")
    End Sub

#End Region

#Region "ClientSocket Callbacks"

    Private Sub clientSocket_OnOpenConnection(ByVal ar As IAsyncResult)
        Try
            ClientSocket.EndConnect(ar)
            ClientSocket.BeginReceive(ClientSocketReceiveBuf, 0, ClientSocketReceiveBuf.Length, 0, New AsyncCallback(AddressOf clientSocket_OnReceive), Nothing)
            SSHClient.Open()
            Log("Client socket connected")
        Catch ex As Exception
            ShowErrorMessage(ex)
            Reset()
        End Try
    End Sub


    Private Sub clientSocket_OnReceive(ByVal ar As IAsyncResult)
        Try
            ClientSocketReceiveLen = ClientSocket.EndReceive(ar)
            If ClientSocketReceiveLen = 0 Then
                Throw New Exception("Connection lost")
            End If
            While ClientSocketReceiveLen > 0
                SSHClient.DataAvailable()
            End While
            ClientSocket.BeginReceive(ClientSocketReceiveBuf, 0, ClientSocketReceiveBuf.Length, 0, New AsyncCallback(AddressOf clientSocket_OnReceive), Nothing)
        Catch ex As Exception
            ShowErrorMessage(ex)
            Reset()
        End Try
    End Sub


    Private Sub clientSocket_OnSend(ByVal ar As IAsyncResult)
        Try
            ClientSocket.EndSend(ar)
        Catch ex As Exception
            ShowErrorMessage(ex)
            Reset()
        End Try
    End Sub

#End Region

  
End Class
#11460
Posted: 10/26/2009 02:33:51
by Ken Ivanov (EldoS Corp.)

Thank you for reporting the issue.

We were able to reproduce the problem. The corresponding fix will go to the future build update, which is expected later today.
#11488
Posted: 10/27/2009 08:49:57
by Sergio Perelli (Basic support level)
Joined: 10/23/2009
Posts: 2

First of all thank you for your quick feedback.
Today I have installed the new beta release [Version 7.2.165 (28791 Kb) . Released on 10/26/2009.] downloaded from https://www.eldos.com/files/sbb7/pr/secbboxnet.zip address. The behaviour of my program is changed, with the new version no error is generated using TElX11ForwardSSHTunnel, but still not a connection is opened using this class.
it works fine if I use the TElShellSSHTunnel class, indeed an SSHTunnel.OnOpen event is generated and the tunnel connection is established.
Using the TElX11ForwardSSHTunnel class, the SSHTunnel.OnOpen event is not generated and the connection it is not established .

I don't know if the my code is correct.

I appreciate if you can help me.
Thanks in advance
Sergio
#11511
Posted: 10/29/2009 13:09:19
by Eugene Mayevski (EldoS Corp.)

Moved to HelpDesk -- Innokentiy will be available on Saturday and he will look into the issue.


Sincerely yours
Eugene Mayevski

Reply

Statistics

Topic viewed 2427 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!