Пример #1
0
    def _has_permission(self):
        """
        Return boolean value that indicates if the user running w3af has
        enough privileges to exec 'traceroute'
        """
        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        try:
            from scapy.all import traceroute
            from scapy.error import Scapy_Exception
        except socket.error:
            # [Errno 1] Operation not permitted #12131
            # https://github.com/andresriancho/w3af/issues/12131
            return False

        try:
            traceroute('127.0.0.1', maxttl=1)
        except socket.error:
            return False
        except Scapy_Exception:
            return False
        except:
            return False
            
        return True
Пример #2
0
def performScan(host):
    # ttl = 1
    # while 1:
    #     p = sr1(IP(dst=host, tt1 = ttl)/ICMP(id=os.getpid()), verbose = 0)
    #     if p[ICMP].type == 11 and p[ICMP].code == 0:
    #         print ttl, '-->',p.src
    #         ttl =+ 1
    #     elif p[ICMP].type == 0:
    #         print ttl,'-->',p.src
    #         break
    try:
        for i in range(1,28):
            pkt = IP(dst=host.strip(), ttl=i)/UDP(dport=33434)
            reply = sr1(pkt, verbose=0)
            if reply is None:
                break
            elif reply.type == 3:
                print 'Done', reply.src
            else:
                print "%d hops away: "%i, reply.src
    except Exception ,e :
        try:
            traceroute(host.strip())
        except Exception,e:
            print("An err occurred: Please check your proxy settings")
Пример #3
0
    def _has_permission(self):
        """
        Return boolean value that indicates if the user running w3af has
        enough privileges to exec 'traceroute'
        """
        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        try:
            from scapy.all import traceroute
            from scapy.error import Scapy_Exception
        except socket.error:
            # [Errno 1] Operation not permitted #12131
            # https://github.com/andresriancho/w3af/issues/12131
            return False

        try:
            traceroute('127.0.0.1', maxttl=1)
        except socket.error:
            return False
        except Scapy_Exception:
            return False
        except:
            return False

        return True
Пример #4
0
 def _has_permission(self):
     """
     Return boolean value that indicates if the user running w3af has
     enough privileges to exec 'traceroute'
     """
     try:
         traceroute('127.0.0.1', maxttl=1)
     except socket.error:
         return False
     return True
Пример #5
0
 def _has_permission(self):
     '''
     Return boolean value that indicates if the user running w3af has
     enough privileges to exec 'traceroute'
     '''
     try:
         traceroute('127.0.0.1', maxttl=1)
     except socket.error:
         return False
     return True
Пример #6
0
 def cons_graph(self):
     # def cons_graph():
     res, unans = traceroute(self.ips, dport=[80, 443], retry=-2)
     data = res.get_trace()
     graph = {}
     localIp = self.getLocalAddress()
     graph[localIp] = []
     for k in data:
         # print(k, "---", data[k])      |       == 1 or list(data[k].values())[0][1] == False
         if (len(list(data[k].keys())) == 1 and (k not in graph[localIp])):
             #print(data[k])
             graph[localIp].append(k)
         else:
             pre = localIp
             for kk in data[k]:
                 if (data[k][kk][0] not in graph.keys()) and (
                         data[k][kk][0] != list(data[k].values())[-1][0]):
                     graph[data[k][kk][0]] = []
                 # print(graph.keys())
                 # print(data[k][kk][0])
                 if (pre != data[k][kk][0]
                         and (data[k][kk][0] not in graph[pre])):
                     graph[pre].append(data[k][kk][0])
                 pre = data[k][kk][0]
     with open('topo.json', 'w') as f:
         json.dump(graph, f)
Пример #7
0
def traceroute_web_server(fqdn):
    """
    Run TCP traceroute to FQDN, using port 80.
    """

    log.info("Running TCP traceroute to port 80 of: %s" % fqdn)

    return scapy.traceroute(fqdn, dport=80, verbose=0)
