Traceroute command with scapy

Traceroute is a network tool, available in Linux and Windows, that allows you to follow the route that a data packet (IP packet) will take to go from computer A to computer B.

By default, the packet is sent over the internet, but the route followed by the packet may vary, in the event of a link failure or in the case of changing the provider connections.

Once the packets have been sent to the access provider, the packet will be sent to the intermediate routers that will transport it to its destination. The packet may undergo changes during its journey. It is also possible that it never reaches its destination if the number of intermediate nodes or machines is too big and the package lifetime expires.

In the following example, we are going to study the possibilities of making a traceroute using scapy.

Using scapy, IP and UDP packets can be built in the following way:

from scapy.all import *
ip_packet = IP(dst="google.com", ttl=10)
udp_packet = UDP(dport=40000)
full_packet = IP(dst="google.com", ttl=10) / UDP(dport=40000)

To send the package, the send function is used:

send(full_packet)

IP packets include an attribute (TTL) where you indicate the lifetime of the packet. In this way, each time a device receives an IP packet, it decrements the TTL (package lifetime) by 1 and passes it to the next machine. Basically, it is a smart way to make sure that packets do not get into infinite loops.

To implement traceroute, we send a UDP packet with TTL = i for i = 1,2,3, n and check the response packet to see whether we have reached the destination and we need to continue doing jumps for each host that we reach.

You can find the following code in the traceroute_scapy.py file:

from scapy.all import *
hostname = "google.com"
for i in range(1, 28):
pkt = IP(dst=hostname, ttl=i) / UDP(dport=33434)
# Send package and wait for an answer
reply = sr1(pkt, verbose=0)
if reply is None:
# No reply
break
elif reply.type == 3:
# the destination has been reached
print "Done!", reply.src
break
else:
# We’re in the middle communication
print "%d hops away: " % i , reply.src

In the following screenshot, we can see the result of executing the traceroute script. Our target is the IP address of 216.58.210.142 and we can see the hops until we reach our target:

Also, we can see all the machines for each hop until we arrive at our target:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.37.154