def print_targets(self): ''' Prints targets to console ''' if len(self.targets) == 0: Color.p('\r') return if self.previous_target_count > 0: # We need to "overwrite" the previous list of targets. if self.previous_target_count > len(self.targets) or \ Scanner.get_terminal_height() < self.previous_target_count + 3: # Either: # 1) We have less targets than before, so we can't overwrite the previous list # 2) The terminal can't display the targets without scrolling. # Clear the screen. from Process import Process Process.call('clear') else: # We can fit the targets in the terminal without scrolling # "Move" cursor up so we will print over the previous list Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count)) self.previous_target_count = len(self.targets) # Overwrite the current line Color.p('\r') Target.print_header() for (index, target) in enumerate(self.targets): index += 1 Color.pl(' {G}%s %s' % (str(index).rjust(3), target))
def strip(self, outfile=None): # XXX: This method might break aircrack-ng, use at own risk. ''' Strips out packets from handshake that aren't necessary to crack. Leaves only handshake packets and SSID broadcast (for discovery). Args: outfile - Filename to save stripped handshake to. If outfile==None, overwrite existing self.capfile. ''' if not outfile: outfile = self.capfile + '.temp' replace_existing_file = True else: replace_existing_file = False cmd = [ 'tshark', '-r', self.capfile, # input file '-R', 'wlan.fc.type_subtype == 0x08 || eapol', # filter '-w', outfile # output file ] proc = Process(cmd) proc.wait() if replace_existing_file: from shutil import copy copy(outfile, self.capfile) os.remove(outfile) pass
def __init__(self, target, attack_type, client_mac=None, replay_file=None): ''' Starts aireplay process. Args: target - Instance of Target object, AP to attack. attack_type - str, e.g. "fakeauth", "arpreplay", etc. client_mac - MAC address of an associated client. ''' super(Aireplay, self).__init__() # Init the parent Thread self.target = target self.output_file = Configuration.temp("aireplay_%s.output" % attack_type) self.attack_type = WEPAttackType(attack_type).value self.error = None self.status = None self.cmd = Aireplay.get_aireplay_command(self.target, attack_type, client_mac=client_mac, replay_file=replay_file) self.pid = Process(self.cmd, stdout=open(self.output_file, 'a'), stderr=Process.devnull(), cwd=Configuration.temp()) self.start()
def __init__(self): self.processor = Process() self.control = Control() self.width = 800 self.height = 600 self.fps = 1000 / 60 self.UI_handler = []
def strip(self, outfile=None): # XXX: This method might break aircrack-ng, use at own risk. ''' Strips out packets from handshake that aren't necessary to crack. Leaves only handshake packets and SSID broadcast (for discovery). Args: outfile - Filename to save stripped handshake to. If outfile==None, overwrite existing self.capfile. ''' if not outfile: outfile = self.capfile + '.temp' replace_existing_file = True else: replace_existing_file = False cmd = [ 'tshark', '-r', self.capfile, # input file '-R', 'wlan.fc.type_subtype == 0x08 || wlan.fc.type_subtype == 0x05 || eapol', # filter '-2', # tshark: -R without -2 is deprecated. '-w', outfile # output file ] proc = Process(cmd) proc.wait() if replace_existing_file: from shutil import copy copy(outfile, self.capfile) os.remove(outfile) pass
def __init__( self, gerst_data, mout_data, extract_data, hop_data, gist_data, mout_process, maisch_process, ): self.gerst = Ingredient("gerst", gerst_data) self.mout = Ingredient("mout", mout_data) self.extract = Ingredient("extract", extract_data) self.hop = Ingredient("hop", hop_data) self.gist = Ingredient("gist", gist_data) self.mouten = Process("mouten", mout_process) self.maischen = Process("maischen", maisch_process) self.y = None # 2 binary variables added self.dim = 2 + sum([ self.gerst.dim, self.mout.dim, self.extract.dim, self.hop.dim, self.gist.dim ])
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', '-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 == None: # Line doesn't contain src, dst, ssid continue (src, dst, essid) = match.groups() if self.bssid: # We know the BSSID, only return the ESSID for this BSSID. if self.bssid.lower() == src.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]
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 ] if self.channel: command.extend(['-c', str(self.channel)]) 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
def IO_interrupt(process: Process, system_clock: int): # 保存现场 process.recover['system_clock'] = system_clock process.recover['occupied_time'] = process.occupied_time process.recover['state'] = process.state # 进程状态变换 process.state = State.ready
def start(self): JSONRPCConfig.append_string = '\n' self._command = [ 'guitarix', '--nogui', '--name', self._cfg.get('name', 'guitarix'), '--rpcport', self._cfg.get('rpc_port', 8881), '--server-name', self._cfg.get('jack', 'jack') ] Process.start(self)
class Aircrack(object): def __init__(self, ivs_file=None): self.cracked_file = Configuration.temp() + 'wepkey.txt' # Delete previous cracked files if os.path.exists(self.cracked_file): os.remove(self.cracked_file) command = ['aircrack-ng', '-a', '1', '-l', self.cracked_file, ivs_file] self.pid = Process(command, devnull=True) def is_running(self): return self.pid.poll() == None def is_cracked(self): return os.path.exists(self.cracked_file) def stop(self): ''' Stops aircrack process ''' if self.pid.poll() == None: self.pid.interrupt() def get_key_hex_ascii(self): if not self.is_cracked(): raise Exception('Cracked file not found') f = open(self.cracked_file, 'r') hex_raw = f.read() f.close() hex_key = '' ascii_key = '' while len(hex_raw) > 0: # HEX if hex_key != '': hex_key += ':' hex_key += hex_raw[0:2] # ASCII # Convert hex to decimal code = int(hex_raw[0:2], 16) if code < 32 or code > 127: # Hex key is non-printable in ascii ascii_key = None continue elif ascii_key == None: # We can't generate an Ascii key continue # Convert decimal to char ascii_key += chr(code) # Trim first two characters hex_raw = hex_raw[2:] continue return (hex_key, ascii_key)
def setSumOfBkg(self): sumofbkg = Process('SumOfBkg', [], {}, 'sumofbkg', year=self.year, region=self.region) for process in self: if process.proctype == 'bkg': sumofbkg.add(process) self.processes['SumOfBkg'] = sumofbkg
def print_oclhashcat(self, cap_file): if not Process.exists("hashcat"): return Color.pl("\n {O}# OCLHASHCAT: GPU-based cracking. Fast.") hccapx_file = "generated.hccapx" if Process.exists("cap2hccapx"): Color.pl(" {G}cap2hccapx {C}%s %s{W}" % (cap_file, hccapx_file)) else: Color.pl(" {O}# Visit https://hashcat.net/cap2hccapx to generate a .hccapx file{W}") Color.pl(" {O}# Browse -> %s -> Convert" % cap_file) Color.pl(" {G}hashcat {W}-m 2500 {C}%s %s{W}" % (hccapx_file, self.wordlist))
def __init__(self, pid, need_time, arrive_time, pname=""): '''任务状态, 包含每个进程的pcb和到达时间,开始时间,结束时间等信息 ''' self.pcb = Process(pid, need_time, pname) # 到达时间 self.arrive_time = arrive_time # 开始时间 self.start_time = 0 # 结束时间 self.finish_time = 0
def addProcess(id): global newList completeOperationMatch = r"(\x2d)?\d(\x2a|\x2b|\x2d|\x5e|\x2f|\x25)\d" x = Xeger(limit=5) operation = x.xeger(completeOperationMatch) TME = random.randint(7, 18) size = random.randint(7, 25) TASK = Process(id, operation, TME, 0, size) TASK.setRemainingT(TME) newList.append(TASK)
def __init__(self, ivs_file=None): self.cracked_file = Configuration.temp() + 'wepkey.txt' # Delete previous cracked files if os.path.exists(self.cracked_file): os.remove(self.cracked_file) command = ['aircrack-ng', '-a', '1', '-l', self.cracked_file, ivs_file] self.pid = Process(command, devnull=True)
def _clientDisconnect(self): if self._client: log.info("Disconnecting client '%s'" % self._cfg.get('name', 'jack')) try: jack.set_info_function(None) jack.set_error_function(None) self._client.deactivate() self._client.close() except Exception as e: log.error("Unable to gracefully disconnect '%s' client: %s" % (self._cfg.get('name', 'jack'), e)) Process._clientDisconnect(self)
class Main: def __init__(self): self.dbg = pydbg() self.config = Config() self.process = Process(self) self.gameState = GameState(self) self.renderer = Renderer(self) def runSynchronous(self): def renderFrame(dbg): self.renderer.renderFrame() return DBG_CONTINUE def startingHandler(dbg): dbg.bp_set(FRAME_BP, handler=renderFrame) dbg.bp_del(START_BP) return DBG_CONTINUE self.process.findGame() self.renderer.makeWindow() self.renderer.initDirect3D() self.dbg.attach(self.process.kof_pid) self.dbg.bp_set(START_BP, restore=False, handler=startingHandler) self.dbg.run() def runAsynchronous(self): self.process.findGame() self.renderer.makeWindow() self.renderer.initDirect3D() self.renderer.runAsynchronous() def release(self): def releaseDebugger(): # remove all set breakpoints/watchpoints #self.dbg.bp_del_all() # why doesn't this work? self.dbg.bp_del_hw_all() self.dbg.bp_del_mem_all() print "Cleaned up pydbg instance" print "Releasing Main..." releaseDebugger() elements = ( self.process, self.renderer, ) for element in elements: if element is not None: element.release() print "Released Main"
def AddData(self, name, file, dir): self.data = Process(name, file, dir, ROOT.kBlack, corrections=None, scale=1.0, regionCondition=None, debug=self.debug) #self.order.append(name) return
def addProcess(self, process_name, req_skill, worker): p = Process() p.assign_to_taskgroup(worker) p.set_req_skills(req_skill) print(p._Process__req_skills) self.__processes[process_name]=p
def stop(iface): Color.p("{!} {R}disabling {O}monitor mode{O} on {R}%s{O}... " % iface) (out,err) = Process.call('nexutil -m0') (out,err) = Process.call('nexutil -m') nexutil_monitor_mode = out.split()[1] # Assert that there is an interface in monitor mode if nexutil_monitor_mode != 0: Color.pl('{R}disabled %s{W}' % iface) else: Color.pl('{O}could not disable on {R}%s{W}' % iface)
def run(self): with Airodump(channel=self.target.channel, target_bssid=self.target.bssid, skip_wash=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")
def start(self): base_dir = path.dirname(path.dirname(__file__)) proxy_path = path.join(base_dir, 'lib', 'websockify', 'websocketproxy.py') webui_path = path.join(base_dir, 'guitarix-webui') self._command = [ 'python', '-u', proxy_path, '--web', webui_path, '%s:%d' % (self._cfg.get('web_address', '*'), self._cfg.get('web', 8000)), 'localhost:%d' % self._cfg.get('rpc_port', 8881) ] Process.start(self)
def cowpatty_handshakes(self): ''' Returns True if cowpatty identifies a handshake, False otherwise ''' if not Process.exists('cowpatty'): return [] if not self.essid: return [] # We need a essid for cowpatty :( proc = Process(self.cowpatty_command(), devnull=False) for line in proc.stdout().split('\n'): if 'Collected all necessary data to mount crack against WPA' in line: return [(None, self.essid)] return []
def start(self): JSONRPCConfig.append_string = "\n" self._command = [ "guitarix", "--nogui", "--name", self._cfg.get("name", "guitarix"), "--rpcport", self._cfg.get("rpc_port", 8881), "--server-name", self._cfg.get("jack", "jack"), ] Process.start(self)
def print_oclhashcat(self, cap_file): if not Process.exists("hashcat"): return Color.pl("\n {O}# OCLHASHCAT: GPU-based cracking. Fast.") hccapx_file = "generated.hccapx" if Process.exists("cap2hccapx"): Color.pl(" {G}cap2hccapx {C}%s %s{W}" % (cap_file, hccapx_file)) else: Color.pl( " {O}# Visit https://hashcat.net/cap2hccapx to generate a .hccapx file{W}" ) Color.pl(" {O}# Browse -> %s -> Convert" % cap_file) Color.pl(" {G}hashcat {W}-m 2500 {C}%s %s{W}" % (hccapx_file, self.wordlist))
class Router: network = None processor = None metadata = "" def __init(self, network): self.network = network self.network.start_server() self.metadata = self.network.get_metadata() self.processor = Process(self.network) def process_data(self, data_to_process): self.processor.get_data(data_to_process)
def create_proc_list(file_name, current_cycle = 0): proc_list = [] proc_to_be_created_list = [] with open(file_name) as proc_file: proc_file_data = json.load(proc_file) for i in xrange(0, len(proc_file_data["procs"])): current_proc = proc_file_data["procs"][i] if current_proc["arrival_time"] == current_cycle: proc_list.append(Process(i + 1, current_proc["num_pages"] * OSParams.page_size, current_proc["arrival_time"], current_proc["page_exec_order"])) else: proc_to_be_created_list.append(Process(i + 1, current_proc["num_pages"], current_proc["arrival_time"], current_proc["page_exec_order"])) return proc_list, proc_to_be_created_list
def start(self): base_dir = path.dirname(path.dirname(__file__)) proxy_path = path.join(base_dir, "lib", "websockify", "websocketproxy.py") webui_path = path.join(base_dir, "guitarix-webui") self._command = [ "python", "-u", proxy_path, "--web", webui_path, "%s:%d" % (self._cfg.get("web_address", "*"), self._cfg.get("web", 8000)), "localhost:%d" % self._cfg.get("rpc_port", 8881), ] Process.start(self)
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 Process.exists(wash_name): # Wash isn't found, drop out return command = [ 'wash', '-f', capfile # Path to cap file ] p = Process(command) p.wait() if p.poll() != 0: return bssids = [bssid.upper() for bssid in Wash.BSSID_REGEX.findall(p.stdout())] for t in targets: t.wps = t.bssid.upper() in bssids
def print_targets(self): ''' Prints targets to console ''' if len(self.targets) == 0: Color.p('\r') return if self.previous_target_count > 0: # We need to "overwrite" the previous list of targets. if Configuration.verbose <= 1: # Don't clear screen buffer in verbose mode. if self.previous_target_count > len(self.targets) or \ Scanner.get_terminal_height() < self.previous_target_count + 3: # Either: # 1) We have less targets than before, so we can't overwrite the previous list # 2) The terminal can't display the targets without scrolling. # Clear the screen. from Process import Process Process.call('clear') else: # We can fit the targets in the terminal without scrolling # "Move" cursor up so we will print over the previous list Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count)) self.previous_target_count = len(self.targets) # Overwrite the current line Color.p('\r') # First row: columns Color.p(' NUM') Color.p(' ESSID') if Configuration.show_bssids: Color.p(' BSSID') Color.pl(' CH ENCR POWER WPS? CLIENT') # Second row: separator Color.p(' ---') Color.p(' -------------------------') if Configuration.show_bssids: Color.p(' -----------------') Color.pl(' --- ---- ----- ---- ------') # Remaining rows: targets for idx, target in enumerate(self.targets, start=1): Color.clear_entire_line() Color.p(' {G}%s ' % str(idx).rjust(3)) Color.pl(target.to_str(Configuration.show_bssids))
def __init__(self): ''' 初始化 新建对象时默认执行 ''' # ## 窗口 # 主窗口 self.mainWindow = MainWindow() # 信息窗口 self.informationMessageApp = QtWidgets.QWidget() self.informationMessageWindow = MessageWindow() # 服务项 self.preprocess = Preprocess() self.process = Process() self.postprocess = Postprocess() self.attachmentMatch = AttachmentMatch() self.jsonService = JsonService() self.settingJsonService = JsonService('settings.json') # ## 连接 Slots 和 Signals # 快速处理/开始: 按下 --> 快速处理 self.mainWindow.expressProcessButton.pressed.connect( self.expressProcess) # 开始处理/开始: 按下 --> 一般处理 self.mainWindow.generalProcessButton.pressed.connect( self.generalProcess) # 开始处理/附件匹配选择框: 状态变化 --> 附件选择是否生效 self.mainWindow.shouldMatchAttachmentCheckBox.stateChanged.connect( self.shouldEnableAttachmentMatch) # 开始处理/原始数据浏览: 按下 --> 选择原始数据文件 self.mainWindow.generalProcessOriginalDataExploreButton.pressed.connect( self.exploreOriginalDataFile) # 开始处理/附件目录浏览: 按下 --> 选择附件所在目录 self.mainWindow.generalProcessAttachmentLocationExploreButton.pressed.connect( self.exploreAttachmentDirectory) # 开始处理/导出数据浏览: 按下 --> 选择导出数据文件 self.mainWindow.generalProcessExportFileExploreButton.pressed.connect( self.exploreExportDataFile)
def __init__(self, **kwargs): # needed for constructor super(Display, self).__init__(**kwargs) # these two lines needed to use the keyboard and stuff self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) # timer just like in java, takes in a function and acts as a independent thread Clock.schedule_interval(self.update, 0.01) try: self.processor = Process() self.connected = True except Exception as e: print("Unable to connect to DAQ") self.connected = False
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)
async def new_build(self, time, func, name, send_message, building=None, cost=None): p = Process(time, func, "building %s" % name, building=building, cost=cost) self.build_threads.append(p) await send_message("you started:\n%s" % p.pretty_str(Player.unit_time_f()))
def launch(self): # Make sure launch file exists if self._launchFile and os.path.exists(self._launchFile): try: popen = subprocess.Popen([ 'roslaunch', self._launchFile, 'NAMESPACE:=' + rospy.get_namespace(), 'DEVICE:=' + self._path ]) self._process = Process(popen) return True except: pass return False
def __init__(self): Gtk.Window.__init__(self) self.set_size_request(320, 240) basebox = Gtk.HPaned() drawing = Gtk.DrawingArea() drawing.modify_bg(0, Gdk.Color(0, 0, 0)) vbox = Gtk.VBox() boton1 = Gtk.Button("Sin Efecto") boton2 = Gtk.Button("Con Efecto") vbox.pack_start(boton1, False, False, 0) vbox.pack_start(boton2, False, False, 0) basebox.pack1(drawing, True, True) basebox.pack2(vbox, False, True) self.add(basebox) self.show_all() self.realize() self.process = Process( drawing.get_property('window').get_xid()) self.process.play() self.connect("delete-event", self.__exit)
def __init__(self, target, attack_type, client_mac=None, replay_file=None): ''' Starts aireplay process. Args: target - Instance of Target object, AP to attack. attack_type - int, str, or WEPAttackType instance. client_mac - MAC address of an associated client. ''' cmd = Aireplay.get_aireplay_command(target, attack_type, client_mac=client_mac, replay_file=replay_file) # TODO: set 'stdout' when creating process to store output to file. # AttackWEP will read file to get status of attack. # E.g., chopchop will regex "(\d+)% done" to get percent complete. ''' from subprocess import PIPE sout = PIPE if '--chopchop' in cmd: sout = open(Configuration.temp('chopchop'), 'w') ''' self.pid = Process(cmd, devnull=False, cwd=Configuration.temp())
def print_john(self, cap_file): if not Process.exists("pyrit"): return Color.pl("\n {O}# JOHN: CPU or GPU-based cracking. Fast.") Color.pl(" {O}# Use --format=wpapsk-cuda (or wpapsk-opengl) to enable GPU acceleration") Color.pl(" {O}# See http://openwall.info/wiki/john/WPA-PSK for more info on this process") Color.pl(" {G}aircrack-ng {W}-J hccap {C}%s{W}" % cap_file) Color.pl(" {G}hccap2john {W}hccap.hccap > hccap.john{W}") Color.pl(" {G}john {W}--wordlist {C}\"%s\" {W}--format=wpapsk {C}\"hccap.john\"{W}" % (self.wordlist))
def aircrack_handshakes(self): if not self.bssid: return [] (stdout, stderr) = Process.call(self.aircrack_command()) if 'passphrase not in dictionary' in stdout.lower(): return [(self.bssid, None)] else: return []
def runExternalFilter(self, inputStream, outputStream): if self.__use_stdin: inFile = None else: inFile = self.newTempFile("%s.in" % self.__class__.__name__) Pump.stream2file(inputStream, inFile) if self.__use_stdout: outFile = None else: outFile = self.newTempFile("%s.out" % self.__class__.__name__) cmd = self.getCommandLine(inFile, outFile) try: assert trace("Starting %s: %s" % (self.__name, cmd)) xfilter = Process(cmd, separate_stderr=self.__separate_stderr) if self.__use_stdin: assert trace("Writing file to %s stdin" % self.__name) Pump.stream2stream(inputStream, xfilter.getInputStream()) if self.__use_stdout: # output assert trace("Pumping %s stdout to outputStream" % self.__name) Pump.stream2stream(xfilter.getOutputStream(), outputStream) if self.__separate_stderr: assert trace("Handling %s stderr" % self.__name) self.handleErrorOutput(xfilter.getErrorStream()) else: assert trace("Handling %s stdout" % self.__name) self.handleOutput(xfilter.getOutputStream()) if self.__separate_stderr: assert trace("Handling %s stderr" % self.__name) self.handleErrorOutput(xfilter.getErrorStream()) rc = xfilter.waitFor() assert trace("%s finished with exit code: 0x%X" % (self.__name, rc)) if not (rc in self.__normalReturnCodes): raise ExternalFilterException, "Return code 0x%X" % (rc,) if not self.__use_stdout: if os.path.exists(outFile): try: if os.path.getsize(outFile) > 0: Pump.file2stream(outFile, outputStream, "b") else: raise ExternalFilterException, "Output file is empty: %s" % (outFile,) finally: self.removeTempFile(outFile) else: raise ExternalFilterException, "Output file not found: %s" % (outFile,) finally: if inFile is not None: self.removeTempFile(inFile) pass return rc
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]
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
def start(self): self._command = ['jackd', '--name', self._cfg.get('name', 'jack')] cfg = self._cfg.get('config', {}) if cfg.get('rtpriority', 89): self._command += ['--realtime', '--realtime-priority', int(self._cfg.get('config', {}).get('rtpriority', 89))] else: self._command += ['--no-realtime'] if self._cfg.get('type', 'alsa') == 'alsa': self._command += ['-dalsa', '--device', cfg.get('device', 'hw:1'), '--rate', cfg.get('samplerate', 44100), '--period', cfg.get('buffer', 128), '--nperiods', cfg.get('periods', 3)] jack.set_info_function(self._jack_info_log) jack.set_error_function(self._jack_error_log) Process.start(self)
def start(iface): ''' Starts an interface (iface) in monitor mode Args: iface - The interface to start in monitor mode Either an instance of Interface object, or the name of the interface (string). Returns: Name of the interface put into monitor mode. Throws: Exception - If an interface can't be put into monitor mode ''' # Get interface name from input if type(iface) == Interface: iface = iface.name Airmon.base_interface = iface # Call airmon-ng Color.p("{+} enabling {G}monitor mode{W} on {C}%s{W}... " % iface) (out,err) = Process.call('airmon-ng start %s' % iface) # Find the interface put into monitor mode (if any) mon_iface = None for line in out.split('\n'): if 'monitor mode' in line and 'enabled' in line and ' on ' in line: mon_iface = line.split(' on ')[1] if ']' in mon_iface: mon_iface = mon_iface.split(']')[1] if ')' in mon_iface: mon_iface = mon_iface.split(')')[0] break if mon_iface == None: # Airmon did not enable monitor mode on an interface Color.pl("{R}failed{W}") mon_ifaces = Airmon.get_interfaces_in_monitor_mode() # Assert that there is an interface in monitor mode if len(mon_ifaces) == 0: Color.pl("{R}failed{W}") raise Exception("iwconfig does not see any interfaces in Mode:Monitor") # Assert that the interface enabled by airmon-ng is in monitor mode if mon_iface not in mon_ifaces: Color.pl("{R}failed{W}") raise Exception("iwconfig does not see %s in Mode:Monitor" % mon_iface) # No errors found; the device 'mon_iface' was put into MM. Color.pl("{G}enabled {C}%s{W}" % mon_iface) Configuration.interface = mon_iface return mon_iface
class DeviceLaunchfile(Device): def __init__(self, name, path , packageName, launchfile): super(DeviceLaunchfile, self).__init__(name, path) self._launchFile = self._getLaunchFile(packageName, launchfile) self._process = None def launch(self): # Make sure launch file exists if self._launchFile and os.path.exists(self._launchFile): try: popen = subprocess.Popen(['roslaunch', self._launchFile, 'NAMESPACE:=' + rospy.get_namespace(), 'DEVICE:=' + self._path]) self._process = Process(popen) return True except: pass return False def kill(self): if self._process: self._process.kill() @staticmethod def _getLaunchFile(packageName, launchfile): packageDir = None rospack = rospkg.RosPack() try: packageDir = rospack.get_path(packageName) except rospkg.ResourceNotFound: pass else: return os.path.join(packageDir, 'launch', launchfile) return None
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
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 == 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]
def launch(self): # Make sure launch file exists if self._launchFile and os.path.exists(self._launchFile): try: popen = subprocess.Popen(['roslaunch', self._launchFile, 'NAMESPACE:=' + rospy.get_namespace(), 'DEVICE:=' + self._path]) self._process = Process(popen) return True except: pass return False
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: continue if 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} ({R}%s{O})' % (pname, pid)) os.kill(int(pid), signal.SIGTERM)
def __init__(self, ivs_file=None): self.cracked_file = Configuration.temp() + 'wepkey.txt' # Delete previous cracked files if os.path.exists(self.cracked_file): os.remove(self.cracked_file) command = [ 'aircrack-ng', '-a', '1', '-l', self.cracked_file, ivs_file ] self.pid = Process(command, devnull=True)
def get_interfaces_in_monitor_mode(): ''' Uses 'iwconfig' to find all interfaces in monitor mode Returns: List of interface names that are in monitor mode ''' interfaces = [] (out, err) = Process.call("iwconfig") for line in out.split("\n"): if len(line) == 0: continue if line[0] != ' ': iface = line.split(' ')[0] if '\t' in iface: iface = iface.split('\t')[0] if 'Mode:Monitor' in line and iface not in interfaces: interfaces.append(iface) return interfaces
def forge_packet(xor_file, bssid, station_mac): ''' Forges packet from .xor file ''' forged_file = 'forged.cap' cmd = [ 'packetforge-ng', '-0', '-a', bssid, # Target MAC '-h', station_mac, # Client MAC '-k', '192.168.1.2', # Dest IP '-l', '192.168.1.100', # Source IP '-y', xor_file, # Read PRNG from .xor file '-w', forged_file, # Write to Configuration.interface ] cmd = '"%s"' % '" "'.join(cmd) (out, err) = Process.call(cmd, cwd=Configuration.temp(), shell=True) if out.strip() == 'Wrote packet to: %s' % forged_file: return forged_file else: from Color import Color Color.pl('{!} {R}failed to forge packet from .xor file{W}') Color.pl('output:\n"%s"' % out) return None
def stop(iface): Color.p("{+} {R}disabling {O}monitor mode{R} on {O}%s{W}... " % iface) (out,err) = Process.call('airmon-ng stop %s' % iface) mon_iface = None for line in out.split('\n'): # aircrack-ng 1.2 rc2 if 'monitor mode' in line and 'disabled' in line and ' for ' in line: mon_iface = line.split(' for ')[1] if ']' in mon_iface: mon_iface = mon_iface.split(']')[1] if ')' in mon_iface: mon_iface = mon_iface.split(')')[0] break # aircrack-ng 1.2 rc1 match = re.search('([a-zA-Z0-9]+).*\(removed\)', line) if match: mon_iface = match.groups()[0] break if mon_iface: Color.pl('{R}disabled {O}%s{W}' % mon_iface) else: Color.pl('{O}could not disable on {R}%s{W}' % iface)
class Airodump(object): ''' Wrapper around airodump-ng program ''' def __init__(self, interface=None, channel=None, encryption=None,\ wps=False, target_bssid=None, output_file_prefix='airodump',\ ivs_only=False): ''' Sets up airodump arguments, doesn't start process yet ''' Configuration.initialize() if interface == None: interface = Configuration.interface if interface == None: raise Exception("Wireless interface must be defined (-i)") self.interface = interface self.targets = [] if channel == None: channel = Configuration.target_channel self.channel = channel self.encryption = encryption self.wps = wps self.target_bssid = target_bssid self.output_file_prefix = output_file_prefix self.ivs_only = ivs_only 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 ] if self.channel: command.extend(['-c', str(self.channel)]) 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 def __exit__(self, type, value, traceback): ''' Tearing things down since the context is being exited. Called after 'with Airodump(...)' goes out of scope. ''' # Kill the process self.pid.interrupt() # Delete temp files self.delete_airodump_temp_files() def find_files(self, endswith=None): ''' Finds all files in the temp directory that start with the output_file_prefix ''' result = [] for fil in os.listdir(Configuration.temp()): if fil.startswith(self.output_file_prefix): if not endswith or fil.endswith(endswith): result.append(Configuration.temp() + fil) return result def delete_airodump_temp_files(self): ''' Deletes airodump* files in the temp directory. Also deletes replay_*.cap and *.xor files in pwd. ''' # Remove all temp files for fil in self.find_files(): os.remove(fil) # Remove .cap and .xor files from pwd for fil in os.listdir('.'): if fil.startswith('replay_') and fil.endswith('.cap'): os.remove(fil) if fil.endswith('.xor'): os.remove(fil) def get_targets(self): ''' Parses airodump's CSV file, returns list of Targets ''' # Find the .CSV file csv_filename = None for fil in self.find_files(endswith='-01.csv'): # Found the file csv_filename = fil break if csv_filename == None or not os.path.exists(csv_filename): # No file found return self.targets # Parse the .CSV file targets = Airodump.get_targets_from_csv(csv_filename) # Check targets for WPS capfile = csv_filename[:-3] + 'cap' Wash.check_for_wps_and_update_targets(capfile, targets) # Filter targets based on encryption targets = Airodump.filter_targets(targets) # Sort by power targets.sort(key=lambda x: x.power, reverse=True) self.targets = targets return self.targets @staticmethod def get_targets_from_csv(csv_filename): ''' Returns list of Target objects parsed from CSV file ''' targets = [] import csv with open(csv_filename, 'rb') as csvopen: lines = (line.replace('\0', '') for line in csvopen) csv_reader = csv.reader(lines, delimiter=',') hit_clients = False for row in csv_reader: # Each "row" is a list of fields for a target/client if len(row) == 0: continue if row[0].strip() == 'BSSID': # This is the "header" for the list of Targets hit_clients = False continue elif row[0].strip() == 'Station MAC': # This is the "header" for the list of Clients hit_clients = True continue if hit_clients: # The current row corresponds to a "Client" (computer) client = Client(row) if 'not associated' in client.bssid: # Ignore unassociated clients continue # Add this client to the appropriate Target for t in targets: if t.bssid == client.bssid: t.clients.append(client) break else: # The current row corresponds to a "Target" (router) target = Target(row) if target.essid_len == 0: # Ignore empty/blank ESSIDs continue targets.append(target) return targets @staticmethod def filter_targets(targets): ''' Filters targets based on Configuration ''' result = [] # Filter based on Encryption for target in targets: if 'WEP' in Configuration.encryption_filter and \ 'WEP' in target.encryption: result.append(target) elif 'WPA' in Configuration.encryption_filter and \ 'WPA' in target.encryption: result.append(target) elif 'WPS' in Configuration.encryption_filter and \ target.wps: result.append(target) # Filter based on BSSID/ESSID bssid = Configuration.target_bssid essid = Configuration.target_essid i = 0 while i < len(result): if bssid and result[i].bssid.lower() != bssid.lower(): result.pop(i) continue if essid and result[i].essid.lower() != essid.lower(): result.pop(i) continue i += 1 return result
def crack_handshake(self, handshake, wordlist): '''Tries to crack a handshake. Returns WPA key if found, otherwise None.''' if wordlist is None: Color.pl("{!} {O}Not cracking handshake because" + " wordlist ({R}--dict{O}) is not set") return None elif not os.path.exists(wordlist): Color.pl("{!} {O}Not cracking handshake because" + " wordlist {R}%s{O} was not found" % wordlist) return None Color.pl("\n{+} {C}Cracking WPA Handshake:{W} Using {C}aircrack-ng{W} via" + " {C}%s{W} wordlist" % os.path.split(wordlist)[-1]) key_file = Configuration.temp('wpakey.txt') command = [ "aircrack-ng", "-a", "2", "-w", wordlist, "--bssid", handshake.bssid, "-l", key_file, handshake.capfile ] crack_proc = Process(command) # Report progress of cracking aircrack_nums_re = re.compile(r"(\d+)/(\d+) keys tested.*\(([\d.]+)\s+k/s") aircrack_key_re = re.compile(r"Current passphrase:\s*([^\s].*[^\s])\s*$") num_tried = num_total = 0 percent = num_kps = 0.0 eta_str = "unknown" current_key = '' while crack_proc.poll() is None: line = crack_proc.pid.stdout.readline() match_nums = aircrack_nums_re.search(line) match_keys = aircrack_key_re.search(line) if match_nums: num_tried = int(match_nums.group(1)) num_total = int(match_nums.group(2)) num_kps = float(match_nums.group(3)) eta_seconds = (num_total - num_tried) / num_kps eta_str = Timer.secs_to_str(eta_seconds) percent = 100.0 * float(num_tried) / float(num_total) elif match_keys: current_key = match_keys.group(1) else: continue status = "\r{+} {C}Cracking WPA Handshake: %0.2f%%{W}" % percent status += " ETA: {C}%s{W}" % eta_str status += " @ {C}%0.1fkps{W}" % num_kps #status += " ({C}%d{W}/{C}%d{W} keys)" % (num_tried, num_total) status += " (current key: {C}%s{W})" % current_key Color.clear_entire_line() Color.p(status) Color.pl("") # Check crack result if os.path.exists(key_file): f = open(key_file, "r") key = f.read().strip() f.close() os.remove(key_file) Color.pl("{+} {G}Cracked WPA Handshake{W} PSK: {G}%s{W}\n" % key) return key else: Color.pl("{!} {R}Failed to crack handshake:" + " {O}%s{R} did not contain password{W}" % wordlist.split(os.sep)[-1]) return None