Exemplo n.º 1
0
    def dissect(udp):
        pudp={}
        pudp["layer"] = 4
        pudp["protocol_name"] = "UDP"
        pudp["sport"] = udp.sport  # Source port
        pudp["dport"] = udp.dport  # Destination port
        pudp["ulen"] = udp.ulen  # Length
        pudp["usum"] = udp.sum  # Checksum

        if dns.check(udp):
            pudp["payload"] = dns.dissect(udp.data)
        else:
            pudp["payload"] = "unknown protocol on layer " + str(pudp["layer"]+1)

        return pudp
Exemplo n.º 2
0
def manager():
    the_config = config.read_redirect_configs()
    from_email = the_config.get('mail', 'from')
    device_error_email = the_config.get('mail', 'device_error')
    activate_url_template = the_config.get('mail', 'activate_url_template')
    password_url_template = the_config.get('mail', 'password_url_template')

    redirect_domain = the_config.get('redirect', 'domain')
    redirect_activate_by_email = the_config.getboolean('redirect',
                                                       'activate_by_email')
    mock_dns = the_config.getboolean('redirect', 'mock_dns')

    if mock_dns:
        dns = MagicMock()
    else:
        statsd_cli = statsd_client(the_config)
        dns = Dns(the_config.get('aws', 'access_key_id'),
                  the_config.get('aws', 'secret_access_key'),
                  the_config.get('aws', 'hosted_zone_id'), statsd_cli)

    create_storage = db_helper.get_storage_creator(the_config)
    smtp = mail.get_smtp(the_config)

    the_mail = mail.Mail(smtp, from_email, activate_url_template,
                         password_url_template, device_error_email)
    users_manager = services.Users(create_storage, redirect_activate_by_email,
                                   the_mail, dns, redirect_domain)
    return users_manager
Exemplo n.º 3
0
 def __init__(self, machine_name):
     self.client = boto3.client('ec2', EC2_CONFIG['region'])
     self.ip = ""
     self._machine_name = machine_name
     self.node = Node(machine_name, NodeSshCommands(self.get_external_ip))
     self.dns = Dns(machine_name, DnsSshCommands(self.get_external_ip))
     self.traffic = TrafficHandler(machine_name, TrafficSshCommands(self.get_external_ip))
Exemplo n.º 4
0
 def __init__(self, name, instance_index):
     self.name = name
     self.instance_index = instance_index
     self.executor = Executor()
     self.node = Node(name, NodeDockerCommands(name, self.get_external_ip))
     self.dns = Dns(name, DnsDockerCommands(name))
     self.traffic = TrafficHandler(name, TrafficDockerCommands(name))
Exemplo n.º 5
0
 def __init__(self, name):
     self.ip_pattern = re.compile(r".*value: (.+), time.*")
     self.command = "VBoxManage"
     self.ip = ""
     self.name = name
     self.node = Node(name, NodeSshCommands(self.get_external_ip))
     self.dns = Dns(name, DnsSshCommands(self.get_external_ip))
     self.traffic = TrafficHandler(name,
                                   TrafficSshCommands(self.get_external_ip))
Exemplo n.º 6
0
 def __init__(self,
              machine_name,
              project=COMPUTE_CONFIG['project'],
              zone=COMPUTE_CONFIG['zone']):
     self.compute = googleapiclient.discovery.build('compute', 'v1')
     self.project = project
     self.zone = zone
     self.ip = ""
     self._machine_name = machine_name
     self.node = Node(machine_name, NodeSshCommands(self.get_external_ip))
     self.dns = Dns(machine_name, DnsSshCommands(self.get_external_ip))
     self.traffic = TrafficHandler(machine_name,
                                   TrafficSshCommands(self.get_external_ip))
