Ejemplo n.º 1
0
def scanner(ip):
    global victims, interface

    nmap = nmap3.NmapHostDiscovery()
    victims = nmap.nmap_no_portscan(ip)["hosts"]
    result = []

    print("")
    for element in victims:
        addr = element["addr"]
        if addr != gateway_ip and addr != get_local_ip(interface):
            result.append(addr)
            print(" -- " + addr)

    if len(result) < 1:
        print("No computers were found on the local network, try again.")
        raise SystemExit
    else:
        print("")
        answer = input("Continue? [Y/n] ")

        if answer.lower() != 'y':
            raise SystemExit

    victims = result
    return victims
Ejemplo n.º 2
0
def nmap():
    with app.app_context():

        info = Monitor.query.all()
        if info is None:
            exit(1)
        ip = ''
        for item in info:
            ip = ip + item.ipaddr + ' '
        nmap = nmap3.NmapHostDiscovery()
        results = nmap.nmap_no_portscan(ip)
        db.session.execute(Monitor.__table__.update(), [{'isok': '0'}])
        db.session.commit()
        if results is None:
            exit(1)
        for i in range(0, len(results['hosts'])):
            ip = results['hosts'][i]['addr']
            status = 1 if results['hosts'][i]['state'] == 'up' else '0'
            mon = Monitor.query.filter_by(ipaddr=ip).first()
            if mon:
                mon.update_time = getCurrentDate()
                mon.isok = status
                db.session.add(mon)
                db.session.execute(MonLog.__table__.insert(),
                                   [{
                                       'mon_id': mon.id,
                                       'update_time': getCurrentDate()
                                   }])
                db.session.commit()
Ejemplo n.º 3
0
def pingRange():
    print("Start Host: ", startHost)
    print("End Host: ", endHost)
    nmap = nmap3.NmapHostDiscovery()
    ipRange = int(ipaddress.IPv4Address(endHost)) - int(
        ipaddress.IPv4Address(
            startHost))  #Gets the range of the IP Addresses to be scanned
    address = ipaddress.IPv4Address(startHost)
    for i in range(
            ipRange + 1
    ):  #For loop to scan all hosts within the range of IP Addresses provided
        result = nmap.nmap_no_portscan(str(address),
                                       args="-PE")  #Command for ICMP Scan
        if str(address) in result:
            hostResults.append({
                'address': str(address),
                'state': result[str(address)]["state"]["state"]
            })  #Stores the host IP Address and its state using ICMP Scan
        else:
            hostResults.append(
                {
                    'address': str(address),
                    'state': 'down'
                }
            )  #Stores the host IP Address and its state as down if there is an error

        address += 1

    scanPort()
Ejemplo n.º 4
0
 def thread(self) -> None:
     """Scan for lost agents with NMAP, and signal them to a \
         controller."""
     mapper = nmap3.NmapHostDiscovery()
     while self.thread_kill_flag is False:
         results = mapper.nmap_no_portscan(
             LOOKUP_BITS_TO_NETWORK_CLASS[self.bits] + "/" +
             str(self.bits))
         results.pop("stats")
         results.pop("runtime")
         self.client_lock.acquire(True)
         for result in list(results.keys()):
             self.host = result
             # pylint: disable=broad-except
             try:
                 Daemon.Herder.connect(self)
                 if Daemon.Herder.receive(self) == \
                         "KINETIC WAITING FOR CONTROLLER":
                     Daemon.Herder.send(
                         self,
                         "POINT " + socket.gethostname() + ".local")
                 else:
                     Daemon.Herder.disconnect(self)
             except BaseException:
                 Daemon.Herder.disconnect(self)
         self.client_lock.release()
Ejemplo n.º 5
0
        def thread(self) -> None:
            """
            Scan for lost agents with NMAP, and signal them to a controller.

            :return: None
            """
            mapper = nmap3.NmapHostDiscovery()
            LOOKUP = {8: "10.0.0.0", 16: "172.16.0.0", 24: "192.168.0.0"}
            while self.thread_kill_flag is False:
                results = mapper.nmap_no_portscan(LOOKUP[self.bits] + "/" +
                                                  str(self.bits))
                results.pop("stats")
                results.pop("runtime")
                for result in list(results.keys()):
                    self.host = result
                    try:
                        Daemon.Herder.connect(self)
                        if Daemon.Herder.receive(
                                self) == "KINETIC WAITING FOR CONTROLLER":
                            Daemon.Herder.send(
                                self,
                                "POINT " + socket.gethostname() + ".local")
                        else:
                            Daemon.Herder.disconnect(self)
                    except BaseException:
                        Daemon.Herder.disconnect(self)
