Esempio n. 1
0
def overview():
    """
        Creates a overview of the hosts per range.
    """
    range_search = RangeSearch()
    ranges = range_search.get_ranges()
    if ranges:
        formatted_ranges = []
        tags_lookup = {}
        for r in ranges:
            formatted_ranges.append({'mask': r.range})
            tags_lookup[r.range] = r.tags
        search = Host.search()
        search = search.filter('term', status='up')
        search.aggs.bucket('hosts',
                           'ip_range',
                           field='address',
                           ranges=formatted_ranges)
        response = search.execute()
        print_line("{0:<18} {1:<6} {2}".format("Range", "Count", "Tags"))
        print_line("-" * 60)
        for entry in response.aggregations.hosts.buckets:
            print_line("{0:<18} {1:<6} {2}".format(entry.key, entry.doc_count,
                                                   tags_lookup[entry.key]))
    else:
        print_error("No ranges defined.")
Esempio n. 2
0
def main():
    rs = RangeSearch()
    arg = argparse.ArgumentParser(parents=[rs.argparser],
                                  conflict_handler='resolve')
    arg.add_argument('-c',
                     '--count',
                     help="Only show the number of results",
                     action="store_true")
    arg.add_argument('-a',
                     '--add',
                     help="Add a new range",
                     action="store_true")
    arguments = arg.parse_args()
    if arguments.add:
        print_notification("Adding new range")
        range_str = input("What range do you want to add? ")
        r = rs.id_to_object(range_str)
        print_success("Added a new range:")
        print_json(r.to_dict(include_meta=True))
    elif arguments.count:
        print_line("Number of ranges: {}".format(rs.argument_count()))
    else:
        response = rs.get_ranges()
        for hit in response:
            print_json(hit.to_dict(include_meta=True))
Esempio n. 3
0
 def __init__(self,
              netmask='255.255.255.0',
              include_public=False,
              own_ip=None):
     self.ip_list = set()
     self.ip_ranges = set()
     self.rs = RangeSearch()
     self.hs = HostSearch()
     self.netmask = netmask
     self.include_public = include_public
     if own_ip:
         self.ip_list.add(own_ip)
Esempio n. 4
0
def nmap_discover():
    """
        This function retrieves ranges from jackal
        Uses two functions of nmap to find hosts:
            ping:   icmp / arp pinging of targets
            lookup: reverse dns lookup
    """
    rs = RangeSearch()
    rs_parser = rs.argparser
    arg = argparse.ArgumentParser(parents=[rs_parser],
                                  conflict_handler='resolve')
    arg.add_argument('type', metavar='type', \
        help='The type of nmap scan to do, choose from ping or lookup', \
        type=str, choices=['ping', 'lookup'])
    arguments, nmap_args = arg.parse_known_args()

    tag = None
    if arguments.type == 'ping':
        tag = 'nmap_ping'
        nmap_args.append('-sn')
        nmap_args.append('-n')
        check_function = include_up_hosts
    elif arguments.type == 'lookup':
        tag = 'nmap_lookup'
        nmap_args.append('-sL')
        check_function = include_hostnames

    ranges = rs.get_ranges(tags=['!{}'.format(tag)])
    ranges = [r for r in ranges]
    ips = []
    for r in ranges:
        ips.append(r.range)

    print_notification("Running nmap with args: {} on {} range(s)".format(
        nmap_args, len(ips)))
    result = nmap(nmap_args, ips)
    stats = import_nmap(result, tag, check_function)
    stats['scanned_ranges'] = len(ips)

    Logger().log(
        'nmap_discover', "Nmap discover with args: {} on {} range(s)".format(
            nmap_args, len(ips)), stats)

    for r in ranges:
        r.add_tag(tag)
        r.save()
Esempio n. 5
0
def main():
    ranges = RangeSearch()
    arguments = ranges.argparser.parse_args()
    if arguments.tags or ranges.is_pipe:
        ranges = ranges.get_ranges()
    else:
        ranges = ranges.search(tags=['!netdiscover'])

    results = 0
    for r in ranges:
        discover = NetDiscover(r)
        results += discover.execute()
        discover.save()

    Logger().log('netdiscover',
                 "Netdiscover on {} ranges".format(len(ranges)),
                 stats={
                     'scanned_ranges': len(ranges),
                     'hosts': results
                 })
