Exemplo n.º 1
0
    def setProcess(self, name, case_id, act_name, act_timestamp, event_index):
        """
        This function receives the basic case attributes and sets them up
        accordingly.
        If a process is new in the stream, the function instantiates a new
        process object and adds it to the process dictionary.
        """
        if name not in self._processes:
            process = Process(name, act_timestamp, self._th, self._gen_plot,
                              self._plot_path, self._gen_metrics,
                              self._metrics_path, self._denstream_kwargs)
            self._processes[name] = process

        self._processes[name].setCase(case_id, act_name, act_timestamp,
                                      event_index)
Exemplo n.º 2
0
    def deauth_hidden_targets(self):
        '''
            Sends deauths (to broadcast and to each client) for all
            targets (APs) that have unknown ESSIDs (hidden router names).
        '''
        self.decloaking = False
        # Only deauth if channel is fixed.
        if self.channel is None: return

        # Reusable deauth command
        deauth_cmd = [
            'aireplay-ng',
            '-0',  # Deauthentication
            '1',  # Number of deauths to perform.
            '--ignore-negative-one'
        ]
        for target in self.targets:
            if target.essid_known: continue
            now = int(time.time())
            secs_since_decloak = now - self.decloaked_times.get(
                target.bssid, 0)
            # Decloak every AP once every 30 seconds
            if secs_since_decloak < 30: continue
            self.decloaking = True
            self.decloaked_times[target.bssid] = now
            if Configuration.verbose > 1:
                from Color import Color
                verbout = " [?] Deauthing %s" % target.bssid
                verbout += " (broadcast & %d clients)" % len(target.clients)
                Color.pe("\n{C}" + verbout + "{W}")
            # Deauth broadcast
            iface = Configuration.interface
            Process(deauth_cmd + ['-a', target.bssid, iface])
            # Deauth clients
            for client in target.clients:
                Process(deauth_cmd + ['-c', client.bssid, iface])
Exemplo n.º 3
0
    def parsefile(self, filename):
        data = open(filename).read()

        data = data.split('\n')
        for line in data:
            if len(line) > 0 and line[0].isupper():
                if ' ' in line:
                    line = line.split(' ')
                elif '\t' in line:
                    line = line.split('\t')
                for i in range(2, len(line)):
                    term = line[i].split('/')
                    AQ.append(
                        Process(line[0], int(line[1]), int(term[0]),
                                int(term[1])))
Exemplo n.º 4
0
 def init(self):
     self.modify = False
     self.ui.btn_apply.setEnabled(False)
     self.currentProcess = None
     self.processDict = {}
     config_dir = self.config_dir()
     items = os.listdir(config_dir)
     for item in items:
         currentPath = self.config_dir() + os.sep + item
         if not os.path.isdir(currentPath) and os.path.exists(currentPath):
             with open(currentPath, 'r') as f:
                 content = f.read()
                 process = Process()
                 if process.load(content):
                     self.add_item(process)
Exemplo n.º 5
0
def ReadLastScanner():
    process = []
    date = ""
    with open("ProcessMonitor/processList.csv", 'rb') as f:
        reader = csv.reader(f)
        for line in reversed(list(reader)):
            p = Process(line[0],line[1])
            if not process:
                process.append(p)
                date = line[2]
            else:
                if date == line[2]:
                    process.append(p)
                else:
                    return process
    return process
Exemplo n.º 6
0
    def __init__(self, filename):
        super().__init__()
        self.processes = queue.Queue()
        list = []

        with open(filename) as file:
            for line in file:
                inputs = line.strip().split(',')
                pid = inputs[0]
                cycles = inputs[1]
                list.append(Process(pid, cycles))

        list = (sorted(list, key=lambda process: int(process.cycles)))

        for i in range(len(list)):
            self.processes.put(list[i])
Exemplo n.º 7
0
    def run(self):
        # Loading all the data into relevant data structures for later operation and use.
        for line in self.lines:
            words = line.split(' ')
            p = Process(words[0], int(words[1]), int(words[2]))
            self.load_time.append(int(words[1]))
            self.all.append(p)

        while self.i < len(self.lines):
            p = self.all[self.i]
            if p.start == self.program_counter:
                self.ready.add(p)
                self.process()
                self.i += 1
            else:
                self.i += 1