Ejemplo n.º 6
0
 def Fin_Scan(self, Host, Timing=4):
     print("Loading ........................................")
     self.Host = sock.gethostbyname(self.Host)
     HOST_lib = nmap3.NmapHostDiscovery()
     System = HOST_lib.nmap_portscan_only(str(self.Host),
                                          args=f" -sF -T{self.Timing} -vv")
     for z in System[self.Host]:
         print(z['portid'], z['service']['name'], z['state'] + self.angry)
Ejemplo n.º 7
0
    def Dns_Brute(self, Host, Timing=4):
        print("Loading ........................................")

        HOST_lib = nmap3.NmapHostDiscovery()
        System = HOST_lib.nmap_dns_brute_script(self.Host)
        for output in System:
            print(" " + output['address'],
                  " " + output['hostname'] + self.angry)
Ejemplo n.º 8
0
def host_discovery(ip):
    if ip.startswith('192') or ip.startswith('10'):
        nmap = nmap3.NmapHostDiscovery()
        result = nmap.nmap_no_portscan(ip + '/24')
    else:
        return None

    return [h['addr'] for h in result['hosts']]
Ejemplo n.º 9
0
 def scan(self):
     nmap = nmap3.NmapHostDiscovery()  # instantiate nmap object
     for item in self.networks:
         temp_scan_result = nmap.nmap_no_portscan(item.replace('\n', ''),
                                                  args="-R --system-dns")
         self.scan_results = {**self.scan_results, **temp_scan_result}
         self.scan_results.pop("stats")
         self.scan_results.pop("runtime")
     return self.scan_results
Ejemplo n.º 10
0
def scan_ip_survial(ip):
    nmScan = nmap3.NmapHostDiscovery()
    results = nmScan.nmap_portscan_only(ip)
    if results[ip] and len(results[ip]) > 0:
        return {
            'IP': ip,
            # 'Hostname:': nmScan[ip]['hostnames'][0]['name']
        }
    else:
        return None
Ejemplo n.º 11
0
def perform_portscan():
    # Fast portscan. Aka Stage 1
    logging.debug('[FAST PORTSCAN] started')
    nmap = nmap3.NmapHostDiscovery()
    res = nmap.scan_top_ports(None, args="-F -iL ips_to_scan.txt")
    res = remove_keys(res)
    # logging.debug(res)
    find_interesting_ip(res)
    logging.debug('[FAST PORTSCAN] done')
    return res
Ejemplo n.º 12
0
def main():
    host = '181.171.237.33'
    nmap = nmap3.NmapHostDiscovery()
    results = nmap.nmap_portscan_only(host)
    for service in results[host]:
        print(f'''
            Port: {service["portid"]}
            State: {service["state"]}
            Service: {service["service"]["name"]}
            Protocol: {service["protocol"]}
        ''')
Ejemplo n.º 13
0
def main(args):
    addr = None
    network = None

    if args.ifname:
        addr, subnet = get_ip(args.ifname)
        network = str(IPNetwork(f"{addr}/{subnet}").cidr)
    elif args.subnet:
        network = args.subnet

    # Simple test, for more info: https://pypi.org/project/python3-nmap/
    nmap = nmap3.NmapHostDiscovery()
    results = nmap.nmap_no_portscan(network)
    for i in results['hosts']:
        print(i['addr'], file=sys.stdout)
Ejemplo n.º 14
0
def perform_host_discovery():
    # Aka stage 0
    logging.debug('[HOST DISCOVERY] started')
    nmap = nmap3.NmapHostDiscovery()
    res = nmap.nmap_no_portscan(
        None, args="-sn --excludefile exclude_ip.txt -iL target.txt")
    #logging.debug('Output of host discovery: ')
    res = remove_keys(res)
    # logging.debug(res)
    f = open("ips_to_scan.txt", "w")
    for ip in res:
        logging.debug('Found IP: ' + ip)
        if res[ip]['state']['state'] == "up":
            f.write(ip + "\n")
    f.close()
    logging.debug('[HOST DISCOVERY] done')