Пример #8
0
def traceroute_web_server(fqdn):
    """
    Run TCP traceroute to FQDN, using port 80.
    """

    log.info("Running TCP traceroute to port 80 of: %s" % fqdn)

    return scapy.traceroute(fqdn, dport=80, verbose=0)
Пример #9
0
def show_traceroute_graph():
    res, unans = scapy.traceroute([
        'kr01.warehouse.pickby.us',
    ],
                                  maxttl=50,
                                  retry=3,
                                  dport=[
                                      80,
                                      443,
                                  ])
Пример #10
0
    def _has_permission(self):
        """
        Return boolean value that indicates if the user running w3af has
        enough privileges to exec 'traceroute'
        """
        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        from scapy.all import traceroute
        from scapy.error import Scapy_Exception

        try:
            traceroute('127.0.0.1', maxttl=1)
        except socket.error:
            return False
        except Scapy_Exception:
            return False
        except:
            return False

        return True
Пример #11
0
    def _has_permission(self):
        """
        Return boolean value that indicates if the user running w3af has
        enough privileges to exec 'traceroute'
        """
        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        from scapy.all import traceroute
        from scapy.error import Scapy_Exception

        try:
            traceroute('127.0.0.1', maxttl=1)
        except socket.error:
            return False
        except Scapy_Exception:
            return False
        except:
            return False
            
        return True
Пример #12
0
def traceroute_dns_servers(hosts, fqdn):
    """
    Run UDP traceroutes to the given DNS servers, using FQDN in DNS requests.
    """

    log.info("Running UDP traceroutes to %d servers." % len(hosts))

    addrs = [host.addr for host in hosts]
    udp_datagram = scapy.UDP(sport=scapy.RandShort())
    dns_msg = scapy.DNS(qd=scapy.DNSQR(qname=fqdn))

    return scapy.traceroute(addrs, l4=udp_datagram / dns_msg, verbose=0)
Пример #13
0
def traceroute_dns_servers(hosts, fqdn):
    """
    Run UDP traceroutes to the given DNS servers, using FQDN in DNS requests.
    """

    log.info("Running UDP traceroutes to %d servers." % len(hosts))

    addrs = [host.addr for host in hosts]
    udp_datagram = scapy.UDP(sport=scapy.RandShort())
    dns_msg = scapy.DNS(qd=scapy.DNSQR(qname=fqdn))

    return scapy.traceroute(addrs, l4=udp_datagram / dns_msg, verbose=0)
Пример #14
0
def tracehost(hostsfile,dstport,outfile):
	f = file(hostsfile,mode='rt')
	fd = f.fileno()
	m = mmap(fd, fstat(fd).st_size, MAP_PRIVATE, PROT_READ)

	dsthosts=[]
	while True:
	        line = m.readline()
        	if not line: break
        	dsthosts.extend(line.split())

	res,unans = scapy.traceroute(dsthosts,dport=int(dstport))
	res.graph(type="svg",target=">"+outfile)
Пример #15
0
def tryTrace(host, port, verbose=False):
    def getProtoObj():
        if port.proto == 'udp': return UDP(dport=port.port)
        if port.proto == 'tcp': return TCP(dport=port.port)

    rtn = None
    resp, _ = traceroute(host,
                         dport=port.port,
                         timeout=3,
                         l4=getProtoObj(),
                         verbose=False)

    if resp is None:
        rtn = PortResults(host, port, 'closed', 'None')
    else:
        rtn = PortResults(host, port, 'trace', resp.get_trace())

    return rtn