Exemplo n.º 8
0
def RLScanner():
    process = []
    date = ""
    with open("MonitorState/processList.csv", 'rb') as a:
        bufferReader = csv.reader(a)
        for line in reversed(list(bufferReader)):
            p = Process(line[0], line[1])
            if not process:
                process.append(p)
                date = line[2]
            else:
                if date == line[2]:
                    process.append(p)
                else:
                    return process
    return process
Exemplo n.º 9
0
    def check_for_wps_and_update_targets(capfile, targets):
        '''
            Given a cap file and list of targets, use TShark to
            find which BSSIDs in the cap file use WPS.
            Then update the 'wps' flag for those BSSIDs in the targets.

            Args:
                capfile - .cap file from airodump containing packets
                targets - list of Targets from scan, to be updated
        '''
        # Tshark is required to detect WPS networks
        if not Process.exists('tshark'):
            return

        command = [
            'tshark',
            '-r', capfile, # Path to cap file
            '-n', # Don't resolve addresses
            # Filter WPS broadcast packets
            '-Y', 'wps.wifi_protected_setup_state && wlan.da == ff:ff:ff:ff:ff:ff',
            '-T', 'fields', # Only output certain fields
            '-e', 'wlan.ta', # BSSID
            '-e', 'wps.ap_setup_locked', # Locked status
            '-E', 'separator=,' # CSV
        ]
        p = Process(command)


        try:
            p.wait()
            lines = p.stdout()
        except:
            # Failure is acceptable
            return

        bssids = set()
        for line in lines.split('\n'):
            if ',' not in line:
                continue
            bssid, locked = line.split(',')
            # Ignore if WPS is locked?
            if '1' not in locked:
                bssids.add(bssid.upper())

        for t in targets:
            t.wps = t.bssid.upper() in bssids
Exemplo n.º 10
0
    def get_mac(iface=None):
        from Configuration import Configuration
        from Process import Process
        import re

        if iface == None:
            Configuration.initialize()
            iface = Configuration.interface
        if iface == None:
            raise Exception('Interface must be defined (-i)')

        output = Process(['ifconfig', iface]).stdout()
        mac_regex = ('[a-zA-Z0-9]{2}-' * 6)[:-1]
        match = re.search('HWaddr (%s)' % mac_regex, output)
        if not match:
            raise Exception('Could not find the mac address for %s' % iface)
        return match.groups()[0].replace('-', ':')
Exemplo n.º 11
0
    def run(self):
        with Airodump(channel=self.target.channel,
                      target_bssid=self.target.bssid,
                      skip_wps=True,
                      output_file_prefix='wps_pin') as airodump:
            # Wait for target
            Color.clear_entire_line()
            Color.pattack("WPS", self.target, self.attack_type(),
                          "Waiting for target to appear...")
            self.target = self.wait_for_target(airodump)

            # Start bully
            self.bully_proc = Process(self.cmd,
                                      stderr=Process.devnull(),
                                      bufsize=0,
                                      cwd=Configuration.temp())
            t = Thread(target=self.parse_line_thread)
            t.daemon = True
            t.start()
            try:
                while self.bully_proc.poll() is None:
                    try:
                        self.target = self.wait_for_target(airodump)
                    except Exception as e:
                        Color.clear_entire_line()
                        Color.pattack("WPS", self.target, self.attack_type(),
                                      "{R}failed: {O}%s{W}" % e)
                        Color.pl("")
                        self.stop()
                        break
                    Color.clear_entire_line()
                    Color.pattack("WPS", self.target, self.attack_type(),
                                  self.get_status())
                    time.sleep(0.5)
            except KeyboardInterrupt as e:
                self.stop()
                raise e
            except Exception as e:
                self.stop()
                raise e

        if self.crack_result is None:
            Color.clear_entire_line()
            Color.pattack("WPS", self.target, self.attack_type(),
                          "{R}Failed{W}\n")