Ejemplo n.º 15
0
def OpPorts():
    pyfiglet.print_figlet("__________", font="standard", colors=colors1)
    cprint('[+] Input the IP or URL to be Checked ------> ',
           'red',
           attrs=['bold'],
           end=' ')
    res = input()
    print()
    nmap = nmap3.NmapHostDiscovery()
    results = nmap.nmap_portscan_only(res)
    for i in results[res]:
        cprint(
            f'[+] {i["service"]["name"]}({i["portid"]}) : {i["state"].upper()} [+]',
            'green',
            attrs=['bold'])
        print()
Ejemplo n.º 16
0
def pingSingle(host):
    print("Host: ", host)
    nmap = nmap3.NmapHostDiscovery()
    result = nmap.nmap_no_portscan(host, args="-PE")  #Command for ICMP scan

    if host in result:
        hostResults.append({
            'address': host,
            'state': result[host]["state"]["state"]
        })  #Stores the host IP Address and its state using ICMP Scan
    else:
        hostResults.append({
            'address': host,
            'state': "down"
        })  #Stores the host IP Address and its state using ICMP Scan

    scanPort()
Ejemplo n.º 17
0
def get_hosts(host: str) -> Dict[str, List[str]]:
    """

    """
    clients_list = []
    try:
        hd_scan = nmap3.NmapHostDiscovery()
        result = hd_scan.nmap_no_portscan(host)
        for res in result:
            check_ip = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", res)
            if check_ip:
                ip = check_ip.group()
                clients_list.append(ip)
    except Exception as e:
        clients_list = []
    record_result(data=clients_list)
    return {"result": clients_list}
Ejemplo n.º 18
0
def discover_ports(url: str):
    """
    Scan a web server for all available https ports.

    :param url: url to be scanned
    :return: list of usable ports
    """
    logging.info('Discovering ports...')
    nmap = nmap3.NmapHostDiscovery()
    # Scan with nmap for all open ports
    logging.debug('Scanning with nmap for all open ports...')
    result = nmap.nmap_portscan_only(url)
    open_ports = [
        port['portid'] for port in list(result.items())[0][1]['ports']
    ]
    usable_ports = []
    logging.debug(f'ports : {open_ports}')
    for port in open_ports:
        sleep = 0
        # Loop until there is a valid response or after 10 seconds
        while True:
            try:
                head = requests.head(f'https://{url}:{port}',
                                     timeout=5,
                                     verify=False,
                                     headers={'Connection': 'close'})
                if head.status_code < 400:
                    usable_ports.append(int(port))
                    break
            except requests.exceptions.SSLError:
                break
            # Valid exception, there might a port alive after timeout
            except (requests.exceptions.ReadTimeout,
                    requests.exceptions.Timeout):
                usable_ports.append(int(port))
                break
            except requests.exceptions.ConnectionError as exception:
                sleep = incremental_sleep(sleep, exception, 5)
    logging.debug(f'scanned ports : {usable_ports}')
    return usable_ports
 def __init__(self, networks):
     self.hosts = dict()
     self.nmap = nmap3.NmapHostDiscovery()
     self.networks = self.sanitaise_networks(networks)
     self.scan_results = self.basic_scan()
Ejemplo n.º 20
0
import nmap3
import netifaces as ni
from rich.console import Console

console = Console()
nmap = nmap3.NmapHostDiscovery()
#Below is what is deciding what to do in different cases, then its doing the scan
try:
    ni.ifaddresses('wlan0')
    ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
    ip = str(ip + '/24')
    results = nmap.nmap_no_portscan(ip)
except:
    try:
        interface = str(input('Enter Your Interface name e.g. wlan0: '))
        ni.ifaddresses(interface)
        ip = ni.ifaddresses(interface)[ni.AF_INET][0]['addr']
        ip = str(ip + '/24')
        results = nmap.nmap_no_portscan(ip)
    except KeyboardInterrupt:
        print("\nGood Bye!")