Пример #16
0
 def geo_trace(self, tracer):
     print red("[!] Using scapy's traceroute")
     time.sleep(1)
     self.tracer = tracer
     self.trace, _ = traceroute([self.tracer], verbose=0)
     self.hosts = self.trace.get_trace().values()[0]
     self.ips = [
         self.hosts[self.i][0] for self.i in range(1,
                                                   len(self.hosts) + 1)
     ]
     self.rawdata = pygeoip.GeoIP('GeoLiteCity.dat')
     self.i = 0
     self.path = []
     print yellow("Geotrace:") + red(str(self.tracer))
     while (self.i < len(self.ips)):
         self.data = self.rawdata.record_by_addr(self.ips[self.i])
         if self.data == None:
             pass
         else:
             self.longi = self.data['longitude']
             self.lat = self.data['latitude']
             self.path.append((self.lat, self.longi))
             print yellow("[X] IP") + ":" + yellow(str(
                 self.ips[self.i])) + ":" + red(
                     str(self.data['country_name']))
         self.i += 1
     self.tracemap = pygmaps.maps(self.lat, self.longi, 3)
     self.tracemap.addpath(self.path, "#FF0000")
     self.tracemap.draw('./geo_trace.html')
     while True:
         self.o_map = raw_input(
             "Try to open geo_trace.html map in browser(y/ n):\n>").lower()
         if self.o_map.startswith('y'):
             try:
                 self.new = 2
                 webbrowser.open("geo_trace.html", new=self.new)
                 break
             except:
                 print '[!]Could not open map in web browser. Open "geo_trace.html" -file manually'
             break
         elif self.o_map.startswith('n'):
             break
Пример #17
0
def main():
    host = sys.argv[1]

    print("-"*50)
    print("Tracing %s" % host)
    print("-"*50)

    r1, unans = traceroute(host, maxttl=20, verbose=0)
    hops = list(r1.get_trace().values())[0]

    params = "size=1000x1000&scale=2&maptype=terrain"
    markers = ""
    paths = "&path=weight:5%%7Ccolor:0x0000ff"

    for k in hops.keys():
        print("%d -> %s (%s)" % (k, get_geolocation_for_ip(hops[k][0]), hops[k][0]))
        m, p = make_google_marker(k, hops[k][0], True)
        markers += m
        paths += p

    print("-"*50)
    print("Click the link below to see the trace:")
    print("%s%s%s%s&key=%s" % (GOOGLE_START_URL, params, markers, paths, GOOGLE_API_KEY))
Пример #18
0
    def discover(self, fuzzable_request):
        """
        Discovery task. Uses scapy.traceroute function in order to determine
        the distance between http and https ports for the target.
        Intended to be executed once during the infrastructure process.
        """
        if not self._has_permission():
            om.out.error(PERM_ERROR_MSG)
            return

        def set_info(name, desc):
            i = Info(name, desc, 1, self.get_name())
            kb.kb.append(self, 'http_vs_https_dist', i)

        target_url = fuzzable_request.get_url()
        domain = target_url.get_domain()
        http_port = self._http_port
        https_port = self._https_port

        # Use target port if specified
        netloc = target_url.get_net_location()
        try:
            port = int(netloc.split(':')[-1])
        except ValueError:
            pass  # Nothing to do.
        else:
            protocol = target_url.get_protocol()
            if protocol == 'https':
                https_port = port
            else:  # it has to be 'http'
                http_port = port

        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        from scapy.all import traceroute

        try:
            # pylint: disable=E1124
            # First try with httpS
            https_troute = traceroute(domain, dport=https_port)[0].get_trace()
            # Then with http
            http_troute = traceroute(domain, dport=http_port)[0].get_trace()
            # pylint: enable=E1124
        except:
            # I've seen numerous bug reports with the following exception:
            # "error: illegal IP address string passed to inet_aton"
            # that come from this part of the code. It seems that in some cases
            # the domain resolves to an IPv6 address and scapy does NOT
            # support that protocol.
            return

        # This destination was probably 'localhost' or a host reached
        # through a vpn?
        if not (https_troute and http_troute):
            return

        https_ip_tuples = https_troute.values()[0].values()
        last_https_ip = https_ip_tuples[-1]
        http_ip_tuples = http_troute.values()[0].values()
        last_http_ip = http_ip_tuples[-1]

        # Last IP should be True; otherwise the dest wasn't reached
        # Tuples have the next form: ('192.168.1.1', False)
        if not (last_https_ip[1] and last_http_ip[1]):
            desc = _('The port \'%s\' is not open on target %s')
            if not last_https_ip[1]:
                om.out.error(desc % (https_port, domain))
            if not last_http_ip[1]:
                om.out.error(desc % (http_port, domain))
        else:
            trace_str = lambda iptuples: '\n'.join('    %s %s' %
                                                  (t[0], t[1][0]) for t in enumerate(iptuples))

            if http_ip_tuples != https_ip_tuples:
                header = '  TCP trace to %s:%s\n%s'

                trc1 = header % (domain, http_port, trace_str(http_ip_tuples))
                trc2 = header % (
                    domain, https_port, trace_str(https_ip_tuples))

                desc = 'Routes to target "%s" using ports %s and ' \
                       '%s are different:\n%s\n%s'
                desc = desc % (domain, http_port, https_port, trc1, trc2)
                set_info('HTTP and HTTPs hop distance', desc)
                om.out.information(desc)
            else:
                desc = 'The routes to the target\'s HTTP and HTTPS ports are' \
                       ' the same:\n%s' % trace_str(http_ip_tuples)
                set_info('HTTP traceroute', desc)
