sshnet / sshnet/SSH.NET

SftpClient Thread leak when authentication fails

Open
#687 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
4.4k
Forks
993
Avg merge
9d 21h
Merged PRs (30d)
1

Description

Using 2016.1.0

As the title says, when attempting to call Connect(), if the connection succeeds but the authentication fails, a leak happens. This can be negated by wrapping the connection in a Try/Catch and calling Disconnect if the call throws.

Here's a simple loop producing the effect (remove the Disconnect to see the increase in thread count) :

class Program
{
    static void Main(string[] args)
    {
        var testCount = 10;
        var clientInstance = new SftpClient("127.0.0.1", 22, "username", "invalidpassword");
        var process = Process.GetCurrentProcess();

        var threadCountBefore = process.Threads.Count;

        for (var i = 0; i < testCount; i++)
        {
            try
            {
                clientInstance.Connect();
            }
            catch
            {
                // Without this, there is a thread leak
                clientInstance.Disconnect();
            }
        }

        process.Refresh();
        var threadCountAfter = process.Threads.Count;
    }
}

After some research, I believe it is linked to the message listener thread in Session.cs. After starting it, if the key exchange fails, the code will gracefully exit by calling Disconnect() first. Otherwise, it goes on to authentication but allows the exceptions to break the flow and exit immediately, without calling Disconnect().

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in Session.cs and reproduce the issue with the provided Connect() loop using invalid credentials. Trace the authentication-failure path after the message listener thread starts, comparing it with the key-exchange failure path. Done means repeated failed authentication attempts no longer leak threads without requiring an explicit Disconnect().

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
networking
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.