Exemplo n.º 12
0
 def on_add(self):
     ret = QInputDialog.getText(self, '请输入启动项目名称', '名称')
     if not ret[1]:
         return
     name = ret[0]
     if name.isEmpty():
         return
     if self.processDict.has_key(QString2str(name)):
         QMessageBox.warning(self, '警告', '该启动项已存在!')
         return
     curProcess = Process()
     curProcess.setName(QString2str(name))
     configDir = self.config_dir()
     configFilePath = configDir + os.sep + QString2str(name) + '.json'
     with open(configFilePath, 'w+') as f:
         f.write(curProcess.save())
     self.add_item(curProcess)
     self.ui.cb_process.setCurrentIndex(self.ui.cb_process.count() - 1)
Exemplo n.º 13
0
 def update(self):
     """
         @method update
         Finds new processes by use of memoization
         Iteratively updates or creates an entry for
         processes
     """
     pids = [int(pid) for pid in os.listdir(PROC_DIR) if pid.isdigit()]
     for pid in pids:
         if pid in self.process_dict:  # it already exists
             self.process_dict[pid].update()
         else:
             p = Process(pid, self.item_focus, self.item_remove, self.w)
             self.process_dict[pid] = p
             self.append(p)
     self.sort(key=lambda x: getattr(x, self.sort_var), reverse=self.asc)
     if self.at_top:
         self.set_focus(0)
Exemplo n.º 14
0
    def create_process(self):
        priority = randrange(0, 6)
        pid = self._generate_pid.next()

        cpu_bursts = randrange(1, 5)
        io_bursts = cpu_bursts - 1

        composite_operation = CompositeOperation()

        for operation in self._generate_operations_vector(
                cpu_bursts, io_bursts):
            composite_operation.add_operation(operation)

        process = Process(pid,
                          priority,
                          composite_operation,
                          systemManager=self.system_manager)

        return process
Exemplo n.º 15
0
 def AddProcess(self,
                name,
                file,
                dir,
                color,
                corrections=None,
                scale=1.0,
                regionCondition=None):
     self.modeling[name] = Process(name,
                                   file,
                                   dir,
                                   color,
                                   corrections,
                                   scale,
                                   regionCondition=regionCondition,
                                   debug=self.debug)
     if not regionCondition:
         self.order.append(name)
     return
Exemplo n.º 16
0
    def handleCreation(self, id_, is_coordinator, lastValue):
        # add each node to the network with Node class
        node_id = int(id_.replace("P", ""))
        # Create Node obj to store in the node_list
        node_obj = Process(node_id, is_coordinator, self.current_port,
                           self.consistency_history[-1])
        create(node_obj.id_, node_obj.is_coordinator, node_obj.port,
               node_obj.value)

        reply = send_message("here?", node_obj.port)

        if reply == "ok":
            self.node_list.append(node_obj)
            if node_obj.is_coordinator:
                self.coordinator = node_obj

            print(
                f"Node {node_obj.label} has been created on PORT {self.current_port}"
            )
Exemplo n.º 17
0
def getInput(input, processes):
    print "Enter number of processes (Range from 3-10):",
    num_of_processes = int(raw_input())
    while num_of_processes < 3 or num_of_processes > 10:
        print "Number of processes is out of range. Please enter again:",
        num_of_processes = int(raw_input())
    input.append(num_of_processes)
    for i in xrange(num_of_processes):
        pid = raw_input("Enter process name: ")
        arrival_time = int(raw_input("Enter arrival time: "))
        burst_time = int(raw_input("Enter burst time: "))
        priority = int(raw_input("Enter priority (Range from 1-6): "))
        while priority < 1 or priority > 6:
            priority = int(
                raw_input("Priority is out of range. Please enter again: "))
        processes.append(Process(pid, arrival_time, burst_time, priority))
    quantum = int(raw_input("Enter quantum: "))
    input.append(quantum)
    print