Пример #19
0
# -*- coding: utf-8 -*-

import os, sys, time, subprocess
from scapy.as_resolvers import AS_resolver_radb
from scapy.all import traceroute
domains = 'www.baidu.com'
target = domains.split(' ')
dport = [80]
if len(target) >= 1 and target[0] != '':
    # 启动路由跟踪
    res, unans = traceroute(domains, dport=dport, retry=-2)
    # traceroute生成的信息绘制成svg
    #res.graph(target="> graph.svg", ASres=AS_resolver_radb(), type="svg") # ASres=AS_resolver_radb()改变为可用的whois提供商,而非原来的ASres=None后默认的被qiang了的提供商
    time.sleep(1)
    # svg 转格式为 png
    #subprocess.Popen("/usr/local/bin/convert test.svg test.png", shell=True)
else:
    print("IP/domain number of errors, exit")
Пример #20
0
def tracehost(host, dstport, outfile):
    res, unans = scapy.traceroute(host, dport=int(dstport))
    res.graph(type="svg", target=">" + outfile)
Пример #21
0
#!/usr/bin/evn python
#-*-coding:utf-8 -*-
import time
import logging, warnings
import subprocess

from scapy.all import traceroute
warnings.filterwarnings("ignore", category=DeprecationWarning)
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
domains = raw_input('Please input domains or IPs: ')

try:
    domain = domains.split(' ')
    res, unans = traceroute(domain, dport=[80, 443], retry=-2)
    res.graph(target=">test.svg")
    time.sleep(1)
    subprocess.Popen("/usr/bin/convert test.svg test.png", shell=True)
except:
    print "you shoud run by root or domain error"
Пример #22
0
#!/usr/local/bin/ipython
#coding: utf-8
import os,sys,time,subprocess
import warnings,logging
warnings.filterwarnings("ignore", category=DeprecationWarning)  #屏蔽scapy无用告警信息
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)      #屏蔽模块IPV6多余警告
from scapy.all import traceroute
domains = raw_input('Please input one or more IP/domain:')      #输入ip或域名
target = domains.split(' ')
dport = [80]                                                    #扫描的端口列表

if len(target) >= 1 and target[0]!='':
    res,unans = traceroute(target,dport=dport,retry=-2)         #启动路由跟踪
    res.graph(target="> test.svg")                              #生成svg矢量图形
    time.sleep(1)
    subprocess.Popen("/usr/bin/convert test.svg test.png", shell=True) #svg转png
else:
    print "IP/domain number of errors,exit"
