Saturday, 11 June 2016

Inherited Handles

This week, I came across with a rather weird issue, the fact that one network port can remain open after the process that opened it has finished. I've tested this on Windows, but the basis are the same for Linux.

The problem stems from the fact that when you create a new process, it can inherit handles from the parent process, socket handles in particular. In .Net this handler inheritance seems to depend on ProcessStartInfo.UseShellExecute. If you set it to false, handles will be inherited. Let's see an example of how we can get into trouble because of this.

IPAddress localAddr = IPAddress.Parse("127.0.0.1");

   var server = new TcpListener(localAddr, 5555);
   
   // Start listening for client requests.
   server.Start();
   
   Console.WriteLine("Press enter to launch notepad");
   Console.ReadLine();
   
   Process myProcess = new Process();
            myProcess.StartInfo.FileName = "notepad.exe";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.Start();

   Console.Write("Press any key to quit . . . ");
   Console.ReadKey(true);

The above code (compiled let's say as Test.exe) starst to listen on port 5555 and launches a notepad.exe instance. If you check with ProcessExplorer you'll see that Test.exe is listening on port 5555, but notepad.exe is not. You can also see with TCPView that the only process listening on that port is Test.exe. Now comes the cool part, exit Test.exe but keep notepad open. If we try to run Test.exe again we will get this exception:

So there is a process listening on that port. Launch TCPView and you'll see this:

So a non-existent process is listening on that port, nice... If from TCPView we try to kill the process there will be no effect, and what is worst, trying to close the connection will also do nothing. So basically, unless that you know that it's notepad.exe who is keeping the port as open (or at least making the OS consider it so), you have no way to release the port and put a new instance of Test.exe to listen on it again.

No comments:

Post a Comment