Esempio n. 6
0
def parse_ips(ips, netmask, include_public):
    """
        Parses the list of ips, turns these into ranges based on the netmask given.
        Set include_public to True to include public IP adresses.
    """
    hs = HostSearch()
    rs = RangeSearch()
    ranges = []
    ips = list(set(ips))
    included_ips = []
    print_success("Found {} ips".format(len(ips)))
    for ip in ips:
        ip_address = ipaddress.ip_address(ip)
        if include_public or ip_address.is_private:
            # To stop the screen filling with ranges.
            if len(ips) < 15:
                print_success("Found ip: {}".format(ip))
            host = hs.id_to_object(ip)
            host.add_tag('dns_discover')
            host.save()
            r = str(ipaddress.IPv4Network("{}/{}".format(ip, netmask), strict=False))
            ranges.append(r)
            included_ips.append(ip)
        else:
            print_notification("Excluding ip {}".format(ip))

    ranges = list(set(ranges))
    print_success("Found {} ranges".format(len(ranges)))
    for rng in ranges:
        # To stop the screen filling with ranges.
        if len(ranges) < 15:
            print_success("Found range: {}".format(rng))
        r = rs.id_to_object(rng)
        r.add_tag('dns_discover')
        r.save()

    stats = {}
    stats['ips'] = included_ips
    stats['ranges'] = ranges
    return stats
Esempio n. 7
0
class Sniffer(object):
    """
        Sniffer class
    """
    def __init__(self,
                 netmask='255.255.255.0',
                 include_public=False,
                 own_ip=None):
        self.ip_list = set()
        self.ip_ranges = set()
        self.rs = RangeSearch()
        self.hs = HostSearch()
        self.netmask = netmask
        self.include_public = include_public
        if own_ip:
            self.ip_list.add(own_ip)

    def callback(self, pkt):
        """
            Callback for the scapy sniffer
        """
        if ARP in pkt:
            self.parse_ip(pkt.sprintf("%ARP.psrc%"))
        if TCP in pkt or UDP in pkt:
            self.parse_ip(pkt.sprintf("%IP.src%"))
            self.parse_ip(pkt.sprintf("%IP.dst%"))

    def parse_ip(self, ip):
        """
            Parses an ip to extract the range.
            Calls new_ip and new_range when a new ip is found.
            Excludes ranges that are multicast and loopback.
        """
        if not ip in self.ip_list:
            try:
                ip_address = ipaddress.ip_address(ip)
                use = not (ip_address.is_multicast or ip_address.is_unspecified
                           or ip_address.is_reserved or ip_address.is_loopback
                           or ip_address.is_link_local)
                if use and (self.include_public or ip_address.is_private):
                    self.new_ip(ip)
                    network = ipaddress.IPv4Network("{}/{}".format(
                        ip, self.netmask),
                                                    strict=False)
                    self.new_range(str(network))
            except ValueError:
                pass

    def new_ip(self, ip):
        """
            Function called when a new IP address was seen
        """
        if not ip in self.ip_list:
            self.ip_list.add(ip)
            host = self.hs.id_to_object(ip)
            host.add_tag('sniffer')
            host.save()
            print_success("New ip address: {}".format(ip))

    def new_range(self, ip_range):
        """
            Function called when a new range was seen
        """
        if not ip_range in self.ip_ranges:
            self.ip_ranges.add(ip_range)
            doc = self.rs.id_to_object(ip_range)
            doc.add_tag('sniffer')
            doc.save()
            print_success("New ip range: {}".format(ip_range))

    def start(self, timeout=None):
        """
            Starts the sniffing
        """
        if timeout:
            print_notification(
                "Starting sniffer for {} seconds".format(timeout))
        else:
            print_notification("Starting sniffer")
        print_notification("Press ctrl-c to stop sniffing")
        try:
            sniff(prn=self.callback, store=0, timeout=timeout)
        except PermissionError:
            print_error("Please run this tool as root")