Exemplo n.º 7
0
    def dissect(tcp):
        """Runs all TCP dissectors.
        @param conn: connection.
        @param data: payload data.
        """
        ptcp = {}  # populate array of connections of Cuckoo default report
        ptcp["layer"] = 4  # Source port
        ptcp["protocol_name"] = "TCP"
        ptcp["sport"] = tcp.sport  # Source port
        ptcp["dport"] = tcp.dport  # Destination port
        ptcp["seqnum"] = tcp.seq  # Sequence number
        ptcp["acknum"] = tcp.flags  # Acknowledge number
        ptcp["off"] = tcp.off  # Data offset
        ptcp["reserved"] = 0  # Reserved - always 0
        ptcp["cb"] = Tcp.tcp_flags(tcp.data)  # Verify flag of control bits
        ptcp["win"] = tcp.win  # Window
        ptcp["cksum"] = tcp.sum  # Checksum
        ptcp["urp"] = tcp.urp  # Urgent Pointer
        ptcp["options"] = tcp.opts  # Options
        ptcp["padding"] = ''  # TODO not present in dpkt.ip.IP (maybe computed)

        # HTTP
        if http.check(tcp.data):
            ptcp["payload"] = http.dissect(tcp.data)
        # SMTP.
        elif smtp.check(tcp):
            ptcp["payload"] = smtp.dissect(tcp.data)
        # IRC
        elif irc.check(tcp):
            ptcp["payload"] = irc.dissect(tcp.data)
        # DNS
        elif dns.check(tcp):
            ptcp["payload"] = dns.dissect(tcp.data)
        # Unknown Protocol
        else:
            ptcp["payload"] = "unknown protocol on layer " + str(
                ptcp["layer"] + 1)

        return ptcp
Exemplo n.º 8
0
    def dissect(tcp):
        """Runs all TCP dissectors.
        @param conn: connection.
        @param data: payload data.
        """
        ptcp = {} # populate array of connections of Cuckoo default report
        ptcp["layer"] = 4  # Source port
        ptcp["protocol_name"] = "TCP"
        ptcp["sport"] = tcp.sport  # Source port
        ptcp["dport"] = tcp.dport  # Destination port
        ptcp["seqnum"] = tcp.seq  # Sequence number
        ptcp["acknum"] = tcp.flags  # Acknowledge number
        ptcp["off"] = tcp.off  # Data offset
        ptcp["reserved"] = 0  # Reserved - always 0
        ptcp["cb"] = Tcp.tcp_flags(tcp.data)  # Verify flag of control bits
        ptcp["win"] = tcp.win  # Window
        ptcp["cksum"] = tcp.sum  # Checksum
        ptcp["urp"] = tcp.urp  # Urgent Pointer
        ptcp["options"] = tcp.opts  # Options
        ptcp["padding"] = ''  # TODO not present in dpkt.ip.IP (maybe computed)

        # HTTP
        if http.check(tcp.data):
            ptcp["payload"] = http.dissect(tcp.data)
        # SMTP.
        elif smtp.check(tcp):
            ptcp["payload"] = smtp.dissect(tcp.data)
        # IRC
        elif irc.check(tcp):
            ptcp["payload"] = irc.dissect(tcp.data)
        # DNS
        elif dns.check(tcp):
            ptcp["payload"] = dns.dissect(tcp.data)
        # Unknown Protocol
        else:
            ptcp["payload"] = "unknown protocol on layer " + str(ptcp["layer"]+1)

        return ptcp
Exemplo n.º 9
0
    def test_revert_standard(self, mocker, commands, printing):
        subject = Dns('standard', self.mock_commands)
        self.mock_commands.dns_utility.return_value = ("reverted", "")

        subject.revert()

        assert self.mock_print.mock_calls == [
            mocker.call('\treverting DNS on standard...'),
            mocker.call('\tdone.')
        ]
        self.mock_commands.dns_utility.assert_called_with('revert')
        assert subject.dns_status == 'reverted'
        self.mock_print.reset()

        subject.revert()

        self.mock_print.assert_called_with('standard already reverted')
Exemplo n.º 10
0
def main(args):
    """Setups and starts dns and arp spoofing"""
    if os.geteuid():
        sys.exit("Hey! Listen! Run as root!")
    router = args.router or get_router()
    new_site = args.newsite or socket.gethostbyname(socket.gethostname())
    victim = args.victim
    site = args.site
    if not site:
        sys.exit("Please enter site. Example: -s test.com")
    if not victim:
        sys.exit("Please enter victim IP. Example: -v 192.168.0.42")
    poison = Arp(router, victim)
    poison.setup()
    poison.start()

    spoof = Dns(site, new_site)
    spoof.setup()
    # This is blocking
    spoof.start()

    poison.stop()
    sys.exit(0)