console.print(f'[yellow]MAC ADDRESS       [blue]---   [yellow]DEVICE NAME',
              style="bold")
#Below is what's printing the result to the user
try:
    for result in results:
        try:
            mac = results[result]['macaddress']['addr']
            name = results[result]['macaddress']['vendor']
            console.print(f'[yellow]{mac} [blue] --- [yellow]{name}',
Ejemplo n.º 21
0
    def do_run(self, prg):
        "run [command] ... execute a command\nPossible commands to run: scan, bruteforce, logintest\n"

        if self.check_open_project():
            if prg.strip() == "":
                self.print_error(
                    "You need to specify something to run! \nPossible commands to run: scan, bruteforce, logintest"
                )

            # Run nmap scan
            if prg == "scan":
                nm = nmap3.NmapHostDiscovery()

                prj_folder = os.path.join(self.PRJ_PATH, self.PRJ_NAME)
                till_ctr = 0
                with open(os.path.join(prj_folder, "to_crack.lst"),
                          "a") as outfile:
                    try:
                        # count number of ranges
                        max_range = 0
                        with open(os.path.join(prj_folder, "to_scan.lst"),
                                  "r") as f:
                            for iprange in f:
                                max_range += 1

                        # run the scan
                        with open(os.path.join(prj_folder, "to_scan.lst"),
                                  "r") as f:
                            for iprange in f:
                                ctr = 0
                                till_ctr += 1

                                # Skip priviously cracked
                                if till_ctr <= self.SCANNED_TILL:
                                    continue

                                iprange = iprange.strip()
                                print("Scanning " + iprange + " [" +
                                      str(till_ctr) + " / " + str(max_range) +
                                      "]")

                                check_online_status.wait_for_connection(
                                    self.TEST_DELAY)
                                try:
                                    res = nm.nmap_portscan_only(
                                        iprange, args="-p 22,3389-3390 -T5")
                                except KeyboardInterrupt:
                                    print("")
                                    return

                                # check results of the scan and save them
                                for key in res.keys():
                                    if key not in ["runtime", "stats"]:
                                        for port_dict in res[key]:
                                            if port_dict['state'] == "open":
                                                line = key + ":" + port_dict[
                                                    'portid']
                                                print(line)
                                                outfile.write(line + "\n")
                                                ctr += 1

                                # Print how much hosts where found
                                if ctr > 0:
                                    print(
                                        f"{Fore.GREEN}{ctr} host(s) added{Style.RESET_ALL}"
                                    )

                                self.SCANNED_TILL += 1
                                self.save_status()
                    except FileNotFoundError:
                        self.print_error(
                            "You need to add one or more IP-ranges before scanning!"
                        )

            # Run hydra-attack
            elif prg == "bruteforce" or prg == "logintest":
                prj_folder = os.path.join(self.PRJ_PATH, self.PRJ_NAME)
                till_ctr = 0
                with open(os.path.join(prj_folder, "cracked_accounts.txt"),
                          "a") as outfile:
                    try:
                        # count
                        max_range = 0
                        with open(os.path.join(prj_folder, "to_crack.lst"),
                                  "r") as f:
                            for host in f:
                                max_range += 1

                        # run hydra
                        with open(os.path.join(prj_folder, "to_crack.lst"),
                                  "r") as f:
                            for host in f:
                                till_ctr += 1

                                # Skip priviously cracked
                                if till_ctr <= self.CRACKED_TILL:
                                    continue

                                host = host.strip()
                                print("Cracking " + host + " [" +
                                      str(till_ctr) + " / " + str(max_range) +
                                      "]")

                                check_online_status.wait_for_connection(
                                    self.TEST_DELAY)
                                hydra_cmd = "hydra -I -t 4 -L " + self.USER_LIST + " -P " + self.PW_LIST + " "

                                # override for combined list
                                if prg == "logintest":
                                    hydra_cmd = "hydra -I -t 4 -C " + self.COMB_LIST + " "

                                ip, port = host.split(":")
                                if port == "22":
                                    hydra_cmd += ip + " ssh"
                                if port == "3389":
                                    hydra_cmd += ip + " rdp"
                                if port == "3390":
                                    hydra_cmd += "-s 3390 " + ip + " rdp"

                                try:
                                    ts = time.time()
                                    res = subprocess.run(
                                        hydra_cmd.split(" "),
                                        stdout=subprocess.PIPE)
                                    td = time.time() - ts
                                except KeyboardInterrupt:
                                    print("")
                                    return
                                lines = res.stdout.decode("utf-8").split("\n")

                                for line in lines:
                                    if "password:"******"{Fore.GREEN}{line}{Style.RESET_ALL}"
                                        )
                                        outfile.write(line + "\n")

                                print("Bruteforcing done in " + str(td) +
                                      " sec.")
                                self.CRACKED_TILL += 1
                                self.save_status()

                    except FileNotFoundError:
                        self.print_error(
                            'You need to find with "run scan" some hosts before cracking!'
                        )

            # Unknown action - display error
            else:
                self.print_error('The input "' + prg +
                                 '" is unknown... Use "scan" or "cracking"!')

            # Save status of the project
            print("")
            self.save_status()