Пример #23
0
class http_vs_https_dist(InfrastructurePlugin):
    """
    Determines the network distance between the http and https ports for a target

    :author: Javier Andalia <jandalia =at= gmail.com>
    """
    def __init__(self):
        InfrastructurePlugin.__init__(self)

        self._http_port = 80
        self._https_port = 443

    @runonce(exc_class=RunOnce)
    def discover(self, fuzzable_request):
        """
        Discovery task. Uses scapy.traceroute function in order to determine
        the distance between http and https ports for the target.
        Intended to be executed once during the infrastructure process.
        """
        if not self._has_permission():
            om.out.error(PERM_ERROR_MSG)
            return

        def set_info(name, desc):
            i = Info(name, desc, 1, self.get_name())
            kb.kb.append(self, 'http_vs_https_dist', i)

        target_url = fuzzable_request.get_url()
        domain = target_url.get_domain()
        http_port = self._http_port
        https_port = self._https_port

        # Use target port if specified
        netloc = target_url.get_net_location()
        try:
            port = int(netloc.split(':')[-1])
        except ValueError:
            pass  # Nothing to do.
        else:
            protocol = target_url.get_protocol()
            if protocol == 'https':
                https_port = port
            else:  # it has to be 'http'
                http_port = port

        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        try:
            from scapy.all import traceroute
        except ImportError, ie:
            om.out.debug('There was an error importing scapy.all: "%s"' % ie)
            return

        try:
            # pylint: disable=E1124,E1136

            # First try with httpS
            https_troute = traceroute(domain, dport=https_port)[0].get_trace()
            # Then with http
            http_troute = traceroute(domain, dport=http_port)[0].get_trace()

            # pylint: enable=E1124,E1136
        except Exception, e:
            # I've seen numerous bug reports with the following exception:
            # "error: illegal IP address string passed to inet_aton"
            # that come from this part of the code. It seems that in some cases
            # the domain resolves to an IPv6 address and scapy does NOT
            # support that protocol.
            om.out.debug(
                'There was an error running scapy\'s traceroute: "%s"' % e)
            return
Пример #24
0
#!/usr/bin/env python
# encoding=utf-8

import os, sys, time, subprocess
import warnings, logging

logging.getLogger("scrapy.runtime").setLevel(logging.ERROR)

from scapy.all import traceroute

host = 'www.ligewei.com'
dport = 80

res, n = traceroute(host, dport, retry=-2)
res.graph(target='> res.svg')

time.sleep(1)

print '=====OK====='
Пример #25
0
# #!/usr/bin/python3.6
# # -*- coding=utf-8 -*-
# # 学习专用
# # ======程序说明======
# #
# #
# # ==================
import os
import sys
import time
import subprocess
import warnings
import logging
warnings.filterwarnings("ignore", category=DeprecationWarning)
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import traceroute

res, unans = traceroute(["baidu.com"])
res.graph(target="test.svg")
print("ok!")

# if __name__ == "__main__":
Пример #26
0
def traceroute(host, port):
	ans, unans = scapy.traceroute(host, maxttl=TRACEROUTE_MAX, dport=port,
				      verbose=0)
	for snd,rcv in sorted(ans, key=lambda exchange: exchange[0].ttl):
		if isinstance(rcv.payload, scapy.TCP): return snd.ttl
	return None
