Dmitry Smirnov
Dmitry Smirnov

Reputation: 3

Connection refused on python sockets (port is open, I can connect with nc)

So for personal reasons, I want to connect to a socket I create via telnetlib, I can connect to it from netcat but when I try from python it refuses the connection.

tn.write(b"/usr/bin/nc -l -p 3333 -e /bin/sh\n")
print("netcat listening on 3333 on target, trying to connect")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((tn.host, 3333))
s.send('ls')
print(s.recv(1024))
s.close()

If I can connect to it via netcat (by putting for example and infinite loop after tn.write())

Upvotes: 0

Views: 1447

Answers (1)

phihag
phihag

Reputation: 288220

You have a classic race condition:

The packet containing the command to start an nc is sent at only nanoseconds before the connection request (TCP SYN packet) of s.connect. It can even happen that the SYN gets to the remote host before the command to start nc.

You need to add proper synchronization. From the code you have shown, there is really no need to use two channels in the first place, so why not send the ls via the existing telnet channel to the remote host?

If you absolutely must use a second channel, try one of these options:

  • Add import time and time.sleep(5) just before calling s.connect. That way, the connection attempt will be deferred by 5 seconds. However, in general, there's no guarantee that 5 seconds is enough.
  • Send an additional command to wait for the port to be taken, as a sign that nc is ready.
  • Retry multiple times (and wait in between).

Also note that your code has three different security vulnerabilities:

  1. You are using telnetlib, which neither ensures confidentiality nor integrity of commands, output and passwords. Use ssh instead.
  2. You are connecting to port 3333 in plain, which neither ensures confidentiality nor integrity of commands and output. Use ssh instead.
  3. In between nc starting and your program connecting to it, anyone can connect to port 3333 and run arbitrary commands. Use ssh instead.

Upvotes: 1

Related Questions