Ejemplo n.º 22
0
import os
import sys
import subprocess
import time
import ipaddress
import nmap3
import json
import signal
from datetime import datetime
from tabulate import tabulate

nmap = nmap3.Nmap()  # Accessing list of basic Nmap functions
nmap_scan = nmap3.NmapScanTechniques(
)  # Accessing list of Nmap scan technique functions
nmap_host = nmap3.NmapHostDiscovery(
)  # Accessing list of Nmap host discovery functions

#Declaring Global Variables
port = 443  # Default port if no port is specified
startRange = None  # Default start range
endRange = None  # Default end range
runtime = False  # Default show runtime
startTime = time.time()  # Starting time in which the command was run
hostList = []  # List of host/s to be scanned


def portScan(port):

    for host in hostList:

        #CONNECT Scan
Ejemplo n.º 23
0
def launch(target, domain, ports, templates):
    def tpl(i):
        template = {
            # OPTIONS FOR THE SCAN TECHNIQUE FUNCTION
            1: '-sF',  # 'FIN scan'
            2: '-sI',  # 'Idle scan'
            3: '-sS',  # 'Default: TCP SYN scan'
            4: '-sP',  # 'ping-only'
            5: '-sT',  # 'TCP connect() scan'
            6: '-sU',  # 'UDP scan'
            7: '-F',  # 'Fast scan'

            # OPTIONS FOR THE SCAN DISCOVERY FUNCTION
            8: '-Pn',  # 'No ping scan'
            9: '-sn',  # 'Liveness detection: no port scan'
            10: '-PR',  # 'ARP scan: local network only'
            11: '-n',  # 'Disable DNS resolution: reduces noise'
            12:
            '-O --osscan-guess',  # 'Used with no ping: aggressive OS detection'
            13:
            '-A',  # 'Used with no ping: Advanced detection: OS detection and Version detection, Script scanning and Traceroute'
            14:
            '-A -T2',  # 'Used with no ping: Advanced detection: with stealth scan mode'
            15: '-A -v',  # 'Used with no ping: Advanced detection: verbose'
            16:
            '-n -A',  # 'Used with no ping: Advanced detection: scan with no DNS resolution'
            17:
            '-f -A',  # 'Used with no ping: Advanced detection: combined with packet fragmentation'
            18: '-T4 -sV',  # 'Used with no ping: Aggressive service detection'
            19:
            '-n -sV --version-intensity 3',  # 'Used with no ping: Aggressive service detection: with version-intensity 3'
            20: '-n -V',  # 'Used with no ping: Number version detection'
            21:
            '-O --osscan-guess -p ',  # 'Used with no ping: OS detection with port selection'

            # OPTIONS FOR THE SCAN COMMAND FUNCTION
            22: '-sX',  # 'Basic service detection combined with Xmas scan'
            23: '-sA',  # 'Firewall rule detection: ACK scan'
            24: '-O',  # 'OS detection'
            25: '20 -sZ',  # 'SCTP: Advanced silent scan for top20 ports'
            26: '--top-ports',  # 'Top ports scan (1000 ports)'
            27: '-script dns-brute',  # 'Dns-brute-script( to get subdomains )'
            28:
            '-sL',  # 'List scan: lists each host on the network(s) specified, without sending any packets to the target hosts'
            29: '-p-',  # 'Subnet scan'
            30: '-sV'  # 'Basic service detection'           
        }

        return template.get(i)

    # try:
    #     nm  = nmap3.Nmap()

    # except nmap3.Nmap:
    #     print('Nmap not found', sys.exc_info()[0])
    #     sys.exit(1)
    # except:
    #     print("Unexpected error:", sys.exc_info()[0])
    #     sys.exit(1)

    nm = nmap3.Nmap()
    nmt = nmap3.NmapScanTechniques()
    nmd = nmap3.NmapHostDiscovery()

    if templates or domain:
        if ports:
            # Not in the final code - just for debug
            choice = tpl(21) + str(ports)
            print("\n\nTrying option: ", choice)

            tpl = tpl(21)
            res = scan_discovery(nmd, tpl, target, ports)

            # Print for debug
            colored_json = highlight(json.dumps(res, indent=4, sort_keys=True),
                                     lexers.JsonLexer(),
                                     formatters.TerminalFormatter())
            print("\n\n", colored_json)

        elif domain:
            tpl = tpl(27)
            res = scan_command(nm, tpl, None, domain)

            # Print for debug
            colored_json = highlight(json.dumps(res, indent=4, sort_keys=True),
                                     lexers.JsonLexer(),
                                     formatters.TerminalFormatter())
            print("\n\n", colored_json)

        else:
            tpl = tpl(templates)
            print("\n\nTrying option: ", tpl)

            if templates <= 7:
                res = scan_techniques(nmt, tpl, target)

                # Print for debug
                colored_json = highlight(
                    json.dumps(res, indent=4, sort_keys=True),
                    lexers.JsonLexer(), formatters.TerminalFormatter())
                print("\n\n", colored_json)

            elif templates in range(8, 22):
                res = scan_discovery(nmd, tpl, target, None)

                # Print for debug
                colored_json = highlight(
                    json.dumps(res, indent=4, sort_keys=True),
                    lexers.JsonLexer(), formatters.TerminalFormatter())
                print("\n\n", colored_json)

            else:
                res = scan_command(nm, tpl, target, None)

                # Print for debug
                colored_json = highlight(
                    json.dumps(res, indent=4, sort_keys=True),
                    lexers.JsonLexer(), formatters.TerminalFormatter())
                print("\n\n", colored_json)

    else:
        tpl = tpl(3)
        res = scan_techniques(nmt, tpl, target)

        # Print for debug
        colored_json = highlight(json.dumps(res, indent=4, sort_keys=True),
                                 lexers.JsonLexer(),
                                 formatters.TerminalFormatter())
        print("No option was set\n\n", colored_json)
