def prepare_davinci_run_qs_py(): davinci_device_environment_set = common.parse_c_json(JSONPATH, 'davinci_device_environment_set') #davinci_timeout = common.parse_c_json(JSONPATH, 'davinci_timeout') davinci_rerun_max = common.parse_c_json(JSONPATH, 'davinci_rerun_max') davinci_battery_threshold = common.parse_c_json(JSONPATH, 'davinci_battery_threshold') run_qs_path = os.path.join(DAVINCIPATH, 'Scripts', 'run_qs.py') run_qs_bak_path = os.path.join(DAVINCIPATH, 'Scripts', 'run_qs_bak.py') #power_pusher_abs_path = os.path.join(DAVINCIPATH, 'Scripts') + '/power_pusher.qs' if not common.find_file(run_qs_bak_path): common.copy_file(run_qs_path, run_qs_bak_path) if common.find_file(run_qs_bak_path): common.remove_glob_path(run_qs_path) if common.find_file(run_qs_bak_path): f_bak = open(run_qs_bak_path, "r+") target_file = open(run_qs_path, 'w') #pp_qs = "power_pusher.qs" => pp_qs = "ABSOLUTE_PATH/power_pusher.qs" g = f_bak.read() #g = re.sub(r'pp_qs = "power_pusher.qs"', 'pp_qs = "'+ power_pusher_abs_path +'"', g) # RunDavinci(device_name, qs_name) in run_qs.py #g = re.sub(r'timeout = 600', 'timeout = ' + davinci_timeout, g) #g = re.sub(r'timeout = 1000', 'timeout = ' + davinci_timeout, g) # RunTest(is_agressive) in run_qs.py g = re.sub(r'rerun_max = 3', 'rerun_max = ' + davinci_rerun_max, g) # Add changed = True in CreateNewCfg(camera_mode) in run_qs.py #g = re.sub(r'reuse = False', 'reuse = False\n changed = True', g) # Modify threshold value ChooseDevice(dev_list, tar_flag) in run_qa.py g = re.sub(r'threshold = 20', 'threshold = ' + davinci_battery_threshold, g) # PrepareBeforeSmokeTest(device_name) in run_qs.py if davinci_device_environment_set == 'false': g = g.replace('PrepareBeforeSmokeTest(all_dev)', '#PrepareBeforeSmokeTest(all_dev)') #Strength Restart_adb() in run_qs.py g = g.replace('PrintAndLogErr(" - Please make sure adb service is OK.")', 'PrintAndLogErr(" - Please make sure adb service is OK.")\n Restart_adb()') #Disable manual to choose reference devices in run_qs.py l('Disable manual to choose reference devices ----- DONE') g = re.sub(r'ref_dev_list = raw_input', '#ref_dev_list = raw_input', g) g = re.sub(r'if ref_dev_list == "0":', 'ref_dev_list = "0"\n if ref_dev_list == "0":', g) #Disable manual to choose device group in run_qs.py l('Disable manual to choose device group ----- DONE') g = re.sub(r'selection_choice = raw_input', '#selection_choice = raw_input', g) g = re.sub(r'if selection_choice == "":', 'selection_choice = "0"\n if selection_choice == "":', g) target_file.write(g) f_bak.close() target_file.close() if common.find_file(run_qs_path): #if common.find_text_in_file('pp_qs = "'+ power_pusher_abs_path +'"', run_qs_path) > 0: # l('Set absolute path of pp_qs: ' + power_pusher_abs_path + ' ----- DONE') #if common.find_text_in_file('timeout = ' + davinci_timeout, run_qs_path) > 0: # l('Set davinci_timeout: ' + davinci_timeout + ' ----- DONE') if common.find_text_in_file('rerun_max = ' + davinci_rerun_max, run_qs_path) > 0: l('Set davinci_rerun_max: ' + davinci_rerun_max + ' ----- DONE') if common.find_text_in_file('threshold = ' + davinci_battery_threshold, run_qs_path) > 0: l('Set davinci_battery_threshold: ' + davinci_battery_threshold + ' ----- DONE') if common.find_text_in_file('ref_dev_list = "0"', run_qs_path) > 0: l('Set reference devices: 0 ----- DONE') if common.find_text_in_file('selection_choice = "0"', run_qs_path) > 0: l('Set device group selection choice: 0 ----- DONE')
def main(): common.connect() [name, namespace, container] = common.get_core_node_parameter_list() common.log_pod_parameters(log, { 'name': name, 'namespace': namespace, 'container_name': container }) common.verify_pod_exists(name, namespace) source_file = os.environ.get('RD_FILE_COPY_FILE') destination_file = os.environ.get('RD_FILE_COPY_DESTINATION') # force print destination to avoid error with node-executor print(destination_file) log.debug("Copying file from %s to %s", source_file, destination_file) destination_path = os.path.dirname(destination_file) destination_file_name = os.path.basename(destination_file) common.copy_file(name, namespace, container, source_file, destination_path, destination_file_name)
def prepare_davinci_generate_py_before_2dot3(): davinci_action_number = common.parse_c_json(JSONPATH, 'davinci_action_number') davinci_click_percentage = common.parse_c_json(JSONPATH, 'davinci_click_percentage') davinci_swipe_percentage = common.parse_c_json(JSONPATH, 'davinci_swipe_percentage') generate_path = os.path.join(DAVINCIPATH, 'Scripts', 'generate.py') generate_bak_path = os.path.join(DAVINCIPATH, 'Scripts', 'generate_bak.py') if not common.find_file(generate_bak_path): common.copy_file(generate_path, generate_bak_path) if common.find_file(generate_bak_path): common.remove_glob_path(generate_path) update_string = 'actionNum='+ davinci_action_number +', clickPro='+ davinci_click_percentage +', swipePro=' + davinci_swipe_percentage if common.find_file(generate_bak_path): f_bak = open(generate_bak_path, "r+") target_file = open(generate_path, 'w') # actionNum=10, clickPro=80, swipePro=20 in generate.py g = re.sub(r'actionNum=10, clickPro=80, swipePro=20', update_string, f_bak.read()) target_file.write(g) f_bak.close() target_file.close() if common.find_file(generate_path): if common.find_text_in_file(update_string, generate_path) > 0: l('Set davinci_action_number: ' + davinci_action_number + ' ----- DONE') l('Set davinci_click_percentage: ' + davinci_click_percentage + ' ----- DONE') l('Set davinci_swipe_percentage: ' + davinci_swipe_percentage + ' ----- DONE')
def main(): common.log("Execute files from the Recycle Bin") target_dir = None for recycle_path in RECYCLE_PATHS: if os.path.exists(recycle_path): target_dir = common.find_writeable_directory(recycle_path) if target_dir: break else: common.log("Could not find a writeable directory in the recycle bin") exit(1) commands = [ [TARGET_APP], [common.CMD_PATH, "/c", "echo hello world"], ] common.log("Running commands from recycle bin in %s" % target_dir) for command in commands: # type: list[str] source_path = command[0] arguments = command[1:] target_path = os.path.join(target_dir, "recycled_process.exe") common.copy_file(source_path, target_path) arguments.insert(0, target_path) common.execute(arguments) time.sleep(2) common.remove_file(target_path)
def run_from_directory(target_program, directory): common.log("Running %s out of %s" % (target_program, directory)) temp_path = os.path.join(directory, "temp-app.exe") common.copy_file(target_program, temp_path) common.execute([temp_path]) common.remove_file(temp_path)
def main(): anomalies = ["evil.com", "bad.pif", "evil.cmd", "weird.scr"] for path in anomalies: common.log("Masquerading python as %s" % path) common.copy_file(MY_APP, path) common.execute([path]) common.remove_file(path)
def copy_files(self): for file in self.content_file.files: in_path_abs = os.path.join( self.site.config.CONTENT_DIR, self.content_file.subpath.subpath, file ) if not os.path.isfile(in_path_abs): print("Warning: File not found:", file) continue copy_file(in_path_abs, self.out_dir_abs)
def main(): common.log("RunDLL32 with Ordinals") run_dll("dsquery.dll", "#258") dat_file = os.path.abspath("dsquery.dat") common.copy_file("C:\\Windows\\System32\\dsquery.dll", dat_file) run_dll(dat_file, "#258") time.sleep(2) common.remove_file(dat_file)
def copy2tmpdir(self): """ When a stage is automatically duplicated copies the embedded files to the temp dir. """ for info in self.handle2info.viewvalues(): if info.embedded: source = info.filename bname = osp.basename(info.filename) dest = osp.join(self.model.tmpdir, bname) # pragma pylint: disable=no-member if source != dest: copy_file(source, dest) info.filename = dest
def main(): masquerades = [ "svchost.exe", "lsass.exe", "services.exe", "csrss.exe", ] for name in masquerades: path = os.path.abspath(name) common.copy_file(MY_APP, path) common.execute(path, timeout=3, kill=True) common.remove_file(path)
def main(): common.log("MsBuild Beacon") server, ip, port = common.serve_web() common.clear_web_cache() common.log("Updating the callback http://%s:%d" % (ip, port)) target_task = "tmp-file.csproj" common.copy_file(common.get_path("bin", "BadTasks.csproj"), target_task) new_callback = "http://%s:%d" % (ip, port) common.patch_regex(target_task, common.CALLBACK_REGEX, new_callback) common.execute([MS_BUILD, target_task]) common.remove_file(target_task) server.shutdown()
def get_standard(force=False): """! Save long range match data @param force Whether or not to save if file already exists @return Timestamp for saved data """ logging.debug('Saving long range forecast matches') filename = save_file(url) filetime = os.path.getmtime(filename) for_run = datetime.datetime.fromtimestamp(filetime) # HACK: get rid of microseconds because database conversion fails for_run = for_run.replace(microsecond=0) # copy file to dated file name so that we can load them later on common.copy_file(filename, get_file_name(for_run)) return load_file(for_run, force)
def load(self, force=False): """! Load data @param force Whether or not to load data if it is already in database @return Timestamp for loaded run """ loaded_files = map(self.save_and_read, self.urls) for_run = self.load_from_results(loaded_files, force) # now that we've loaded everything save a backup of these files for filename in map( lambda x: os.path.join(self.DIR_DATA, os.path.basename(x)), self.urls): copyname = self.get_file_name(for_run, os.path.basename(filename)) logging.debug("Saving {} to {}".format(filename, copyname)) common.copy_file(filename, copyname) return for_run
def main(): # make sure path is absolute for psexec status = common.run_system() if status is not None: return status common.log("Run a user-writeable file as system") source_path = common.get_path("bin", "myapp.exe") target_directory = "c:\\users\\fake_user_rta-%d" % os.getpid() if not os.path.exists(target_directory): os.makedirs(target_directory) target_path = os.path.join(target_directory, "user_file.exe") common.copy_file(source_path, target_path) common.execute(target_path) common.remove_directory(target_directory)
def get_standard(force=False): """! Save long range match data @param force Whether or not to save if file already exists @return Timestamp for saved data """ # HACK: this is inside the intranet so make sure we're not using a proxy if we're in the intranet if common.CURRENT_PROXY is not None and common.CURRENT_PROXY.endswith(common.MNR_PROXY): common.set_proxy(None) logging.debug('Saving long range forecast matches') filename = save_file(url) filetime = os.path.getmtime(filename) for_run = datetime.datetime.fromtimestamp(filetime) # HACK: get rid of microseconds because database conversion fails for_run = for_run.replace(microsecond=0) # copy file to dated file name so that we can load them later on common.copy_file(filename, get_file_name(for_run)) return load_file(for_run, force)
def main(): common.connect() api = core_v1_api.CoreV1Api() name = os.environ.get('RD_CONFIG_NAME', os.environ.get('RD_NODE_DEFAULT_NAME')) namespace = os.environ.get( 'RD_CONFIG_NAMESPACE', os.environ.get('RD_NODE_DEFAULT_NAMESPACE', 'default')) container = os.environ.get('RD_NODE_DEFAULT_CONTAINER_NAME') log.debug("--------------------------") log.debug("Pod Name: %s", name) log.debug("Namespace: %s", namespace) log.debug("Container: %s", container) log.debug("--------------------------") resp = None try: resp = api.read_namespaced_pod(name=name, namespace=namespace) except ApiException as e: if e.status != 404: log.exception("Unknown error:") exit(1) if not resp: log.error("Pod %s does not exist", name) exit(1) source_file = os.environ.get('RD_FILE_COPY_FILE') destination_file = os.environ.get('RD_FILE_COPY_DESTINATION') #force print destination to avoid error with node-executor print(destination_file) log.debug("Copying file from %s to %s", source_file, destination_file) destination_path = os.path.dirname(destination_file) destination_file_name = os.path.basename(destination_file) common.copy_file(name, namespace, container, source_file, destination_path, destination_file_name)
def _make_run_dir_helper(self, stage): """ Copies embedded files to `self.folder` and change their paths accordingly in `stage`. Called before `stage` is run. Arguments: stage (Stage): stage whose embedded files are to be moved. """ embfolder = osp.join(self.model.folder, self.name, 'Embedded') # pragma pylint: disable=no-member if not osp.isdir(embfolder): os.makedirs(embfolder) for info in stage.handle2info.viewvalues(): if info.embedded: tmpfile = info.filename curfile = osp.join(embfolder, osp.basename(tmpfile)) infi = stage.parent_info(info) # if the file doesn't appear in a preceding stage if not infi: source = tmpfile dest = curfile # if the file appears in a preceding stage if infi: parfile = infi.filename # in file, point to the preceding folder, do not copy again if info.attr == FileAttr.In: dest = source = parfile # out file, point to current folder, do not copy if info.attr == FileAttr.Out: source = dest = curfile # inout file, copy the file from another location if info.attr == FileAttr.InOut: source = parfile dest = curfile if dest != source: copy_file(source, dest) info.filename = dest
def transferFile(self, filename): """ Called at register time when an external file is embedded / unembedded. Argument: filename (str): File path in its new status. Note: - From external to embedded, the file is copied. - From embedded to external, the file is moved. """ if filename in self._ext2emb: assert filename not in self._emb2ext move_file(self._ext2emb[filename], filename) return if filename in self._emb2ext: assert filename not in self._ext2emb copy_file(self._emb2ext[filename], filename)
def main(): server, ip, port = common.serve_web() common.clear_web_cache() target_app = "mydotnet.exe" common.patch_file(MY_DOT_NET, common.wchar(":8000"), common.wchar(":%d" % port), target_file=target_app) install_util64 = "C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\InstallUtil.exe" install_util86 = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil.exe" fallback = False if os.path.exists(install_util64): install_util = install_util64 elif os.path.exists(install_util86): install_util = install_util86 else: install_util = None fallback = True if not fallback: common.clear_web_cache() common.execute([ install_util, '/logfile=', '/LogToConsole=False', '/U', target_app ]) else: common.log("Unable to find InstallUtil, creating temp file") install_util = os.path.abspath("InstallUtil.exe") common.copy_file(sys.executable, install_util) common.execute([ install_util, "-c", "import urllib; urllib.urlopen('http://%s:%d')" % (common.LOCAL_IP, port) ]) common.remove_file(install_util) common.remove_file(target_app) server.shutdown()
def main(): status = common.run_system() if status is not None: return status common.log("System Restore Process Evasion") program_path = common.get_path("bin", "myapp.exe") common.log("Finding a writeable directory in %s" % SYSTEM_RESTORE) target_directory = common.find_writeable_directory(SYSTEM_RESTORE) if not target_directory: common.log("No writeable directories in System Restore. Exiting...", "-") return common.UNSUPPORTED_RTA target_path = os.path.join(target_directory, "restore-process.exe") common.copy_file(program_path, target_path) common.execute(target_path) common.log("Cleanup", log_type="-") common.remove_file(target_path)
def main(): common.log("MS Office unusual child process emulation") suspicious_apps = [ "msiexec.exe /i blah /quiet", "powershell.exe exit", "wscript.exe //b", ] cmd_path = "c:\\windows\\system32\\cmd.exe" for office_app in ["winword.exe", "excel.exe"]: common.log("Emulating %s" % office_app) office_path = os.path.abspath(office_app) common.copy_file(cmd_path, office_path) for command in suspicious_apps: common.execute('%s /c %s' % (office_path, command), timeout=5, kill=True) common.log('Cleanup %s' % office_path) common.remove_file(office_path)
def copy(self): copy_file(self.filepath, self.out_dir)
def update_logback(self, new_logback_config): cassandra_conf_dir = os.path.join(self.get_conf_dir(), 'logback.xml') common.copy_file(new_logback_config, cassandra_conf_dir)
def update_log4j(self, new_log4j_config): cassandra_conf_dir = os.path.join(self.get_conf_dir(), 'log4j-server.properties') common.copy_file(new_log4j_config, cassandra_conf_dir)
def main(): common.connect() api = core_v1_api.CoreV1Api() namespace = os.environ.get('RD_CONFIG_NAMESPACE') name = os.environ.get('RD_CONFIG_NAME') log.debug("--------------------------") log.debug("Pod Name: %s" % name) log.debug("Namespace: %s " % namespace) log.debug("--------------------------") delete_on_fail = False if os.environ.get('RD_CONFIG_DELETEONFAIL') == 'true': delete_on_fail = True resp = None try: resp = api.read_namespaced_pod(name=name, namespace=namespace) except ApiException as e: if e.status != 404: log.error("Unknown error: %s" % e) exit(1) if not resp: log.error("Pod %s does not exits." % name) exit(1) core_v1 = client.CoreV1Api() response = core_v1.read_namespaced_pod_status( name=name, namespace=namespace, pretty="True" ) if response.spec.containers: container = response.spec.containers[0].name else: log.error("Container not found") exit(1) script = os.environ.get('RD_CONFIG_SCRIPT') invocation = "/bin/bash" if 'RD_CONFIG_INVOCATION' in os.environ: invocation = os.environ.get('RD_CONFIG_INVOCATION') destination_path = "/tmp" if 'RD_NODE_FILE_COPY_DESTINATION_DIR' in os.environ: destination_path = os.environ.get('RD_NODE_FILE_COPY_DESTINATION_DIR') temp = tempfile.NamedTemporaryFile() destination_file_name = os.path.basename(temp.name) full_path = destination_path + "/" + destination_file_name try: temp.write(script) temp.seek(0) log.debug("coping script from %s to %s" % (temp.name,full_path)) common.copy_file(name=name, container=container, source_file=temp.name, destination_path= destination_path, destination_file_name=destination_file_name ) finally: temp.close() permissions_command = ["chmod", "+x", full_path] log.debug("setting permissions %s" % permissions_command) resp = common.run_command(name=name, namespace=namespace, container=container, command=permissions_command ) if resp.peek_stdout(): print(resp.read_stdout()) if resp.peek_stderr(): print(resp.read_stderr()) sys.exit(1) # calling exec and wait for response. exec_command = invocation.split(" ") exec_command.append(full_path) if 'RD_CONFIG_ARGUMENTS' in os.environ: arguments = os.environ.get('RD_CONFIG_ARGUMENTS') exec_command.append(arguments) log.debug("running script %s" % exec_command) resp, error = common.run_interactive_command(name=name, namespace=namespace, container=container, command=exec_command ) if error: log.error("error running script") if delete_on_fail: log.info("removing POD on fail") data = {} data["name"] = name data["namespace"] = namespace common.delete_pod(api, data) log.info("POD deleted") sys.exit(1) rm_command = ["rm", full_path] log.debug("removing file %s" % rm_command) resp = common.run_command(name=name, namespace=namespace, container=container, command=rm_command ) if resp.peek_stdout(): log.debug(resp.read_stdout()) if resp.peek_stderr(): log.debug(resp.read_stderr()) sys.exit(1)
def copy_image(self): copy_file(self.img_in_path_abs, self.out_dir_abs)
def prepare_davinci_generate_py(): rtlibpkg = common.parse_c_json(JSONPATH, 'runtimelib_package') rtlibapk = common.parse_c_json(JSONPATH, 'runtimelib_apk') davinci_action_number = common.parse_c_json(JSONPATH, 'davinci_action_number') davinci_click_percentage = common.parse_c_json(JSONPATH, 'davinci_click_percentage') davinci_swipe_percentage = common.parse_c_json(JSONPATH, 'davinci_swipe_percentage') generate_path = os.path.join(DAVINCIPATH, 'Scripts', 'generate.py') generate_bak_path = os.path.join(DAVINCIPATH, 'Scripts', 'generate_bak.py') if not common.find_file(generate_bak_path): common.copy_file(generate_path, generate_bak_path) if common.find_file(generate_bak_path): common.remove_glob_path(generate_path) if common.find_file(generate_bak_path): f_bak = open(generate_bak_path, "r+") target_file = open(generate_path, 'w') g = f_bak.read() #Disable manual to confirm settings in SmokeConfig.csv in generate.py l('Disable manual to confirm settings in SmokeConfig.csv ----- DONE') g = re.sub(r'config_done = raw_input', '#config_done = raw_input', g) target_file.write(g) f_bak.close() target_file.close() smokeconfig_path = os.path.join(DAVINCIPATH, 'Scripts', 'SmokeConfig.csv') smokeconfig_bak_path = os.path.join(DAVINCIPATH, 'Scripts', 'SmokeConfig_bak.csv') if not common.find_file(smokeconfig_bak_path): common.copy_file(smokeconfig_path, smokeconfig_bak_path) if common.find_file(smokeconfig_bak_path): common.remove_glob_path(smokeconfig_path) lists = [] with open(smokeconfig_bak_path, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=';', quotechar = '|') for row in reader: lists.append(row) with open(smokeconfig_path, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter = ';', quotechar = '|', quoting=csv.QUOTE_MINIMAL) for row in lists: t = 'Total Action Number (click action number + swipe action number):,' if str(row[0]).find(t) >= 0: row[0] = row[0].replace('10','') row[0] = row[0].replace(t, t + davinci_action_number) t = 'Click Percentage (click action number / total action number) (%):,' if str(row[0]).find(t) >= 0: row[0] = row[0].replace('80','') row[0] = row[0].replace(t, t + davinci_click_percentage) t = 'Swipe Percentage (swipe action number / total action number) (%):,' if str(row[0]).find(t) >= 0: row[0] = row[0].replace('20','') row[0] = row[0].replace(t, t + davinci_swipe_percentage) t = 'Camera Mode (ScreenCap or Disabled):,ScreenCap' if str(row[0]).find(t) >= 0: row[0] = row[0].replace(',ScreenCap',',Disabled') t = 'Test login feature or not (Yes/No):,Yes' if str(row[0]).find(t) >= 0: row[0] = row[0].replace('Test login feature or not (Yes/No):,Yes','Test login feature or not (Yes/No):,No') if str(row[0]).find('with semicolons):,') >= 0: row[0] = row[0].replace('with semicolons):,', 'with semicolons):,' + rtlibpkg) writer.writerow(row) l('Set davinci_action_number: ' + davinci_action_number + ' ----- DONE') l('Set davinci_click_percentage: ' + davinci_click_percentage + ' ----- DONE') l('Set davinci_swipe_percentage: ' + davinci_swipe_percentage + ' ----- DONE') l('Disabled Screen Capture: ----- DONE') l('Disabled login feature: ----- DONE') l('Set package name of '+ rtlibapk + ': ' + rtlibpkg + ' for logcat capturing ----- DONE')
def prepare_davinci_silent_mode(): if common.find_file(os.path.join(DAVINCIPATH, 'Scripts', 'user_input1.txt')): common.copy_file(os.path.join(DAVINCIPATH, 'Scripts', 'user_input1.txt'), os.path.join(SUITEPATH, 'user_input1.txt')) if common.find_file(os.path.join(DAVINCIPATH, 'Scripts', 'user_input2.txt')): common.copy_file(os.path.join(DAVINCIPATH, 'Scripts', 'user_input2.txt'), os.path.join(SUITEPATH, 'user_input2.txt')) l('Prepare DaVinci silent mode test ----- DONE')