Exemplo n.º 11
0
class CLI:

    conf = Configuration()
    disc = Discovery(conf.getNumberOfHosts(), conf.getSimilarResponses(), conf.getNumberOfHosts())
    dns = None
    arp = Arp()
    PiIP = ""
    ARPresult = False
    thread = None

    mainText = "Enter the number of the method you want to use:\n\
        1. Pi-hole discovery\n\
        2. ARP Poisoning\n\
        3. DNS Poisoning\n\
        4. Exit\n"




    def mainCLI(self):
        while True:
            inp = input(self.mainText)
            if inp.lower().strip() == "1":  # Discovery
                self.discoveryCLI()
            elif inp.lower().strip() == "2":  # ARP Poisoning
                self.ARPCLI()
            elif inp.lower().strip() == "3":  # DNS Poisoning
                self.DNSCLI()
            elif inp.lower().strip() == "4":  # Exit
                print("Quitting...")
                if self.thread is not None:
                    print("   Stopping ARP poisoning")
                    self.thread.stop()
                sys.exit()
            else:  # Error
                print("Please only enter a number 1-4\n")


    # =========================== Discovery ==============================

    def discoveryCLI(self):
        print("You are about to search for the Pi-hole with settings: ")
        print("   DnsQueryTimeout:  {} ms".format(self.conf.getDNSQueryTimeout()))
        print("   SimilarResp:      {}%".format(self.conf.getSimilarResponses()))
        print("   NumberOfHosts:    {}".format(self.conf.getNumberOfHosts()))
        print("   DNSServer:        {}".format(self.conf.getDNSsetting()))
        print("   HostsURL          {}".format(self.conf.getHostsURL()))
        inp = input("Do you want to continue? (Y/n): ")

        if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
            print("\n")
            self.PiIP = self.disc.getPi(self.conf.getDNSQueryTimeout(), self.conf.getDNSsetting())
            if not self.PiIP == None:
                print("Pi-hole was found at " + self.PiIP + "\nYou can continue with ARP Poisoning")
            else:
                print("No Pi-hole was found")
            return
        elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
            return
        else:
            print("Invalid answer, please answer Y or N\n")
            self.discoveryCLI()
            return


    # ================================= ARP ====================================

    # For multi-threading
    def ARPPoisoning(self, setting):
        if len(setting) == 2:
            self.arp.poison_all(self.conf.getDNSsetting(), self.PiIP, self.arp.get_dns_mac(self.PiIP))
        else:
            self.arp.poison_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP))


    def ARPCLI(self):
        if self.thread is None:
            if self.PiIP == "" or self.PiIP is None:
                print("IP of the Pi-hole was not set, please run Discovery first.")
                return
            print("You are about to initiate ARP poisoning with settings: ")
            print("   NetworkInterface: " + self.conf.getNetworkInterface())
            setting = '{}'.format(self.conf.getARPtarget())
            if len(setting) == 2:
                print("   ARPtargets: " + self.conf.getDNSsetting())
            else:
                print("   ARPtargets: " + setting)

            print("   ARPdelay:  {} sec".format(self.conf.getARPdelay()))

            inp = input("Do you want to continue? (Y/n): ")

            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:

                # ARP poisoning, initial call

                # If target is all hosts on DNS server's subnet
                if len(setting) == 2:
                    print("Performing poisoning on " + self.conf.getDNSsetting())
                    if self.arp.poison_all(self.conf.getDNSsetting(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                # Otherwise
                else:
                    print("Performing poisoning on " + self.conf.getARPtarget())
                    if self.arp.poison_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP)):
                        self.ARPresult = True

                if self.ARPresult:
                    print("Pi-hole was successfully poisoned")
                    # ARP poisoning, threading
                    self.thread = RepeatedTimer(self.conf.getARPdelay(), self.ARPPoisoning, setting)
                    self.thread.start()

                    self.mainText = "Enter the number of the method you want to use:\n\
                            1. Pi-hole discovery\n\
                            2. Stop ARP Poisoning\n\
                            3. DNS Poisoning\n\
                            4. Exit\n"
                    return
                else:
                    print("Poisoning was not successful. Please try again.")
                    return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return

        # ARP Poisoning already running
        else:
            inp = input("You are about to stop the ARP poisoning, are you sure? (Y/N)")
            if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
                # Stop thread and restore ARP tables
                self.thread.stop()
                self.arp.restore_all(self.conf.getARPtarget(), self.PiIP, self.arp.get_dns_mac(self.PiIP))
                self.thread = None
                print("ARP poisoning successfully stopped.")
                self.mainText = "Enter the number of the method you want to use:\n\
                        1. Pi-hole discovery\n\
                        2. ARP Poisoning\n\
                        3. DNS Poisoning\n\
                        4. Exit\n"
                return
            elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
                print("Cancelling...")
                return
            else:
                print("Invalid answer, please answer Y or N\n")
                self.ARPCLI()
                return

    # ================================= DNS ===================================

    def DNSCLI(self):
        if not self.ARPresult:
            print("ARP Poisoning was not completed successfully, please do this first.")
            return
        print("You are about to replace DNS responses of the Pi-hole with settings: ")
        print("   PoisonType:      {}".format(self.conf.getPoisonType()))
        print("   ReplaceIP:       {}".format(self.conf.getReplaceIP()))
        print("   SpoofingTimeout: {}".format(self.conf.getSpoofingTimeout()))
        inp = input("Do you want to continue? (Y/n): ")

        if inp.lower().strip() == "y" or inp.lower().strip() == "yes" or len(inp.strip()) == 0:
            # Ask if we should run in verbose mode
            verbose = input("Do you want to run in verbose mode? (Y/n): ")
            if verbose.lower().strip() == "y" or verbose.lower().strip() == "yes" or len(verbose.strip()) == 0:
                self.dns = Dns(self.PiIP, self.conf.getReplaceIP(), self.conf.getPoisonType(), self.conf.getNetworkInterface(), True)
            else:
                self.dns = Dns(self.PiIP, self.conf.getReplaceIP(), self.conf.getPoisonType(), self.conf.getNetworkInterface(), False)
            print("\n")
            # Start spoofing
            self.dns.poison()
        elif inp.lower().strip() == "n" or inp.lower().strip() == "no":
            return
        else:
            print("Invalid answer, please answer Y or N\n")
            self.DNSCLI()
            return