Ejemplo n.º 24
0
def main():
    logo = (f"""{PURP}
                                                 
                                                                  
 __         ______     ______   __  __     ______    
/\ \       /\  ___\   /\__  _\ /\ \_\ \   /\  ___\   
\ \ \____  \ \  __\   \/_/\ \/ \ \  __ \  \ \  __\   
 \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_____\ 
  \/_____/   \/_____/     \/_/   \/_/\/_/   \/_____/ 
                                        
    by Hades921                               

""")
    print(logo)
    print("""
    1. Information Gathering
    2. Vulnerability Analysis
    3. Exploiting
    4. Passwords/Hashes
    5. GeoIP
    6. Network
    
    """)
    choice = input("Please select a module: ")
    import os
    clear = lambda: os.system('cls')
    clear()

    if choice == "1":
        print(logo)
        print("What kind of scan would you like to conduct?")
        print("1. Whois Scan")
        print("2. Port Scan")
        print("3. Subdomain Scanner")
        print("4. Spider")
        print("5. OS fingerprinting")
        print("6. Subnet scan")
        print("99. Back \n")
        infochoice = input("Please put in your choice: ")
        if infochoice == "1":
            clear = lambda: os.system('cls')
            clear()
            print(logo)
            ip = input("What IP do you want to look up: ")
            obj = IPWhois(ip)
            res = obj.lookup_whois()
            from pprint import pprint
            pprint(res)
        if infochoice == "2":
            clear = lambda: os.system('cls')
            clear()
            os.system("python modules/port_scanner.py")
        if infochoice == "3":
            clear = lambda: os.system('cls')
            clear()
            os.system("python modules/subdomain_scanner.py")
        if infochoice == "4":
            os.system("python modules/spider.py")
        if infochoice == "5":
            import nmap3
            nmap = nmap3.Nmap()
            os_results = nmap.nmap_version_detection(
                input("Please enter the IP you want to scan: "))
            print(os_results)
        if infochoice == "6":
            import nmap3
            nmap = nmap3.Nmap()
            results = nmap.nmap_subnet_scan(
                "Please enter the IP you want to scan: ")

    if choice == "2":
        print(logo)
        print("""
You have selected the Vulnerability Analysis module
    1. SQLI vulnerability scan
    2. SSL vulnerability scan
    3. XSS vulnerability scan
    99. Back
""")

        choice2 = input("Please select a module: ")
        if choice2 == "1":
            clear = lambda: os.system('cls')
            clear()
            os.system("python modules/sqli.py")
        if choice2 == "2":
            clear = lambda: os.system('cls')
            clear()
            import os
            server = input("please put in the domain: ")
            command = 'pysslscan scan --tls10 --scan=server.ciphers --scan=vuln.heartbleed --scan=server.compression --report=term:rating=ssllabs.2009e ' + server
            os.system(command)
        if choice2 == "3":
            os.system("python modules/xss.py")

    if choice == "3":
        print(logo)
        print("1. SQL injection")
        print("2. DOS")
        print("99. Back")
        exChoice = input("Select an attack module: ")
        if exChoice == "1":
            clear = lambda: os.system('cls')
            clear()
            domain = input("what is the domain: ")
            import os
            myCmd = 'sqlmap -u ' + domain
            os.system(myCmd)
        if exChoice == "2":
            print("Please select one")
            print("1. SlowLoris")
            print("2. SYN flood")
            doschoice = input(": ")
            if doschoice == "1":
                clear = lambda: os.system('cls')
                clear()
                domain = input("What is the domain: ")
                import os
                myCmd = "slowloris -v " + domain
                os.system(myCmd)
            if doschoice == "2":
                from modules import syn_flood
    if choice == "4":
        print(logo)
        print("Lets crack some hashes")
        print("1. hashes")
        print("2. brute")
        print("99. Back")
        choice1 = input("select a module: ")
        if choice1 == "1":
            clear = lambda: os.system('cls')
            clear()
            print(logo)
            print("1. Hash identifier")
            print("2. Hash Cracking")
            print("99. Back")
            cryptographyc1 = input("Please put in your choice: ")
            if cryptographyc1 == "1":
                from modules import hash_identifier
            if cryptographyc1 == "2":
                print("""
                1. Hash database lookup
                2. Hash dictionary attack
                """)
                c = input("Please choose a module: ")
                if c == "1":
                    clear = lambda: os.system('cls')
                    clear()
                    from modules import hash_database
                if c == "2":
                    clear = lambda: os.system('cls')
                    clear()
                    from modules import hash_cracker2

        if choice1 == "2":
            clear = lambda: os.system('cls')
            clear()
            print(logo)
            print("""
    Please choose a module
        1. SSH
        2. FTP

                """)
            c1 = input(": ")
            if c1 == "1":
                from modules import ssh_bruter
            if c1 == "2":
                from modules import ftp_cracker

    if choice == "5":
        clear = lambda: os.system('cls')
        clear()
        print(logo)
        adress = input("what ip do you want me to locate: ")
        import urllib.request
        import json
        with urllib.request.urlopen("https://geolocation-db.com/json/" +
                                    adress) as url:
            data = json.loads(url.read().decode())
            print(data)
    if choice == "6":
        clear = lambda: os.system('cls')
        clear()
        print(logo)
        print("""Network Module
        
        1. ARP scan
        2. Local network host discovery 

        """)
        nscan = input("Please select a module: ")
        if nscan == "1":
            os.system("sudo python3 modules/arp_req.py")
        if nscan == "2":
            import nmap3
            ip = input("Please put in the local ip of the target: ")
            nmap = nmap3.NmapHostDiscovery()
            results = nmap.nmap_arp_discovery(ip)
            import json
            json_data = results
            print(json.dumps(json_data, indent=1))

    else:
        return
