SSH.NET icon indicating copy to clipboard operation
SSH.NET copied to clipboard

ForwardedPortLocal occasionally leads to CLOSE_WAIT connection

Open aberbegall opened this issue 4 years ago • 0 comments

I'm using ssh.net (previously plink) in order to establish a secure tunnel between a Linux machine running sshd and my client Windows server. The tunnel is required to redirect VNC traffic from\to a not exposed VNC server (x11vnc bound to localhost:5900) in the Linux server to\from my Windows server where a VNC client connects to the ssh.net tunnel.

I randomly end up in half-open connections in the Linux server, the connection goes into CLOSE_WAIT forever and the x11vnc stays running and I have to manually kill the x11vnc process to release the CLOSE_WAIT server connection. I would like to know how I can prevent it and get the disconnection fully acknowledged.

This is an schema of the code:

try
{
....
    var sshClient = new SshClient(sshConnectionInfo);
    sshClient.ErrorOccurred += SshError;
    sshClient.Connect();       
    port = new ForwardedPortLocal("127.0.0.1", 0, "127.0.0.1", 5900);
    port.Exception += PortException;
    sshClient.AddForwardedPort(port);
    port.Start();
    shell = sshClient.CreateShellStream(string.Empty, 0, 0, 0, 0, 0); // shell is required for other purposes
    shell.ErrorOccurred += ShellError;
....
    tcpClient = new TcpClient();
    tcpClient.Connect(port.BoundHost, (int)port.BoundPort);
    // At this point I'm able to get the stream out of the local connection to Read & Write Remote Frame Buffer                   
....                
    tcpClient.Close();
    tcpClient.Dispose();                
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
finally
{
    port.Exception -= PortException;
    sshClient.ErrorOccurred -= SshError;
    sshClient.RemoveForwardedPort(port);                
    port.Stop();
    port.Dispose();    
    shell.ErrorOccurred -= ShellError;
    shell.Close();                
    sshClient.Disconnect();
}   

Any idea how to overcome this issue? Is the order of executing port.Stop(), sshClient.Disconnect() and tcpClient.Close() important?

========================================= ssh.net version: 2020.0.2 target framework: .NET 6.0 client OS: Win Server 2019 server OS: Embedded Linux sshd version: OpenSSH 5.2p1, OpenSSL 0.97i

aberbegall avatar Jun 30 '22 11:06 aberbegall