Exemplo n.º 18
0
    def pyrit_handshakes(self):
        ''' Returns True if pyrit identifies a handshake, False otherwise '''
        if not Process.exists('pyrit'):
            return []

        bssid_essid_pairs = set()
        hit_target = False
        current_bssid = self.bssid
        current_essid = self.essid
        proc = Process(self.pyrit_command(), devnull=False)
        for line in proc.stdout().split('\n'):
            mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1]
            match = re.search("^#\d+: AccessPoint (%s) \('(.*)'\):$"
                % (mac_regex), line)
            if match:
                # We found a BSSID and ESSID
                (bssid, essid) = match.groups()

                # Compare to what we're searching for
                if self.bssid and self.bssid.lower() == bssid.lower():
                    current_essid = essid
                    hit_target = True
                    continue

                elif self.essid and self.essid == essid:
                    current_bssid = bssid
                    hit_target = True
                    continue

                elif not self.bssid and not self.essid:
                    # We don't know either
                    current_bssid = bssid
                    current_essid = essid
                    hit_target = True
                else:
                    # This AccessPoint is not what we're looking for
                    hit_Target = False
            else:
                # Line does not contain AccessPoint
                if hit_target and ', good,' in line:
                    bssid_essid_pairs.add( (current_bssid, current_essid) )
        return [x for x in bssid_essid_pairs]
Exemplo n.º 19
0
    def get_interfaces():
        '''
            Returns:
                List of Interface objects known by airmon-ng
        '''
        interfaces = []
        p = Process('airmon-ng')
        for line in p.stdout().split('\n'):
            # Ignore blank/header lines
            if len(line) == 0: continue
            if line.startswith('Interface'): continue
            if line.startswith('PHY'): continue

            # Strip out interface information
            fields = line.split("\t")
            while '' in fields:
                fields.remove('')
            # Add Interface object to list
            interfaces.append(Interface(fields))
        return interfaces
Exemplo n.º 20
0
def create_processes(rand, n,tau):
    """
    A method to create all processes objects once and for all.
    @param rand: rand48 generator
    @param n: number of processes needed to be generated
    @return processes: list of processes generated
    """
    name = 'A'
    processes = []
    for _ in range(n):
        arrival = math.floor(rand.next_exp())
        num_bursts = math.ceil(rand.drand48() * 100)
        timelist = []
        for _ in range(num_bursts - 1):
            timelist.append(math.ceil(rand.next_exp()))
            timelist.append(math.ceil(rand.next_exp()) * 10)
        timelist.append(math.ceil(rand.next_exp()))
        processes.append(Process(name, arrival, num_bursts, timelist,int(tau)))
        name = chr(ord(name) + 1)
    return processes
Exemplo n.º 21
0
def parseFile(filename):
    process = []
    num = 0
    for line in open(fileName, "r"):
        temp = (line.strip()).split(" ")
        if (num == 0):
            num = temp
            continue
        else:
            arrivals = temp[2:]
            # clean input
            for x in range(len(arrivals)):
                arrivals[x] = arrivals[x].split("/")
                arrivals[x][0] = int(arrivals[x][0])
                arrivals[x][1] = int(arrivals[x][1])
            # make object for each time
            for x in arrivals:
                new = Process(temp[0], temp[1], x)
                process.append(new)
    return [process, num]
Exemplo n.º 22
0
def read_config():
    global last_config
    file = open("config.txt", "r")
    lines = file.readlines()
    if "".join(lines) == last_config:
        return

    last_config = "".join(lines)

    temp_processes = []
    for line in lines:
        params = line.replace(" ", "").replace("\n", "").split(",")

        temp_processes.append(
            Process(params[0], int(params[1]), params[2], int(params[3]),
                    int(params[4]), params[5:]))

    processes.clear()
    processes.extend(custom_processes)
    processes.extend(temp_processes)
Exemplo n.º 23
0
    def tshark_bssid_essid_pairs(self):
        '''
            Scrapes capfile for beacon frames indicating the ESSID.
            Returns list of tuples: (bssid,essid)
        '''
        if not Process.exists('tshark'):
            raise Exception('tshark is required to find ESSID')

        essids = set()

        # Extract beacon frames from cap file
        cmd = [
            'tshark',
            '-r',
            self.capfile,
            '-R',
            'wlan.fc.type_subtype == 0x08 || wlan.fc.type_subtype == 0x05',
            '-2',  # tshark: -R without -2 is deprecated.
            '-n'
        ]
        proc = Process(cmd, devnull=False)
        for line in proc.stdout().split('\n'):
            # Extract src, dst, and essid
            mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1]
            match = re.search(
                '(%s) [^ ]* (%s).*.*SSID=(.*)$' % (mac_regex, mac_regex), line)
            if match is None:
                # Line doesn't contain src, dst, ssid
                continue
            (src, dst, essid) = match.groups()
            if dst.lower() == "ff:ff:ff:ff:ff:ff": continue
            if self.bssid:
                # We know the BSSID, only return the ESSID for this BSSID.
                if self.bssid.lower() == src.lower() or self.bssid.lower(
                ) == dst.lower():
                    essids.add((src, essid))
            else:
                # We do not know BSSID, add it.
                essids.add((src, essid))
        # Return list of tuples
        return [x for x in essids]