Ejemplo n.º 25
0
class Networkscanner:
    host_discoverer = nmap3.NmapScanTechniques().nmap_ping_scan
    version_detector = nmap3.Nmap().nmap_version_detection
    port_scanner = nmap3.NmapHostDiscovery().nmap_portscan_only
    add_lock = threading.Lock()

    def __init__(self, ip_range, port_range, detect_version):
        print('[TRACE] Init NetworkScanner...')

        ip_version = check_ip(ip_range)

        if ip_version is None:
            raise Exception('Bad ip range')

        if not check_ports(port_range):
            raise Exception('Bad port range')

        self.ip_range = ip_range
        self.port_range = port_range
        self.detect_version = detect_version
        self.args = '-T4 '

        if ip_version == 6:
            self.args += '-6'
        else:
            self.args += '-D RND:10'

        self.available_hosts = Queue()
        self.report = dict()

        print('[TRACE] Init was done')

    def __discover(self):
        print('[TRACE] Discover what hosts are available...')
        results = self.host_discoverer(target=self.ip_range, args=self.args)

        for key, _ in results.items():
            try:
                ipaddress.ip_address(key)
                self.available_hosts.put(key)
            except:
                pass

        print(f'[TRACE] {self.available_hosts.qsize()} hosts are available')

    def __scan_host(self, host):
        results = dict()

        results['state'] = 'up'
        results['port_info'] = dict()

        result = self.port_scanner(target=host,
                                   args=self.args + ' -p ' + self.port_range)

        open_ports = []
        service_info = []

        for state in result[host]['ports']:
            if self.detect_version and (state['portid'] == '80'
                                        or state['portid'] == '443'):
                continue

            if state['state'] == 'open':
                open_ports.append(state['portid'])

        if self.detect_version:
            result = self.version_detector(target=host,
                                           args=self.args + ' -p 80,443')

            for state in result[host]['ports']:
                port_report = dict()
                port_report['state'] = state['state']

                if port_report['state'] == 'open':
                    port_report['service'] = state['service']

                service_info.append({state['portid']: port_report})

            results['port_info']['service_info'] = service_info

        results['port_info']['open_ports'] = open_ports

        with self.add_lock:
            self.report[host] = results

    def __do_scan(self):
        while True:
            host = self.available_hosts.get()
            self.__scan_host(host)
            self.available_hosts.task_done()

    def scan(self):
        self.__discover()

        print('[TRACE] Start scanning. Wait, please...')
        for _ in range(0, min(100, self.available_hosts.qsize())):
            threading.Thread(target=self.__do_scan, daemon=True).start()

        self.available_hosts.join()

        print('[TRACE] Scan has finished')
        return self.report