Exemplo n.º 12
0
    def test_construction(self):
        subject = Dns('nodename', 'commands')

        assert subject.machine_name() == 'nodename'
        assert subject.dns_commands == 'commands'
        assert subject.dns_status == ''
Exemplo n.º 13
0
class HTTPHandler(BaseHTTPRequestHandler):
    '''handle the htpp request'''
    _dns = Dns(PROPS.get('region'), PROPS.get('key'), PROPS.get('secret'))
    _addr_record = {}
    _record_ip = {}

    def do_GET(self):
        '''处理GET请求'''

        # easy to use
        dns = HTTPHandler._dns
        addr_record = HTTPHandler._addr_record
        record_ip = HTTPHandler._record_ip
        html = 'sucess'

        # resolve request info: client ip and request params
        request_ip = str(self.client_address[0])
        query_str = self.path[2:].strip().split('&')
        params = {}  # request parameters dictionary
        for param in query_str:
            key_val = param.strip().split('=')
            if len(key_val) > 1:
                params[key_val[0]] = key_val[1]
            else:
                params[key_val[0]] = ''

        token = params.get('token')  # verify is the token valide
        record = params.get('record')
        host = params.get('host')
        domain = params.get('domain')

        if not token or token != PROPS.get('token'):
            html = 'invalid request'
        elif not host:
            html = 'dns host is necessary'
        else:
            if not record:  # get record
                if not domain:
                    self.response_content('missing dns record and domain')
                    return

                host_domain = '%s.%s' % (host, domain)
                if addr_record.has_key(host_domain):
                    record = addr_record.get(host_domain)
                else:
                    record = self._dns.get_dns_record(host, domain)
                    if record:
                        # add in address record dictionary
                        addr_record[host_domain] = record
                    else:
                        record = self._dns.add_dns_record(
                            host, domain, request_ip)
                        addr_record[host_domain] = record
                        # passed = 0 # don't have this record in ali dns server

            # update dns record
            try:
                if not record_ip.has_key(record):
                    record_ip[record] = dns.get_dns_ip(
                        record)  # get dns ip and store it
                if record_ip[record] != request_ip:
                    dns.update(record, host, request_ip)
                    record_ip[record] = request_ip
            except Exception, ex:
                html = 'failure:' + str(ex)

            self.response_content(html)
Exemplo n.º 14
0
            "[*] Victim IP:",
            colors.GREEN + net.get_victim_ip() + colors.DEFAULT))

    except KeyboardInterrupt:
        print("\r")
        print(colors.RED + "\n[!] Quitting.." + colors.DEFAULT)
        sys.exit(0)

    try:
        # ARP poison
        arp = Arp(net.get_gateway_ip(), net.get_victim_ip(),
                  net.get_interface())
        arp.setup_mac()

        # DNS spoofing
        dns = Dns(net.get_attacker_ip())

        # Let's start thread of both
        print(colors.WHITE + "\n[*] Starting ARP poisoning.." + colors.DEFAULT)
        poisonThread = threading.Thread(target=arp.poison)
        print(colors.WHITE + '[*] Spoofing DNS responses...' + colors.DEFAULT)
        dnsThread = threading.Thread(target=dns.spoof)

        poisonThread.daemon = True
        dnsThread.daemon = True

    except KeyboardInterrupt:
        print("\r")
        print(colors.RED + "\n[!] Quitting.." + colors.DEFAULT)
        sys.exit(0)