So, hopefully someone noticed the glaring logic error in the port scanning utility I posted in my last post on SCAPY, now I am going to show how to fix it.
The tool shown accepted ANY reply from a tested port as a “yes, this is open”. Even an RST saying the port was closed. The reason I left it broken is fairly obvious – so I could do a followup explaining what a noob mistake it is 😉
The following snippet of code sends a SYN packet to a defined IP and port, and if it recieves a SYN-ACK packet in return, reports the port as actually open. If it recieves any other kind of packet, it reports the port is in fact closed.
#!/usr/bin/python2 | |
# SYN probes a port on an IP, tells if open/closed | |
from scapy.all import * | |
import sys | |
def synprobe(targetIP, targetPort): | |
""" Send a SYN packet, recieve reply, tell if open/closed """ | |
probe = sr1(IP(dst=targetIP)/TCP(dport= int(targetPort), flags = "S"), verbose = False, timeout = 2) | |
if probe[TCP].flags == 18: | |
print "%s:%s open" %(targetIP, targetPort) | |
else: | |
print "%s:%s closed" %(targetIP, targetPort) | |
def main(args): | |
if len(sys.argv) != 3: | |
sys.exit("usage: %s <targetip> <targetport>" %(sys.argv[0])) | |
synprobe(sys.argv[1], sys.argv[2]) | |
if __name__ == "__main__": | |
main(sys.argv) |
Modifying this code to allow for en-masse scanning is left as an exercise for the reader. I am instead going to write something about using threads next.
First though, I have to figure out how to make threading work properly without forkbombing the ever living shit out of my box!