Ejemplo n.º 26
0
import socket
import nmap
import nmap3
import datetime
import json
import dns.resolver
#Imports the required packages
hostname = socket.gethostname(
)  #sets the varaiable hostname to the socket command
ip = socket.gethostbyname(
    hostname)  #sets the ip varaible and gets the ip of the machine
nm = nmap.PortScanner()  #sets the nm varaible to call the nmap PortScanner
nm3Host = nmap3.NmapHostDiscovery(
)  #sets the nm3Host to the nmap host discover
nm3 = nmap3.Nmap()  #sets the nm3 varaible to the nmap command
DT = datetime.datetime.now()  #sets DT to the date and time
dns = dns.resolver.Resolver()  #sets dns to the dns command


def rangeScan(ip):  #creates the range scan function with the input of the ip
    for ip in nm.all_hosts(
    ):  #creates a for loop for the ip in the scanned hosts
        deviceName = ("Host : %s (%s)" % (ip, nm[ip].hostname()))
        state = ("State : %s" % nm[ip].state())
        fOpen = open("Port-Range-Scan(%s)-Created(%s).txt" % (portRange, DT),
                     "a")
        fOpen.write("%s\n%s" % (deviceName, state))
        fOpen.close()
        #writes to the file
        for protocol in nm[ip].all_protocols(
        ):  #creates a for loop for protocol in all of the protocols that were scanned