Exemplo n.º 24
0
def prep_subprocess(args=[], pipe_read=None, pipe_write=None):
    ''' Return a process object that read can execute.'''
    p = Process()
    new_in_fpath = None
    new_out_fpath = None
    
    try: # check for < > file redirection
        index = 0
        while index < len(args):
            arg = args[index]
            if arg == '<':
                if pipe_read:
                    raise IndexError # TODO Multiple redirection error
                new_in_fpath = args[index + 1]
                index += 2
            elif arg == '>':
                if pipe_write:
                    raise IndexError # TODO Multiple redirection error
                new_out_fpath = args[index + 1]
                index += 2
            else:
                p.args.append(arg)
                index += 1
 
    except IndexError:
        os.write(2, ("Shelly: Unexpected redirection %s \n" % args).encode())
        return None

    if new_in_fpath:
        p.input= os.open(new_in_fpath, os.O_RDONLY)
        os.set_inheritable(p.input, True)
    else:
        p.input = pipe_read

    if new_out_fpath:
        p.output = os.open(new_out_fpath, os.O_WRONLY | os.O_CREAT)
        os.set_inheritable(p.output, True)
    else:
        p.output = pipe_write

    return p
Exemplo n.º 25
0
 def deauth(target_bssid, essid=None, client_mac=None, num_deauths=None, timeout=2):
     num_deauths = num_deauths or Configuration.num_deauths
     deauth_cmd = [
         "aireplay-ng",
         "-0", # Deauthentication
         str(num_deauths),
         "--ignore-negative-one",
         "-a", target_bssid, # Target AP
         "-D" # Skip AP detection
     ]
     if client_mac is not None:
         # Station-specific deauth
         deauth_cmd.extend(["-c", client_mac])
     if essid:
         deauth_cmd.extend(["-e", essid])
     deauth_cmd.append(Configuration.interface)
     proc = Process(deauth_cmd)
     while proc.poll() is None:
         if proc.running_time() >= timeout:
             proc.interrupt()
         time.sleep(0.2)
Exemplo n.º 26
0
    def __enter__(self):
        '''
            Setting things up for this context.
            Called at start of 'with Airodump(...) as x:'
            Actually starts the airodump process.
        '''
        self.delete_airodump_temp_files()

        self.csv_file_prefix = Configuration.temp() + self.output_file_prefix

        # Build the command
        command = [
            'airodump-ng',
            self.interface,
            '-a',  # Only show associated clients
            '-w',
            self.csv_file_prefix,  # Output file prefix
            '--write-interval',
            '1'  # Write every second
        ]
        if self.channel:
            command.extend(['-c', str(self.channel)])
        elif self.five_ghz:
            command.extend(['--band', 'a'])

        if self.encryption:
            command.extend(['--enc', self.encryption])
        if self.wps:
            command.extend(['--wps'])
        if self.target_bssid:
            command.extend(['--bssid', self.target_bssid])

        if self.ivs_only:
            command.extend(['--output-format', 'ivs,csv'])
        else:
            command.extend(['--output-format', 'pcap,csv'])

        # Start the process
        self.pid = Process(command, devnull=True)
        return self