Пример #27
0
class http_vs_https_dist(InfrastructurePlugin):
    """
    Determines the network distance between the http and https ports for a target

    :author: Javier Andalia <jandalia =at= gmail.com>
    """

    def __init__(self):
        InfrastructurePlugin.__init__(self)

        self._http_port = 80
        self._https_port = 443

    @runonce(exc_class=RunOnce)
    def discover(self, fuzzable_request, debugging_id):
        """
        Discovery task. Uses scapy.traceroute function in order to determine
        the distance between http and https ports for the target.
        Intended to be executed once during the infrastructure process.

        :param debugging_id: A unique identifier for this call to discover()
        :param fuzzable_request: A fuzzable_request instance that contains
                                    (among other things) the URL to test.
        """
        if not self._has_permission():
            om.out.error(PERM_ERROR_MSG)
            return

        def set_info(name, desc):
            i = Info(name, desc, 1, self.get_name())
            kb.kb.append(self, 'http_vs_https_dist', i)

        target_url = fuzzable_request.get_url()
        domain = target_url.get_domain()
        http_port = self._http_port
        https_port = self._https_port

        # Use target port if specified
        netloc = target_url.get_net_location()
        try:
            port = int(netloc.split(':')[-1])
        except ValueError:
            pass  # Nothing to do.
        else:
            protocol = target_url.get_protocol()
            if protocol == 'https':
                https_port = port
            else:  # it has to be 'http'
                http_port = port

        # Import things from scapy when I need them in order to reduce memory
        # usage (which is specially big in scapy module, just when importing)
        try:
            from scapy.all import traceroute
        except ImportError, ie:
            om.out.debug('There was an error importing scapy.all: "%s"' % ie)
            return

        try:
            # pylint: disable=E1124,E1136

            # First try with httpS
            https_troute = traceroute(domain, dport=https_port)[0].get_trace()
            # Then with http
            http_troute = traceroute(domain, dport=http_port)[0].get_trace()

            # pylint: enable=E1124,E1136
        except Exception as e:
            # I've seen numerous bug reports with the following exception:
            # "error: illegal IP address string passed to inet_aton"
            # that come from this part of the code. It seems that in some cases
            # the domain resolves to an IPv6 address and scapy does NOT
            # support that protocol.
            om.out.debug('There was an error running scapy\'s traceroute: "%s"' % e)
            return

        # This destination was probably 'localhost' or a host reached
        # through a vpn?
        if not (https_troute and http_troute):
            return

        https_ip_tuples = https_troute.values()[0].values()
        last_https_ip = https_ip_tuples[-1]
        http_ip_tuples = http_troute.values()[0].values()
        last_http_ip = http_ip_tuples[-1]

        # Last IP should be True; otherwise the dest wasn't reached
        # Tuples have the next form: ('192.168.1.1', False)
        if not (last_https_ip[1] and last_http_ip[1]):
            desc = _('The port \'%s\' is not open on target %s')
            if not last_https_ip[1]:
                om.out.error(desc % (https_port, domain))
            if not last_http_ip[1]:
                om.out.error(desc % (http_port, domain))
        else:
            trace_str = lambda iptuples: '\n'.join('    %s %s' %
                                                  (t[0], t[1][0]) for t in enumerate(iptuples))

            if http_ip_tuples != https_ip_tuples:
                header = '  TCP trace to %s:%s\n%s'

                trc1 = header % (domain, http_port, trace_str(http_ip_tuples))
                trc2 = header % (
                    domain, https_port, trace_str(https_ip_tuples))

                desc = 'Routes to target "%s" using ports %s and ' \
                       '%s are different:\n%s\n%s'
                desc %= (domain, http_port, https_port, trc1, trc2)
                set_info('HTTP and HTTPs hop distance', desc)
                om.out.information(desc)
            else:
                desc = 'The routes to the target\'s HTTP and HTTPS ports are' \
                       ' the same:\n%s' % trace_str(http_ip_tuples)
                set_info('HTTP traceroute', desc)
Пример #28
0
#!/usr/bin/env python3
from scapy.all import traceroute
import subprocess
domains = input("Please input one or more IP/domain:")
target = domains.split(' ')
dport = [80]
if len(target) >= 1 and target[0] != '':
    res, unans = traceroute(target, dport=dport)
    res.graph(target=">test.svg")  #生成svg矢量图形
    time.sleep(1)
    subprocess.Popen('/usr/bin/convert test.svg test.png',
                     shell=True)  #svg转png格式
    print("路由追踪完成")
else:
    print("域名异常!")