Exemplo n.º 27
0
def run_batch(cfg):

    directory = cfg.get('data', 'response_file')
    get_capabilities_docs = cfg.get('data', 'get_capabilities')
    output_dir = cfg.get('data', 'output_dir')
    max_features = cfg.get('other', 'max_features_for_validation')

    for file_path in glob.glob(directory + '*.json'):
        file = Path(file_path).stem
        logging.info("file {} begins".format(file))

        config = configparser.ConfigParser()
        config.add_section('data')
        config.add_section('other')

        config.set('data', 'response_file', file_path)
        config.set('data', 'get_capabilities',
                   get_capabilities_docs + file.split("_")[0] + ".xml")
        config.set('data', 'raster_output_path', output_dir + file + ".tif")

        config.set('data', 'output_dir', output_dir)
        config.set('data', 'raster_output_path', output_dir + file + ".tif")
        config.set('data', 'binary_raster_output_path',
                   output_dir + "bin_" + file + ".tif")
        config.set('data', 'validation_raster_output_path',
                   output_dir + "val_" + file + ".tif")
        config.set('other', 'max_features_for_validation', max_features)

        process = Process(config)
        process.run_algorithm()

        # validation of the result.
        validate(process.url, process.layer_name, process.input_data.crs.name,
                 process.layer_bbox, process.bin_raster_path,
                 process.val_raster_output_path, process.service_type,
                 process.service_version, process.max_features_for_validation)

        logging.info("file {} done \n \n".format(file))
Exemplo n.º 28
0
    def check_for_wps_and_update_targets(capfile, targets):
        '''
            Given a cap file and list of targets, use Wash to
            find which BSSIDs in the cap file use WPS.
            Then update the 'wps' flag for those BSSIDs in the targets.

            Args:
                capfile - .cap file from airodump containing packets
                targets - list of Targets from scan, to be updated
        '''
        # Wash/Walsh is required to detect WPS
        wash_name = 'wash'
        if not Process.exists(wash_name):
            wash_name = 'walsh'
            if not Proces.exists(wash_name):
                # Wash isn't found, drop out
                return

        command = [
            'wash',
            '-f', capfile, # Path to cap file
            '-C'            # Ignore Frame Check Sum errors
        ]
        p = Process(command)
        for line in p.stdout().split('\n'):
            # Ignore irrelevant lines
            if line.strip() == '' or line.startswith('Scanning for'):
                continue
            bssid = line.split(' ')[0]
            for t in targets:
                if t.bssid.lower() == bssid.lower():
                    # Update the WPS flag
                    t.wps = True

        # Mark other targets as "no" wps support
        for t in targets:
            if t.wps: continue
            t.wps = False
Exemplo n.º 29
0
    def terminate_conflicting_processes():
        ''' Deletes conflicting processes reported by airmon-ng '''
        '''
        % airmon-ng check

        Found 3 processes that could cause trouble.
        If airodump-ng, aireplay-ng or airtun-ng stops working after
        a short period of time, you may want to kill (some of) them!
        -e
        PID Name
        2272    dhclient
        2293    NetworkManager
        3302    wpa_supplicant
        '''

        out = Process(['airmon-ng', 'check']).stdout()
        if 'processes that could cause trouble' not in out:
            # No proceses to kill
            return

        hit_pids = False
        for line in out.split('\n'):
            if re.search('^ *PID', line):
                hit_pids = True
                continue
            if not hit_pids or line.strip() == '':
                continue
            match = re.search('^[ \t]*(\d+)[ \t]*([a-zA-Z0-9_\-]+)[ \t]*$',
                              line)
            if match:
                # Found process to kill
                pid = match.groups()[0]
                pname = match.groups()[1]
                Color.pl('{!} {R}terminating {O}conflicting process' +
                         ' {R}%s{O} (PID {R}%s{O})' % (pname, pid))
                os.kill(int(pid), signal.SIGTERM)
                if pname == 'NetworkManager':
                    Airmon.killed_network_manager = True
Exemplo n.º 30
0
 async def build_units(self, player, send_message, unit_time):
     """starts the currently prepared build thread"""
     if not self.build_prep:
         await send_message("nothing prepped")
         return
     if len(self.build_threads) >= self.workforce:
         await send_message(
             "You cannot train more then %i unit%s at once" %
             (self.workforce, "" if self.workforce == 1 else "s"))
         return
     cost = self.total_cost()
     # enough free threads and the player has the resources
     if await player.can_build(cost, None, send_message):
         player.use_resources(cost)
         p = Process(self.total_time(),
                     self.add_prep_to_player_func(player),
                     self.name + " building units",
                     cost=cost)
         self.build_threads.append(p)
         await send_message(
             "you started building:\n===================\n%s\n%s\n==================="
             % (get_units_str(self.build_prep), p.pretty_str(unit_time)))
         self.clear_build_prep()