Пример #29
0
    def discover(self, fuzzableRequest):
        '''
        Discovery task. Uses scapy.traceroute function in order to determine
        the distance between http and https ports for the target.
        Intended to be executed once during the discovery process.
        '''
        if not self._has_permission():
            raise w3afException(PERM_ERROR_MSG) 
        
        def set_info(name, desc):
            inf = info.info()
            inf.setPluginName(self.getName())
            inf.setName(name)
            inf.setDesc(desc)
            kb.kb.append(self, 'http_vs_https_dist', inf)

        target_url = fuzzableRequest.getURL()
        domain = target_url.getDomain()
        http_port = self._http_port
        https_port = self._https_port

        # Use target port if specified
        netloc = target_url.getNetLocation()
        try:
            port = int(netloc.split(':')[-1])
        except ValueError:
            pass # Nothing to do.
        else:
            protocol = target_url.getProtocol()
            if protocol == 'https':
                https_port = port
            else: # it has to be 'http'
                http_port = port

        # First try with httpS
        https_troute = traceroute(domain, dport=https_port)[0].get_trace()
        # Then with http
        http_troute = traceroute(domain, dport=http_port)[0].get_trace()
        
        # This destination was probably 'localhost' or a host reached
        # through a vpn?
        if not (https_troute and http_troute):
            return []
        
        https_ip_tuples = https_troute.values()[0].values()
        last_https_ip = https_ip_tuples[-1]
        http_ip_tuples = http_troute.values()[0].values()
        last_http_ip = http_ip_tuples[-1]
        
        # Last IP should be True; otherwise the dest wasn't reached
        # Tuples have the next form: ('192.168.1.1', False)
        if not (last_https_ip[1] and last_http_ip[1]):
            desc = _('The port \'%s\' is not open on target %s')
            if not last_https_ip[1]:
                om.out.error(desc % (https_port, domain))
            if not last_http_ip[1]:
                om.out.error(desc % (http_port, domain))
        else:
            # Are routes different
            if http_ip_tuples != https_ip_tuples:
                header = '  TCP trace to %s:%s\n%s'
                trace_str = lambda iptuples: '\n'.join('    %s %s' % \
                                (t[0], t[1][0]) for t in enumerate(iptuples))

                trc1 = header % (domain, http_port, trace_str(http_ip_tuples))
                trc2 = header % (domain, https_port, trace_str(https_ip_tuples))

                desc = 'Routes to target \'%s\' using ports \'%s\' and ' \
                '\'%s\' are different:\n%s\n%s' % (domain, http_port, 
                                                    https_port, trc1, trc2)
                set_info('HTTP vs. HTTPS Distance', desc)
                om.out.information(desc)
        return []
Пример #30
0
@author: admin
'''
'''
scapy一个强大的交互式数据所处理程序,能对数据进行伪造或解包,包括发送数据包,包嗅探,应答和反馈等
可以用来处理网络扫描,路由跟踪,服务探测,单元测试等

本实践是通过traceroute()方法实现路由的跟踪,跟踪动态结果动态生成图形格式
'''
# -*- coding: utf-8 -*-

import os, sys, time, subprocess
import warnings, logging

from pip._vendor.distlib.compat import raw_input

from scapy.all import traceroute

warnings.filterwarnings("ignore", category=DeprecationWarning)
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
domains = raw_input('Please input one or more IP/domain: ')
target = domains.split(' ')
dport = [80]
if len(target) >= 1 and target[0] != '':
    res, unans = traceroute(target, dport=dport, retry=-2)
    res.graph(target="> test.svg")
    time.sleep(1)
    subprocess.Popen("/usr/bin/convert test.svg test.png", shell=True)
else:
    print("IP/domain number of errors,exit")
# Scapy是一个可以让用户发送、侦听和解析并伪装网络报文的Python程序。这些功能可以用于制作侦测、扫描和攻击网络的工具。
# Scapy 是一个强大的操纵报文的交互程序。它可以伪造或者解析多种协议的报文,还具有发送、捕获、匹配请求和响应这些报文以及更多的功能。
# Scapy 可以轻松地做到像扫描(scanning)、路由跟踪(tracerouting)、探测(probing)、单元测试(unit tests)、攻击(attacks)和
# 发现网络(network discorvery)这样的传统任务。它可以代替hping,arpspoof,arp-sk,arping,p0f 甚至是部分的Namp,tcpdump和tshark 的功能。
# scapy模块需要tcpdump程序支持,生成报表需要graphviz、ImageMagick图像包支持

from scapy.all import traceroute
import os
import sys
import time
import subprocess
import warnings
import logging

warnings.filterwarnings("ignore", category=DeprecationWarning)  # 屏蔽scapy无用告警信息
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)  # 屏蔽模块IPV6多余告警

domains = input('Please input one or more Ip/Domain:')

target = domains.split(' ')
dport = [80]  # 扫描的端口列表

if len(target) >= 1 and target[0] != "":
    res, unns = traceroute(target, dport=dport, retry=-2)  # 启动路由跟踪
    res.graph(target="> test.svg")  # 生成svg矢量图
    time.sleep(1)
    subprocess.Popen("/usr/bin/convert test.svg test.png",
                     shell=True)  # svg转png格式
else:
    print("IP/domain number of errors, exit")
Пример #32
0
    def discover(self, fuzzable_request):
        """
        Discovery task. Uses scapy.traceroute function in order to determine
        the distance between http and https ports for the target.
        Intended to be executed once during the infrastructure process.
        """
        if not self._has_permission():
            om.out.error(PERM_ERROR_MSG)
            return

        def set_info(name, desc):
            i = Info(name, desc, 1, self.get_name())
            kb.kb.append(self, 'http_vs_https_dist', i)

        target_url = fuzzable_request.get_url()
        domain = target_url.get_domain()
        http_port = self._http_port
        https_port = self._https_port

        # Use target port if specified
        netloc = target_url.get_net_location()
        try:
            port = int(netloc.split(':')[-1])
        except ValueError:
            pass  # Nothing to do.
        else:
            protocol = target_url.get_protocol()
            if protocol == 'https':
                https_port = port
            else:  # it has to be 'http'
                http_port = port

        try:
            # First try with httpS
            https_troute = traceroute(domain, dport=https_port)[0].get_trace()
            # Then with http
            http_troute = traceroute(domain, dport=http_port)[0].get_trace()
        except:
            #   I've seen numerous bug reports with the following exception:
            #   "error: illegal IP address string passed to inet_aton"
            #   that come from this part of the code. It seems that in some cases
            #   the domain resolves to an IPv6 address and scapy does NOT
            #   support that protocol.
            return []

        # This destination was probably 'localhost' or a host reached
        # through a vpn?
        if not (https_troute and http_troute):
            return []

        https_ip_tuples = https_troute.values()[0].values()
        last_https_ip = https_ip_tuples[-1]
        http_ip_tuples = http_troute.values()[0].values()
        last_http_ip = http_ip_tuples[-1]

        # Last IP should be True; otherwise the dest wasn't reached
        # Tuples have the next form: ('192.168.1.1', False)
        if not (last_https_ip[1] and last_http_ip[1]):
            desc = _('The port \'%s\' is not open on target %s')
            if not last_https_ip[1]:
                om.out.error(desc % (https_port, domain))
            if not last_http_ip[1]:
                om.out.error(desc % (http_port, domain))
        else:
            trace_str = lambda iptuples: '\n'.join(
                '    %s %s' % (t[0], t[1][0]) for t in enumerate(iptuples))

            if http_ip_tuples != https_ip_tuples:
                header = '  TCP trace to %s:%s\n%s'

                trc1 = header % (domain, http_port, trace_str(http_ip_tuples))
                trc2 = header % (domain, https_port,
                                 trace_str(https_ip_tuples))

                desc = 'Routes to target "%s" using ports %s and ' \
                       '%s are different:\n%s\n%s'
                desc = desc % (domain, http_port, https_port, trc1, trc2)
                set_info('HTTP and HTTPs hop distance', desc)
                om.out.information(desc)
            else:
                desc = 'The routes to the target\'s HTTP and HTTPS ports are' \
                       ' the same:\n%s' % trace_str(http_ip_tuples)
                set_info('HTTP traceroute', desc)
Пример #33
0
#!./venv/bin/python 
import sys, json, socket
from scapy.all import traceroute, conf

lookups = dict((hostname, socket.gethostbyname(hostname)) for hostname in sys.argv[1:])
ips = filter(None, set(lookups.values())) # distinct, remove false

conf.verb = 0
res, unans = traceroute(ips, maxttl=30)

print json.dumps(dict(lookups=lookups, trace=res.get_trace()))