pile_js / CERT-Polska__drakvuf-sandbox.jsonl
Hamhams's picture
commit files to HF hub
c7f4bd0
raw
history blame
143 kB
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_apicalls","parameters":"(self, output_file, pid)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/apicall\/{pid}.json\", output_file.name\n )","docstring":"Download API calls of this process","docstring_summary":"Download API calls of this process","docstring_tokens":["Download","API","calls","of","this","process"],"function":"def get_apicalls(self, output_file, pid):\n \"\"\"Download API calls of this process\"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/apicall\/{pid}.json\", output_file.name\n )","function_tokens":["def","get_apicalls","(","self",",","output_file",",","pid",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/apicall\/{pid}.json\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L15-L19"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_processed","parameters":"(self, output_file, name)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/{name}.json\", output_file.name\n )","docstring":"Download post-process results","docstring_summary":"Download post-process results","docstring_tokens":["Download","post","-","process","results"],"function":"def get_processed(self, output_file, name):\n \"\"\"Download post-process results\"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/{name}.json\", output_file.name\n )","function_tokens":["def","get_processed","(","self",",","output_file",",","name",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/{name}.json\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L21-L25"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.list_logs","parameters":"(self)","argument_list":"","return_statement":"return [x.object_name for x in objects if x.object_name.endswith(\".log\")]","docstring":"List DRAKVUF logs","docstring_summary":"List DRAKVUF logs","docstring_tokens":["List","DRAKVUF","logs"],"function":"def list_logs(self):\n \"\"\"List DRAKVUF logs\"\"\"\n objects = self.minio.list_objects_v2(self.bucket, f\"{self.uid}\/\")\n return [x.object_name for x in objects if x.object_name.endswith(\".log\")]","function_tokens":["def","list_logs","(","self",")",":","objects","=","self",".","minio",".","list_objects_v2","(","self",".","bucket",",","f\"{self.uid}\/\"",")","return","[","x",".","object_name","for","x","in","objects","if","x",".","object_name",".","endswith","(","\".log\"",")","]"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L27-L30"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_log","parameters":"(self, log_type, output_file, headers=None)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket,\n f\"{self.uid}\/{log_type}.log\",\n output_file.name,\n request_headers=headers,\n )","docstring":"Download DRAKVUF log","docstring_summary":"Download DRAKVUF log","docstring_tokens":["Download","DRAKVUF","log"],"function":"def get_log(self, log_type, output_file, headers=None):\n \"\"\"Download DRAKVUF log\"\"\"\n return self.minio.fget_object(\n self.bucket,\n f\"{self.uid}\/{log_type}.log\",\n output_file.name,\n request_headers=headers,\n )","function_tokens":["def","get_log","(","self",",","log_type",",","output_file",",","headers","=","None",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/{log_type}.log\"",",","output_file",".","name",",","request_headers","=","headers",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L32-L39"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_log_index","parameters":"(self, log_type, output_file)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/index\/{log_type}\", output_file.name\n )","docstring":"Download log index, useful for quickly accessing n-th\n log line","docstring_summary":"Download log index, useful for quickly accessing n-th\n log line","docstring_tokens":["Download","log","index","useful","for","quickly","accessing","n","-","th","log","line"],"function":"def get_log_index(self, log_type, output_file):\n \"\"\"\n Download log index, useful for quickly accessing n-th\n log line\n \"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/index\/{log_type}\", output_file.name\n )","function_tokens":["def","get_log_index","(","self",",","log_type",",","output_file",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/index\/{log_type}\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L41-L48"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_pcap_dump","parameters":"(self, output_file)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/dump.pcap\", output_file.name\n )","docstring":"Download dump.pcap file.","docstring_summary":"Download dump.pcap file.","docstring_tokens":["Download","dump",".","pcap","file","."],"function":"def get_pcap_dump(self, output_file):\n \"\"\"Download dump.pcap file.\"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/dump.pcap\", output_file.name\n )","function_tokens":["def","get_pcap_dump","(","self",",","output_file",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/dump.pcap\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L50-L54"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_wireshark_key_file","parameters":"(self, output_file)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/wireshark_key_file.txt\", output_file.name\n )","docstring":"Download tls session keys in format that is accepted by wireshark.","docstring_summary":"Download tls session keys in format that is accepted by wireshark.","docstring_tokens":["Download","tls","session","keys","in","format","that","is","accepted","by","wireshark","."],"function":"def get_wireshark_key_file(self, output_file):\n \"\"\"\n Download tls session keys in format that is accepted by wireshark.\n \"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/wireshark_key_file.txt\", output_file.name\n )","function_tokens":["def","get_wireshark_key_file","(","self",",","output_file",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/wireshark_key_file.txt\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L56-L62"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_dumps","parameters":"(self, output_file)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/dumps.zip\", output_file.name\n )","docstring":"Download memory dumps","docstring_summary":"Download memory dumps","docstring_tokens":["Download","memory","dumps"],"function":"def get_dumps(self, output_file):\n \"\"\"Download memory dumps\"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/dumps.zip\", output_file.name\n )","function_tokens":["def","get_dumps","(","self",",","output_file",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/dumps.zip\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L64-L68"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_graph","parameters":"(self, output_file)","argument_list":"","return_statement":"return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/graph.dot\", output_file.name\n )","docstring":"Download ProcDOT graph","docstring_summary":"Download ProcDOT graph","docstring_tokens":["Download","ProcDOT","graph"],"function":"def get_graph(self, output_file):\n \"\"\"Download ProcDOT graph\"\"\"\n return self.minio.fget_object(\n self.bucket, f\"{self.uid}\/graph.dot\", output_file.name\n )","function_tokens":["def","get_graph","(","self",",","output_file",")",":","return","self",".","minio",".","fget_object","(","self",".","bucket",",","f\"{self.uid}\/graph.dot\"",",","output_file",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L70-L74"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.get_metadata","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Download metadata.json","docstring_summary":"Download metadata.json","docstring_tokens":["Download","metadata",".","json"],"function":"def get_metadata(self):\n \"\"\"Download metadata.json\"\"\"\n try:\n response = None\n response = self.minio.get_object(self.bucket, f\"{self.uid}\/metadata.json\")\n return json.load(response)\n finally:\n # release network resources\n if response is not None:\n response.close()\n response.release_conn()","function_tokens":["def","get_metadata","(","self",")",":","try",":","response","=","None","response","=","self",".","minio",".","get_object","(","self",".","bucket",",","f\"{self.uid}\/metadata.json\"",")","return","json",".","load","(","response",")","finally",":","# release network resources","if","response","is","not","None",":","response",".","close","(",")","response",".","release_conn","(",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L76-L86"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/analysis.py","language":"python","identifier":"AnalysisProxy.enumerate","parameters":"(self)","argument_list":"","return_statement":"return map(\n lambda obj: AnalysisProxy(self.minio, obj.object_name.strip(\"\/\")),\n self.minio.list_objects_v2(self.bucket),\n )","docstring":"Return iterator over all analyses stored in the bucket","docstring_summary":"Return iterator over all analyses stored in the bucket","docstring_tokens":["Return","iterator","over","all","analyses","stored","in","the","bucket"],"function":"def enumerate(self):\n \"\"\"Return iterator over all analyses stored in the bucket\"\"\"\n return map(\n lambda obj: AnalysisProxy(self.minio, obj.object_name.strip(\"\/\")),\n self.minio.list_objects_v2(self.bucket),\n )","function_tokens":["def","enumerate","(","self",")",":","return","map","(","lambda","obj",":","AnalysisProxy","(","self",".","minio",",","obj",".","object_name",".","strip","(","\"\/\"",")",")",",","self",".","minio",".","list_objects_v2","(","self",".","bucket",")",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/analysis.py#L88-L93"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/app.py","language":"python","identifier":"update_metadata_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"Scans whole MinIO bucket and fetch missing metadata files","docstring_summary":"Scans whole MinIO bucket and fetch missing metadata files","docstring_tokens":["Scans","whole","MinIO","bucket","and","fetch","missing","metadata","files"],"function":"def update_metadata_cache():\n \"\"\"Scans whole MinIO bucket and fetch missing metadata files\"\"\"\n for analysis in AnalysisProxy(minio, None).enumerate():\n try:\n get_analysis_metadata(analysis.uid)\n except NoSuchKey:\n # Well, we tried. Too bad\n pass","function_tokens":["def","update_metadata_cache","(",")",":","for","analysis","in","AnalysisProxy","(","minio",",","None",")",".","enumerate","(",")",":","try",":","get_analysis_metadata","(","analysis",".","uid",")","except","NoSuchKey",":","# Well, we tried. Too bad","pass"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/app.py#L30-L37"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/app.py","language":"python","identifier":"pcap_dump","parameters":"(task_uid)","argument_list":"","return_statement":"","docstring":"Return archaive containing dump.pcap along with extracted tls sessions\n keys in format acceptable by wireshark.","docstring_summary":"Return archaive containing dump.pcap along with extracted tls sessions\n keys in format acceptable by wireshark.","docstring_tokens":["Return","archaive","containing","dump",".","pcap","along","with","extracted","tls","sessions","keys","in","format","acceptable","by","wireshark","."],"function":"def pcap_dump(task_uid):\n \"\"\"\n Return archaive containing dump.pcap along with extracted tls sessions\n keys in format acceptable by wireshark.\n \"\"\"\n analysis = AnalysisProxy(minio, task_uid)\n try:\n with NamedTemporaryFile() as f_pcap, NamedTemporaryFile() as f_keys, NamedTemporaryFile() as f_archive:\n with ZipFile(f_archive, \"w\", ZIP_DEFLATED) as archive:\n analysis.get_pcap_dump(f_pcap)\n archive.write(f_pcap.name, \"dump.pcap\")\n try:\n analysis.get_wireshark_key_file(f_keys)\n archive.write(f_keys.name, \"dump.keys\")\n except NoSuchKey:\n # No dumped keys.\n pass\n f_archive.seek(0)\n return send_file(f_archive.name, mimetype=\"application\/zip\")\n except NoSuchKey:\n abort(404, description=\"No network traffic avaible.\")","function_tokens":["def","pcap_dump","(","task_uid",")",":","analysis","=","AnalysisProxy","(","minio",",","task_uid",")","try",":","with","NamedTemporaryFile","(",")","as","f_pcap",",","NamedTemporaryFile","(",")","as","f_keys",",","NamedTemporaryFile","(",")","as","f_archive",":","with","ZipFile","(","f_archive",",","\"w\"",",","ZIP_DEFLATED",")","as","archive",":","analysis",".","get_pcap_dump","(","f_pcap",")","archive",".","write","(","f_pcap",".","name",",","\"dump.pcap\"",")","try",":","analysis",".","get_wireshark_key_file","(","f_keys",")","archive",".","write","(","f_keys",".","name",",","\"dump.keys\"",")","except","NoSuchKey",":","# No dumped keys.","pass","f_archive",".","seek","(","0",")","return","send_file","(","f_archive",".","name",",","mimetype","=","\"application\/zip\"",")","except","NoSuchKey",":","abort","(","404",",","description","=","\"No network traffic avaible.\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/app.py#L167-L187"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/postprocess\/pstree.py","language":"python","identifier":"ProcessTree.get_processes","parameters":"(self, pid: int, ts_from: float, ts_to: float)","argument_list":"","return_statement":"return processes","docstring":"Retrieves all processes with given pid that were alive in provided time period: [ts_from, ts_to].","docstring_summary":"Retrieves all processes with given pid that were alive in provided time period: [ts_from, ts_to].","docstring_tokens":["Retrieves","all","processes","with","given","pid","that","were","alive","in","provided","time","period",":","[","ts_from","ts_to","]","."],"function":"def get_processes(self, pid: int, ts_from: float, ts_to: float) -> List[Process]:\n \"\"\"\n Retrieves all processes with given pid that were alive in provided time period: [ts_from, ts_to].\n \"\"\"\n processes = []\n for p in self.processes:\n if (\n pid == p.pid\n and (p.ts_to is None or ts_from <= p.ts_to)\n and p.ts_from <= ts_to\n ):\n processes.append(p)\n return processes","function_tokens":["def","get_processes","(","self",",","pid",":","int",",","ts_from",":","float",",","ts_to",":","float",")","->","List","[","Process","]",":","processes","=","[","]","for","p","in","self",".","processes",":","if","(","pid","==","p",".","pid","and","(","p",".","ts_to","is","None","or","ts_from","<=","p",".","ts_to",")","and","p",".","ts_from","<=","ts_to",")",":","processes",".","append","(","p",")","return","processes"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/postprocess\/pstree.py#L42-L54"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/postprocess\/pstree.py","language":"python","identifier":"ProcessTree.get_single_process","parameters":"(self, pid, ts_from, ts_to)","argument_list":"","return_statement":"return next(iter(processes), None)","docstring":"Retrieves process with given pid that was alive in provided time period.\n Fails if there is more than 1 process that fulfills this condidions.","docstring_summary":"Retrieves process with given pid that was alive in provided time period.\n Fails if there is more than 1 process that fulfills this condidions.","docstring_tokens":["Retrieves","process","with","given","pid","that","was","alive","in","provided","time","period",".","Fails","if","there","is","more","than","1","process","that","fulfills","this","condidions","."],"function":"def get_single_process(self, pid, ts_from, ts_to) -> Optional[Process]:\n \"\"\"\n Retrieves process with given pid that was alive in provided time period.\n Fails if there is more than 1 process that fulfills this condidions.\n \"\"\"\n processes = self.get_processes(pid, ts_from, ts_to)\n if len(processes) > 1:\n raise MultipleProcessesReturned(processes)\n return next(iter(processes), None)","function_tokens":["def","get_single_process","(","self",",","pid",",","ts_from",",","ts_to",")","->","Optional","[","Process","]",":","processes","=","self",".","get_processes","(","pid",",","ts_from",",","ts_to",")","if","len","(","processes",")",">","1",":","raise","MultipleProcessesReturned","(","processes",")","return","next","(","iter","(","processes",")",",","None",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/postprocess\/pstree.py#L56-L64"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakcore\/drakcore\/postprocess\/cache_update.py","language":"python","identifier":"insert_metadata","parameters":"(task: Task, resources: Dict[str, RemoteResource], minio)","argument_list":"","return_statement":"","docstring":"Why is this required?\n Currently there's no easy way to notify web application about the analysis\n being finished. In order for it to find out, user has to explicitly ask\n an endpoint for metadata of given analysis. Otherwise we're be forced to\n query MinIO every time user requests a list of analyses.","docstring_summary":"Why is this required?\n Currently there's no easy way to notify web application about the analysis\n being finished. In order for it to find out, user has to explicitly ask\n an endpoint for metadata of given analysis. Otherwise we're be forced to\n query MinIO every time user requests a list of analyses.","docstring_tokens":["Why","is","this","required?","Currently","there","s","no","easy","way","to","notify","web","application","about","the","analysis","being","finished",".","In","order","for","it","to","find","out","user","has","to","explicitly","ask","an","endpoint","for","metadata","of","given","analysis",".","Otherwise","we","re","be","forced","to","query","MinIO","every","time","user","requests","a","list","of","analyses","."],"function":"def insert_metadata(task: Task, resources: Dict[str, RemoteResource], minio):\n \"\"\"\n Why is this required?\n Currently there's no easy way to notify web application about the analysis\n being finished. In order for it to find out, user has to explicitly ask\n an endpoint for metadata of given analysis. Otherwise we're be forced to\n query MinIO every time user requests a list of analyses.\n \"\"\"\n analysis_uid = task.payload[\"analysis_uid\"]\n # Trigger metadata request, thus pulling it into cache\n get_analysis_metadata(analysis_uid)","function_tokens":["def","insert_metadata","(","task",":","Task",",","resources",":","Dict","[","str",",","RemoteResource","]",",","minio",")",":","analysis_uid","=","task",".","payload","[","\"analysis_uid\"","]","# Trigger metadata request, thus pulling it into cache","get_analysis_metadata","(","analysis_uid",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakcore\/drakcore\/postprocess\/cache_update.py#L8-L18"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/util.py","language":"python","identifier":"try_run","parameters":"(\n list_args: list, msg: str, reraise=True, **kwargs\n)","argument_list":"","return_statement":"return sub","docstring":"Runs subprocess.run in a try except with some default arguments ( which can be overriden by supplying kwargs )\n\n Parameters:\n list_args (list): Subprocess list which will be passed to subprocess.run\n msg (str): A meaningful error message to be raised during non-zero exit code\n reraise (bool):\n True: will raise an Exception with traceback on error\n False: will log a warning on error\n **kwargs: additional parameters to be passed to subprocess.run\n\n Defaults:\n subprocess.run is called with the following arguments by default\n stderr = subprocess.PIPE\n stdout = subprocess.PIPE # to print to console, pass kwargs ( stdout = None )\n check = True\n\n Returns:\n sub (subprocess.CompletedProcess): Object with the completed process\n or\n None: if the subprocess failed and reraise=False","docstring_summary":"Runs subprocess.run in a try except with some default arguments ( which can be overriden by supplying kwargs )","docstring_tokens":["Runs","subprocess",".","run","in","a","try","except","with","some","default","arguments","(","which","can","be","overriden","by","supplying","kwargs",")"],"function":"def try_run(\n list_args: list, msg: str, reraise=True, **kwargs\n) -> subprocess.CompletedProcess:\n \"\"\"\n Runs subprocess.run in a try except with some default arguments ( which can be overriden by supplying kwargs )\n\n Parameters:\n list_args (list): Subprocess list which will be passed to subprocess.run\n msg (str): A meaningful error message to be raised during non-zero exit code\n reraise (bool):\n True: will raise an Exception with traceback on error\n False: will log a warning on error\n **kwargs: additional parameters to be passed to subprocess.run\n\n Defaults:\n subprocess.run is called with the following arguments by default\n stderr = subprocess.PIPE\n stdout = subprocess.PIPE # to print to console, pass kwargs ( stdout = None )\n check = True\n\n Returns:\n sub (subprocess.CompletedProcess): Object with the completed process\n or\n None: if the subprocess failed and reraise=False\n \"\"\"\n\n try:\n kwargs[\"stdout\"]\n except KeyError:\n kwargs[\"stdout\"] = subprocess.PIPE\n\n if kwargs.get(\"stderr\") is None:\n kwargs[\"stderr\"] = subprocess.PIPE\n if kwargs.get(\"check\") is None:\n kwargs[\"check\"] = True\n\n try:\n sub = subprocess.run(list_args, **kwargs)\n except (FileNotFoundError, TypeError) as e:\n logging.debug(\"arguments to subprocess\")\n logging.debug(list_args)\n logging.debug(msg)\n logging.debug(kwargs)\n raise Exception(\"Command not found\") from e\n except subprocess.CalledProcessError as e:\n if e.stdout is not None:\n logging.debug(\"stdout: \\n{}\".format(e.stdout.decode()))\n if e.stderr is not None:\n logging.debug(\"stderr: \\n{}\".format(e.stderr.decode()))\n logging.debug(\"returncode: {}\".format(e.returncode))\n if reraise:\n raise Exception(msg) from e\n else:\n logging.warning(msg)\n logging.debug(traceback.format_exc())\n return None\n return sub","function_tokens":["def","try_run","(","list_args",":","list",",","msg",":","str",",","reraise","=","True",",","*","*","kwargs",")","->","subprocess",".","CompletedProcess",":","try",":","kwargs","[","\"stdout\"","]","except","KeyError",":","kwargs","[","\"stdout\"","]","=","subprocess",".","PIPE","if","kwargs",".","get","(","\"stderr\"",")","is","None",":","kwargs","[","\"stderr\"","]","=","subprocess",".","PIPE","if","kwargs",".","get","(","\"check\"",")","is","None",":","kwargs","[","\"check\"","]","=","True","try",":","sub","=","subprocess",".","run","(","list_args",",","*","*","kwargs",")","except","(","FileNotFoundError",",","TypeError",")","as","e",":","logging",".","debug","(","\"arguments to subprocess\"",")","logging",".","debug","(","list_args",")","logging",".","debug","(","msg",")","logging",".","debug","(","kwargs",")","raise","Exception","(","\"Command not found\"",")","from","e","except","subprocess",".","CalledProcessError","as","e",":","if","e",".","stdout","is","not","None",":","logging",".","debug","(","\"stdout: \\n{}\"",".","format","(","e",".","stdout",".","decode","(",")",")",")","if","e",".","stderr","is","not","None",":","logging",".","debug","(","\"stderr: \\n{}\"",".","format","(","e",".","stderr",".","decode","(",")",")",")","logging",".","debug","(","\"returncode: {}\"",".","format","(","e",".","returncode",")",")","if","reraise",":","raise","Exception","(","msg",")","from","e","else",":","logging",".","warning","(","msg",")","logging",".","debug","(","traceback",".","format_exc","(",")",")","return","None","return","sub"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/util.py#L147-L203"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/vm.py","language":"python","identifier":"VirtualMachine.restore","parameters":"(self, snapshot_path=None, pause=False, **kwargs)","argument_list":"","return_statement":"","docstring":"Restore virtual machine from snapshot.\n :raises: subprocess.CalledProcessError","docstring_summary":"Restore virtual machine from snapshot.\n :raises: subprocess.CalledProcessError","docstring_tokens":["Restore","virtual","machine","from","snapshot",".",":","raises",":","subprocess",".","CalledProcessError"],"function":"def restore(self, snapshot_path=None, pause=False, **kwargs) -> None:\n \"\"\"Restore virtual machine from snapshot.\n :raises: subprocess.CalledProcessError\n \"\"\"\n if self.is_running:\n self.destroy()\n\n args = [\"xl\", \"restore\"]\n\n if snapshot_path is None:\n snapshot_path = Path(VOLUME_DIR) \/ \"snapshot.sav\"\n\n if pause is True:\n args += [\"-p\"]\n\n if kwargs.get(\"stderr\") is None:\n kwargs[\"stderr\"] = subprocess.STDOUT\n\n # we are explicitely passing stdout=None so that things can be print to terminal\n kwargs[\"stdout\"] = kwargs.get(\"stdout\")\n\n # No need to rollback vm-0. Since the state of vm-0\n # is correct by definition.\n if self.vm_id != 0 and self.backend is not None and self.vm_id is not None:\n self.backend.rollback_vm_storage(self.vm_id)\n\n args += [self._cfg_path, snapshot_path]\n logging.info(f\"Restoring VM {self.vm_name}\")\n try_run(args, msg=f\"Failed to restore VM {self.vm_name}\", **kwargs)","function_tokens":["def","restore","(","self",",","snapshot_path","=","None",",","pause","=","False",",","*","*","kwargs",")","->","None",":","if","self",".","is_running",":","self",".","destroy","(",")","args","=","[","\"xl\"",",","\"restore\"","]","if","snapshot_path","is","None",":","snapshot_path","=","Path","(","VOLUME_DIR",")","\/","\"snapshot.sav\"","if","pause","is","True",":","args","+=","[","\"-p\"","]","if","kwargs",".","get","(","\"stderr\"",")","is","None",":","kwargs","[","\"stderr\"","]","=","subprocess",".","STDOUT","# we are explicitely passing stdout=None so that things can be print to terminal","kwargs","[","\"stdout\"","]","=","kwargs",".","get","(","\"stdout\"",")","# No need to rollback vm-0. Since the state of vm-0","# is correct by definition.","if","self",".","vm_id","!=","0","and","self",".","backend","is","not","None","and","self",".","vm_id","is","not","None",":","self",".","backend",".","rollback_vm_storage","(","self",".","vm_id",")","args","+=","[","self",".","_cfg_path",",","snapshot_path","]","logging",".","info","(","f\"Restoring VM {self.vm_name}\"",")","try_run","(","args",",","msg","=","f\"Failed to restore VM {self.vm_name}\"",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/vm.py#L137-L165"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/vm.py","language":"python","identifier":"VirtualMachine.destroy","parameters":"(self, **kwargs)","argument_list":"","return_statement":"","docstring":"Destroy a running virtual machine.\n :raises: subprocess.CalledProcessError","docstring_summary":"Destroy a running virtual machine.\n :raises: subprocess.CalledProcessError","docstring_tokens":["Destroy","a","running","virtual","machine",".",":","raises",":","subprocess",".","CalledProcessError"],"function":"def destroy(self, **kwargs):\n \"\"\"Destroy a running virtual machine.\n :raises: subprocess.CalledProcessError\n \"\"\"\n if self.is_running:\n logging.info(f\"Destroying {self.vm_name}\")\n try_run(\n [\"xl\", \"destroy\", self.vm_name],\n f\"Failed to destroy VM {self.vm_name}\",\n **kwargs,\n )","function_tokens":["def","destroy","(","self",",","*","*","kwargs",")",":","if","self",".","is_running",":","logging",".","info","(","f\"Destroying {self.vm_name}\"",")","try_run","(","[","\"xl\"",",","\"destroy\"",",","self",".","vm_name","]",",","f\"Failed to destroy VM {self.vm_name}\"",",","*","*","kwargs",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/vm.py#L167-L177"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/vm.py","language":"python","identifier":"VirtualMachine.memory_dump","parameters":"(self, compressed_filepath)","argument_list":"","return_statement":"","docstring":"Dump raw memory from running vm using vmi-dump-memory and compress it with gzip\n :raises: subprocess.CalledProcessError","docstring_summary":"Dump raw memory from running vm using vmi-dump-memory and compress it with gzip\n :raises: subprocess.CalledProcessError","docstring_tokens":["Dump","raw","memory","from","running","vm","using","vmi","-","dump","-","memory","and","compress","it","with","gzip",":","raises",":","subprocess",".","CalledProcessError"],"function":"def memory_dump(self, compressed_filepath):\n \"\"\"Dump raw memory from running vm using vmi-dump-memory and compress it with gzip\n :raises: subprocess.CalledProcessError\n \"\"\"\n\n with tempfile.NamedTemporaryFile() as raw_memdump, open(\n compressed_filepath, \"wb\"\n ) as compressed_file:\n\n log.info(f\"Dumping raw memory from {self.vm_name} guest...\")\n try:\n subprocess.run(\n [\"vmi-dump-memory\", self.vm_name, raw_memdump.name], check=True\n )\n except subprocess.CalledProcessError as e:\n log.error(f\"Dumping raw memory from {self.vm_name} failed.\")\n raise e\n\n log.info(f\"Compressing {self.vm_name} guest memory dump...\")\n try:\n subprocess.run(\n [\"gzip\", \"-c\", raw_memdump.name], check=True, stdout=compressed_file\n )\n except subprocess.CalledProcessError as e:\n log.error(f\"Compressing raw memory from {self.vm_name} failed.\")\n raise e","function_tokens":["def","memory_dump","(","self",",","compressed_filepath",")",":","with","tempfile",".","NamedTemporaryFile","(",")","as","raw_memdump",",","open","(","compressed_filepath",",","\"wb\"",")","as","compressed_file",":","log",".","info","(","f\"Dumping raw memory from {self.vm_name} guest...\"",")","try",":","subprocess",".","run","(","[","\"vmi-dump-memory\"",",","self",".","vm_name",",","raw_memdump",".","name","]",",","check","=","True",")","except","subprocess",".","CalledProcessError","as","e",":","log",".","error","(","f\"Dumping raw memory from {self.vm_name} failed.\"",")","raise","e","log",".","info","(","f\"Compressing {self.vm_name} guest memory dump...\"",")","try",":","subprocess",".","run","(","[","\"gzip\"",",","\"-c\"",",","raw_memdump",".","name","]",",","check","=","True",",","stdout","=","compressed_file",")","except","subprocess",".","CalledProcessError","as","e",":","log",".","error","(","f\"Compressing raw memory from {self.vm_name} failed.\"",")","raise","e"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/vm.py#L179-L204"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/main.py","language":"python","identifier":"DrakrunKarton.get_plugin_list","parameters":"(self, quality, requested_plugins)","argument_list":"","return_statement":"return plugin_list","docstring":"Determine final plugin list that will be used during analysis.","docstring_summary":"Determine final plugin list that will be used during analysis.","docstring_tokens":["Determine","final","plugin","list","that","will","be","used","during","analysis","."],"function":"def get_plugin_list(self, quality, requested_plugins):\n \"\"\"\n Determine final plugin list that will be used during analysis.\n \"\"\"\n plugin_list = self.active_plugins[\"_all_\"]\n if quality in self.active_plugins:\n plugin_list = self.active_plugins[quality]\n plugin_list = list(set(plugin_list) & set(requested_plugins))\n\n if \"ipt\" in plugin_list and \"codemon\" not in plugin_list:\n self.log.info(\"Using ipt plugin implies using codemon\")\n plugin_list.append(\"codemon\")\n return plugin_list","function_tokens":["def","get_plugin_list","(","self",",","quality",",","requested_plugins",")",":","plugin_list","=","self",".","active_plugins","[","\"_all_\"","]","if","quality","in","self",".","active_plugins",":","plugin_list","=","self",".","active_plugins","[","quality","]","plugin_list","=","list","(","set","(","plugin_list",")","&","set","(","requested_plugins",")",")","if","\"ipt\"","in","plugin_list","and","\"codemon\"","not","in","plugin_list",":","self",".","log",".","info","(","\"Using ipt plugin implies using codemon\"",")","plugin_list",".","append","(","\"codemon\"",")","return","plugin_list"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/main.py#L201-L213"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/main.py","language":"python","identifier":"DrakrunKarton.reconfigure","parameters":"(cls, config: Dict[str, str])","argument_list":"","return_statement":"","docstring":"Reconfigure DrakrunKarton class","docstring_summary":"Reconfigure DrakrunKarton class","docstring_tokens":["Reconfigure","DrakrunKarton","class"],"function":"def reconfigure(cls, config: Dict[str, str]):\n \"\"\"Reconfigure DrakrunKarton class\"\"\"\n\n def load_json(config, key):\n try:\n return json.loads(config.get(key)) if key in config else None\n except json.JSONDecodeError:\n raise RuntimeError(\n f\"Key '{key}' in section [drakrun] is not valid JSON\"\n )\n\n cls.identity = config.get(\"identity\", cls.DEFAULT_IDENTITY)\n cls.filters = load_json(config, \"filters\") or cls.DEFAULT_FILTERS\n cls.headers = load_json(config, \"headers\") or cls.DEFAULT_HEADERS\n cls.test_headers = load_json(config, \"test_headers\") or cls.DEFAULT_TEST_HEADERS\n cls.test_filters = load_json(config, \"test_filters\") or cls.DEFAULT_TEST_FILTERS\n\n # If testing is enabled, add additional test filters from the configuration\n # or fall back to hardcoded\n if config.getboolean(\"sample_testing\", fallback=False):\n cls.filters.extend(cls.test_filters)","function_tokens":["def","reconfigure","(","cls",",","config",":","Dict","[","str",",","str","]",")",":","def","load_json","(","config",",","key",")",":","try",":","return","json",".","loads","(","config",".","get","(","key",")",")","if","key","in","config","else","None","except","json",".","JSONDecodeError",":","raise","RuntimeError","(","f\"Key '{key}' in section [drakrun] is not valid JSON\"",")","cls",".","identity","=","config",".","get","(","\"identity\"",",","cls",".","DEFAULT_IDENTITY",")","cls",".","filters","=","load_json","(","config",",","\"filters\"",")","or","cls",".","DEFAULT_FILTERS","cls",".","headers","=","load_json","(","config",",","\"headers\"",")","or","cls",".","DEFAULT_HEADERS","cls",".","test_headers","=","load_json","(","config",",","\"test_headers\"",")","or","cls",".","DEFAULT_TEST_HEADERS","cls",".","test_filters","=","load_json","(","config",",","\"test_filters\"",")","or","cls",".","DEFAULT_TEST_FILTERS","# If testing is enabled, add additional test filters from the configuration","# or fall back to hardcoded","if","config",".","getboolean","(","\"sample_testing\"",",","fallback","=","False",")",":","cls",".","filters",".","extend","(","cls",".","test_filters",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/main.py#L216-L236"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/main.py","language":"python","identifier":"DrakrunKarton._get_base_from_drakrun_dump","parameters":"(self, dump_name)","argument_list":"","return_statement":"return hex(int(dump_name.split(\"_\")[0], 16))","docstring":"Drakrun dumps come in form: <base>_<hash> e.g. 405000_688f58c58d798ecb,\n that can be read as a dump from address 0x405000 with a content hash\n equal to 688f58c58d798ecb.","docstring_summary":"Drakrun dumps come in form: <base>_<hash> e.g. 405000_688f58c58d798ecb,\n that can be read as a dump from address 0x405000 with a content hash\n equal to 688f58c58d798ecb.","docstring_tokens":["Drakrun","dumps","come","in","form",":","<base",">","_<hash",">","e",".","g",".","405000_688f58c58d798ecb","that","can","be","read","as","a","dump","from","address","0x405000","with","a","content","hash","equal","to","688f58c58d798ecb","."],"function":"def _get_base_from_drakrun_dump(self, dump_name):\n \"\"\"\n Drakrun dumps come in form: <base>_<hash> e.g. 405000_688f58c58d798ecb,\n that can be read as a dump from address 0x405000 with a content hash\n equal to 688f58c58d798ecb.\n \"\"\"\n return hex(int(dump_name.split(\"_\")[0], 16))","function_tokens":["def","_get_base_from_drakrun_dump","(","self",",","dump_name",")",":","return","hex","(","int","(","dump_name",".","split","(","\"_\"",")","[","0","]",",","16",")",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/main.py#L325-L331"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/main.py","language":"python","identifier":"DrakrunKarton.update_vnc_info","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Put analysis ID -> drakrun node mapping into Redis.\n Required to know where to connect VNC client","docstring_summary":"Put analysis ID -> drakrun node mapping into Redis.\n Required to know where to connect VNC client","docstring_tokens":["Put","analysis","ID","-",">","drakrun","node","mapping","into","Redis",".","Required","to","know","where","to","connect","VNC","client"],"function":"def update_vnc_info(self):\n \"\"\"\n Put analysis ID -> drakrun node mapping into Redis.\n Required to know where to connect VNC client\n \"\"\"\n self.backend.redis.set(\n f\"drakvnc:{self.analysis_uid}\", self.instance_id, ex=3600 # 1h\n )","function_tokens":["def","update_vnc_info","(","self",")",":","self",".","backend",".","redis",".","set","(","f\"drakvnc:{self.analysis_uid}\"",",","self",".","instance_id",",","ex","=","3600","# 1h",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/main.py#L333-L340"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/main.py","language":"python","identifier":"DrakrunKarton.send_raw_analysis","parameters":"(self, sample, outdir, metadata, dumps_metadata, quality)","argument_list":"","return_statement":"","docstring":"Offload drakrun-prod by sending raw analysis output to be processed by\n drakrun.processor.","docstring_summary":"Offload drakrun-prod by sending raw analysis output to be processed by\n drakrun.processor.","docstring_tokens":["Offload","drakrun","-","prod","by","sending","raw","analysis","output","to","be","processed","by","drakrun",".","processor","."],"function":"def send_raw_analysis(self, sample, outdir, metadata, dumps_metadata, quality):\n \"\"\"\n Offload drakrun-prod by sending raw analysis output to be processed by\n drakrun.processor.\n \"\"\"\n\n if self.test_run:\n headers = dict(self.test_headers)\n else:\n headers = dict(self.headers)\n\n headers[\"quality\"] = quality\n\n task = Task(headers, payload=metadata)\n task.add_payload(\"sample\", sample)\n task.add_payload(\"dumps_metadata\", dumps_metadata)\n\n if self.test_run:\n task.add_payload(\"testcase\", self.current_task.payload[\"testcase\"])\n\n if self.config.config.getboolean(\"drakrun\", \"attach_profiles\", fallback=False):\n self.log.info(\"Uploading profiles...\")\n task.add_payload(\"profiles\", self.build_profile_payload())\n\n if self.config.config.getboolean(\n \"drakrun\", \"attach_apiscout_profile\", fallback=False\n ):\n self.log.info(\"Uploading static ApiScout profile...\")\n task.add_payload(\n \"static_apiscout_profile.json\",\n LocalResource(\n name=\"static_apiscout_profile.json\",\n path=Path(APISCOUT_PROFILE_DIR) \/ \"static_apiscout_profile.json\",\n ),\n )\n\n self.log.info(\"Uploading artifacts...\")\n for resource in self.upload_artifacts(self.analysis_uid, outdir):\n task.add_payload(resource.name, resource)\n\n self.send_task(task)","function_tokens":["def","send_raw_analysis","(","self",",","sample",",","outdir",",","metadata",",","dumps_metadata",",","quality",")",":","if","self",".","test_run",":","headers","=","dict","(","self",".","test_headers",")","else",":","headers","=","dict","(","self",".","headers",")","headers","[","\"quality\"","]","=","quality","task","=","Task","(","headers",",","payload","=","metadata",")","task",".","add_payload","(","\"sample\"",",","sample",")","task",".","add_payload","(","\"dumps_metadata\"",",","dumps_metadata",")","if","self",".","test_run",":","task",".","add_payload","(","\"testcase\"",",","self",".","current_task",".","payload","[","\"testcase\"","]",")","if","self",".","config",".","config",".","getboolean","(","\"drakrun\"",",","\"attach_profiles\"",",","fallback","=","False",")",":","self",".","log",".","info","(","\"Uploading profiles...\"",")","task",".","add_payload","(","\"profiles\"",",","self",".","build_profile_payload","(",")",")","if","self",".","config",".","config",".","getboolean","(","\"drakrun\"",",","\"attach_apiscout_profile\"",",","fallback","=","False",")",":","self",".","log",".","info","(","\"Uploading static ApiScout profile...\"",")","task",".","add_payload","(","\"static_apiscout_profile.json\"",",","LocalResource","(","name","=","\"static_apiscout_profile.json\"",",","path","=","Path","(","APISCOUT_PROFILE_DIR",")","\/","\"static_apiscout_profile.json\"",",",")",",",")","self",".","log",".","info","(","\"Uploading artifacts...\"",")","for","resource","in","self",".","upload_artifacts","(","self",".","analysis_uid",",","outdir",")",":","task",".","add_payload","(","resource",".","name",",","resource",")","self",".","send_task","(","task",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/main.py#L389-L429"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/injector.py","language":"python","identifier":"Injector._get_cmdline_generic","parameters":"(self, method: str)","argument_list":"","return_statement":"return [\n \"injector\",\n \"-o\",\n \"json\",\n \"-d\",\n self.vm_name,\n \"-r\",\n self.kernel_profile,\n \"-i\",\n str(self.runtime_info.inject_pid),\n \"-k\",\n hex(self.runtime_info.vmi_offsets.kpgd),\n \"-m\",\n method,\n ]","docstring":"Build base command line for all injection methods","docstring_summary":"Build base command line for all injection methods","docstring_tokens":["Build","base","command","line","for","all","injection","methods"],"function":"def _get_cmdline_generic(self, method: str) -> List[str]:\n \"\"\"Build base command line for all injection methods\"\"\"\n return [\n \"injector\",\n \"-o\",\n \"json\",\n \"-d\",\n self.vm_name,\n \"-r\",\n self.kernel_profile,\n \"-i\",\n str(self.runtime_info.inject_pid),\n \"-k\",\n hex(self.runtime_info.vmi_offsets.kpgd),\n \"-m\",\n method,\n ]","function_tokens":["def","_get_cmdline_generic","(","self",",","method",":","str",")","->","List","[","str","]",":","return","[","\"injector\"",",","\"-o\"",",","\"json\"",",","\"-d\"",",","self",".","vm_name",",","\"-r\"",",","self",".","kernel_profile",",","\"-i\"",",","str","(","self",".","runtime_info",".","inject_pid",")",",","\"-k\"",",","hex","(","self",".","runtime_info",".","vmi_offsets",".","kpgd",")",",","\"-m\"",",","method",",","]"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/injector.py#L15-L31"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/injector.py","language":"python","identifier":"Injector.write_file","parameters":"(\n self, local_path: str, remote_path: str, timeout: int = 60\n )","argument_list":"","return_statement":"return subprocess.run(\n injector_cmd, stdout=subprocess.PIPE, timeout=timeout, check=True\n )","docstring":"Copy local file to the VM","docstring_summary":"Copy local file to the VM","docstring_tokens":["Copy","local","file","to","the","VM"],"function":"def write_file(\n self, local_path: str, remote_path: str, timeout: int = 60\n ) -> subprocess.CompletedProcess:\n \"\"\"Copy local file to the VM\"\"\"\n injector_cmd = self._get_cmdline_writefile(local_path, remote_path)\n return subprocess.run(\n injector_cmd, stdout=subprocess.PIPE, timeout=timeout, check=True\n )","function_tokens":["def","write_file","(","self",",","local_path",":","str",",","remote_path",":","str",",","timeout",":","int","=","60",")","->","subprocess",".","CompletedProcess",":","injector_cmd","=","self",".","_get_cmdline_writefile","(","local_path",",","remote_path",")","return","subprocess",".","run","(","injector_cmd",",","stdout","=","subprocess",".","PIPE",",","timeout","=","timeout",",","check","=","True",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/injector.py#L52-L59"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/injector.py","language":"python","identifier":"Injector.read_file","parameters":"(\n self, remote_path: str, local_path: str, timeout: int = 60\n )","argument_list":"","return_statement":"return subprocess.run(injector_cmd, timeout=timeout, capture_output=True)","docstring":"Copy VM file to local","docstring_summary":"Copy VM file to local","docstring_tokens":["Copy","VM","file","to","local"],"function":"def read_file(\n self, remote_path: str, local_path: str, timeout: int = 60\n ) -> subprocess.CompletedProcess:\n \"\"\"Copy VM file to local\"\"\"\n injector_cmd = self._get_cmdline_readfile(remote_path, local_path)\n return subprocess.run(injector_cmd, timeout=timeout, capture_output=True)","function_tokens":["def","read_file","(","self",",","remote_path",":","str",",","local_path",":","str",",","timeout",":","int","=","60",")","->","subprocess",".","CompletedProcess",":","injector_cmd","=","self",".","_get_cmdline_readfile","(","remote_path",",","local_path",")","return","subprocess",".","run","(","injector_cmd",",","timeout","=","timeout",",","capture_output","=","True",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/injector.py#L61-L66"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/injector.py","language":"python","identifier":"Injector.create_process","parameters":"(\n self, cmdline: str, wait: bool = False, timeout: int = 60\n )","argument_list":"","return_statement":"return subprocess.run(injector_cmd, check=True)","docstring":"Create a process inside the VM with given command line","docstring_summary":"Create a process inside the VM with given command line","docstring_tokens":["Create","a","process","inside","the","VM","with","given","command","line"],"function":"def create_process(\n self, cmdline: str, wait: bool = False, timeout: int = 60\n ) -> subprocess.CompletedProcess:\n injector_cmd = self._get_cmdline_createproc(cmdline, wait=wait)\n \"\"\" Create a process inside the VM with given command line \"\"\"\n return subprocess.run(injector_cmd, check=True)","function_tokens":["def","create_process","(","self",",","cmdline",":","str",",","wait",":","bool","=","False",",","timeout",":","int","=","60",")","->","subprocess",".","CompletedProcess",":","injector_cmd","=","self",".","_get_cmdline_createproc","(","cmdline",",","wait","=","wait",")","return","subprocess",".","run","(","injector_cmd",",","check","=","True",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/injector.py#L68-L73"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/apiscout.py","language":"python","identifier":"get_product_version","parameters":"(pe: pefile.PE)","argument_list":"","return_statement":"","docstring":"Based on https:\/\/stackoverflow.com\/a\/16076661\/12452744","docstring_summary":"Based on https:\/\/stackoverflow.com\/a\/16076661\/12452744","docstring_tokens":["Based","on","https",":","\/\/","stackoverflow",".","com","\/","a","\/","16076661","\/","12452744"],"function":"def get_product_version(pe: pefile.PE) -> str:\n \"\"\"\n Based on https:\/\/stackoverflow.com\/a\/16076661\/12452744\n \"\"\"\n\n def LOWORD(dword):\n return dword & 0x0000FFFF\n\n def HIWORD(dword):\n return dword >> 16\n\n if len(pe.VS_FIXEDFILEINFO) != 1:\n log.error(\"Unsupported case: len(pe.VS_FIXEDFILEINFO) != 1\")\n return None\n try:\n ms = pe.VS_FIXEDFILEINFO[0].ProductVersionMS\n ls = pe.VS_FIXEDFILEINFO[0].ProductVersionLS\n return \"{}.{}.{}.{}\".format(HIWORD(ms), LOWORD(ms), HIWORD(ls), LOWORD(ls))\n except AttributeError:\n log.exception(\"\")\n return None","function_tokens":["def","get_product_version","(","pe",":","pefile",".","PE",")","->","str",":","def","LOWORD","(","dword",")",":","return","dword","&","0x0000FFFF","def","HIWORD","(","dword",")",":","return","dword",">>","16","if","len","(","pe",".","VS_FIXEDFILEINFO",")","!=","1",":","log",".","error","(","\"Unsupported case: len(pe.VS_FIXEDFILEINFO) != 1\"",")","return","None","try",":","ms","=","pe",".","VS_FIXEDFILEINFO","[","0","]",".","ProductVersionMS","ls","=","pe",".","VS_FIXEDFILEINFO","[","0","]",".","ProductVersionLS","return","\"{}.{}.{}.{}\"",".","format","(","HIWORD","(","ms",")",",","LOWORD","(","ms",")",",","HIWORD","(","ls",")",",","LOWORD","(","ls",")",")","except","AttributeError",":","log",".","exception","(","\"\"",")","return","None"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/apiscout.py#L24-L44"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/apiscout.py","language":"python","identifier":"make_static_apiscout_profile_for_dll","parameters":"(filepath: str)","argument_list":"","return_statement":"return dll_entry","docstring":"Based on https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L99-L127","docstring_summary":"Based on https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L99-L127","docstring_tokens":["Based","on","https",":","\/\/","github",".","com","\/","danielplohmann","\/","apiscout","\/","blob","\/","0fca2eefa5b557b05eb77ab7a3246825f7aa71c3","\/","apiscout","\/","db_builder","\/","DatabaseBuilder",".","py#L99","-","L127"],"function":"def make_static_apiscout_profile_for_dll(filepath: str) -> Dict[str, Any]:\n \"\"\"\n Based on https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L99-L127\n \"\"\"\n pe = pefile.PE(filepath, fast_load=True)\n pe.parse_data_directories(\n directories=[\n pefile.DIRECTORY_ENTRY[\"IMAGE_DIRECTORY_ENTRY_EXPORT\"],\n pefile.DIRECTORY_ENTRY[\"IMAGE_DIRECTORY_ENTRY_RESOURCE\"],\n ]\n )\n\n dll_entry = {}\n dll_entry[\"base_address\"] = pe.OPTIONAL_HEADER.ImageBase\n dll_entry[\"bitness\"] = get_bitness(pe)\n dll_entry[\"version\"] = get_product_version(pe) or \"0.0.0.0\"\n dll_entry[\"filepath\"] = filepath\n dll_entry[\"aslr_offset\"] = 0\n dll_entry[\"exports\"] = []\n if not hasattr(pe, \"DIRECTORY_ENTRY_EXPORT\"):\n if pe.is_driver():\n return dll_entry\n raise RuntimeError(f\"DIRECTORY_ENTRY_EXPORT not found in '{filepath}'\")\n for exp in sorted(pe.DIRECTORY_ENTRY_EXPORT.symbols, key=attrgetter(\"address\")):\n export_info = {}\n\n export_info[\"address\"] = exp.address\n if exp.name is None:\n export_info[\"name\"] = \"None\"\n else:\n export_info[\"name\"] = exp.name.decode()\n export_info[\"ordinal\"] = exp.ordinal\n dll_entry[\"exports\"].append(export_info)\n\n return dll_entry","function_tokens":["def","make_static_apiscout_profile_for_dll","(","filepath",":","str",")","->","Dict","[","str",",","Any","]",":","pe","=","pefile",".","PE","(","filepath",",","fast_load","=","True",")","pe",".","parse_data_directories","(","directories","=","[","pefile",".","DIRECTORY_ENTRY","[","\"IMAGE_DIRECTORY_ENTRY_EXPORT\"","]",",","pefile",".","DIRECTORY_ENTRY","[","\"IMAGE_DIRECTORY_ENTRY_RESOURCE\"","]",",","]",")","dll_entry","=","{","}","dll_entry","[","\"base_address\"","]","=","pe",".","OPTIONAL_HEADER",".","ImageBase","dll_entry","[","\"bitness\"","]","=","get_bitness","(","pe",")","dll_entry","[","\"version\"","]","=","get_product_version","(","pe",")","or","\"0.0.0.0\"","dll_entry","[","\"filepath\"","]","=","filepath","dll_entry","[","\"aslr_offset\"","]","=","0","dll_entry","[","\"exports\"","]","=","[","]","if","not","hasattr","(","pe",",","\"DIRECTORY_ENTRY_EXPORT\"",")",":","if","pe",".","is_driver","(",")",":","return","dll_entry","raise","RuntimeError","(","f\"DIRECTORY_ENTRY_EXPORT not found in '{filepath}'\"",")","for","exp","in","sorted","(","pe",".","DIRECTORY_ENTRY_EXPORT",".","symbols",",","key","=","attrgetter","(","\"address\"",")",")",":","export_info","=","{","}","export_info","[","\"address\"","]","=","exp",".","address","if","exp",".","name","is","None",":","export_info","[","\"name\"","]","=","\"None\"","else",":","export_info","[","\"name\"","]","=","exp",".","name",".","decode","(",")","export_info","[","\"ordinal\"","]","=","exp",".","ordinal","dll_entry","[","\"exports\"","]",".","append","(","export_info",")","return","dll_entry"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/apiscout.py#L47-L81"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/apiscout.py","language":"python","identifier":"build_apiscout_dll_key","parameters":"(dll_info: Dict[str, Any])","argument_list":"","return_statement":"return \"{}_{}_{}_0x{:x}\".format(\n dll_info[\"bitness\"], dll_info[\"version\"], filename, dll_info[\"base_address\"]\n )","docstring":"From https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L129-L131","docstring_summary":"From https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L129-L131","docstring_tokens":["From","https",":","\/\/","github",".","com","\/","danielplohmann","\/","apiscout","\/","blob","\/","0fca2eefa5b557b05eb77ab7a3246825f7aa71c3","\/","apiscout","\/","db_builder","\/","DatabaseBuilder",".","py#L129","-","L131"],"function":"def build_apiscout_dll_key(dll_info: Dict[str, Any]) -> str:\n \"\"\"\n From https:\/\/github.com\/danielplohmann\/apiscout\/blob\/0fca2eefa5b557b05eb77ab7a3246825f7aa71c3\/apiscout\/db_builder\/DatabaseBuilder.py#L129-L131\n \"\"\"\n filename = PureWindowsPath(dll_info[\"filepath\"]).name\n return \"{}_{}_{}_0x{:x}\".format(\n dll_info[\"bitness\"], dll_info[\"version\"], filename, dll_info[\"base_address\"]\n )","function_tokens":["def","build_apiscout_dll_key","(","dll_info",":","Dict","[","str",",","Any","]",")","->","str",":","filename","=","PureWindowsPath","(","dll_info","[","\"filepath\"","]",")",".","name","return","\"{}_{}_{}_0x{:x}\"",".","format","(","dll_info","[","\"bitness\"","]",",","dll_info","[","\"version\"","]",",","filename",",","dll_info","[","\"base_address\"","]",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/apiscout.py#L84-L91"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/drakpdb.py","language":"python","identifier":"make_symstore_hash","parameters":"(\n codeview_struct: Union[Container, pdbparse.PDBInfoStream]\n)","argument_list":"","return_statement":"return \"%s%x\" % (guid_str, codeview_struct.Age)","docstring":"If `codeview_struct` is an instance of Container, it should be returned from `CV_RSDS_HEADER.parse()`.","docstring_summary":"If `codeview_struct` is an instance of Container, it should be returned from `CV_RSDS_HEADER.parse()`.","docstring_tokens":["If","codeview_struct","is","an","instance","of","Container","it","should","be","returned","from","CV_RSDS_HEADER",".","parse","()","."],"function":"def make_symstore_hash(\n codeview_struct: Union[Container, pdbparse.PDBInfoStream]\n) -> str:\n \"\"\"\n If `codeview_struct` is an instance of Container, it should be returned from `CV_RSDS_HEADER.parse()`.\n \"\"\"\n guid = codeview_struct.GUID\n guid_str = \"%08x%04x%04x%s\" % (\n guid.Data1,\n guid.Data2,\n guid.Data3,\n guid.Data4.hex(),\n )\n return \"%s%x\" % (guid_str, codeview_struct.Age)","function_tokens":["def","make_symstore_hash","(","codeview_struct",":","Union","[","Container",",","pdbparse",".","PDBInfoStream","]",")","->","str",":","guid","=","codeview_struct",".","GUID","guid_str","=","\"%08x%04x%04x%s\"","%","(","guid",".","Data1",",","guid",".","Data2",",","guid",".","Data3",",","guid",".","Data4",".","hex","(",")",",",")","return","\"%s%x\"","%","(","guid_str",",","codeview_struct",".","Age",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/drakpdb.py#L356-L369"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/drakpdb.py","language":"python","identifier":"Demangler.DemangleName","parameters":"(self, mangled_name)","argument_list":"","return_statement":"return mangled_name","docstring":"Returns the de-mangled name.\n\n At this stage we don't really do proper demangling since we usually dont\n care about the prototype, nor c++ exports. In the future we should\n though.","docstring_summary":"Returns the de-mangled name.","docstring_tokens":["Returns","the","de","-","mangled","name","."],"function":"def DemangleName(self, mangled_name):\n \"\"\"Returns the de-mangled name.\n\n At this stage we don't really do proper demangling since we usually dont\n care about the prototype, nor c++ exports. In the future we should\n though.\n \"\"\"\n m = self.SIMPLE_X86_CALL.match(mangled_name)\n if m:\n # If we see x86 name mangling (_cdecl, __stdcall) with stack sizes\n # of 4 bytes, this is definitely a 32 bit pdb. Sometimes we dont\n # know the architecture of the pdb file for example if we do not\n # have the original binary, but only the GUID as extracted by\n # version_scan.\n # TODO set arch to i386\n return m.group(1)\n\n m = self.FUNCTION_NAME_RE.match(mangled_name)\n if m:\n return m.group(1)\n\n # Strip the first _ from the name. I386 mangled constants have a\n # leading _ but their AMD64 counterparts do not.\n if mangled_name and mangled_name[0] in \"_.\":\n mangled_name = mangled_name[1:]\n\n elif mangled_name.startswith(\"??_C@\"):\n return self._UnpackMangledString(mangled_name)\n\n return mangled_name","function_tokens":["def","DemangleName","(","self",",","mangled_name",")",":","m","=","self",".","SIMPLE_X86_CALL",".","match","(","mangled_name",")","if","m",":","# If we see x86 name mangling (_cdecl, __stdcall) with stack sizes","# of 4 bytes, this is definitely a 32 bit pdb. Sometimes we dont","# know the architecture of the pdb file for example if we do not","# have the original binary, but only the GUID as extracted by","# version_scan.","# TODO set arch to i386","return","m",".","group","(","1",")","m","=","self",".","FUNCTION_NAME_RE",".","match","(","mangled_name",")","if","m",":","return","m",".","group","(","1",")","# Strip the first _ from the name. I386 mangled constants have a","# leading _ but their AMD64 counterparts do not.","if","mangled_name","and","mangled_name","[","0","]","in","\"_.\"",":","mangled_name","=","mangled_name","[","1",":","]","elif","mangled_name",".","startswith","(","\"??_C@\"",")",":","return","self",".","_UnpackMangledString","(","mangled_name",")","return","mangled_name"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/drakpdb.py#L258-L287"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"on_create_rekall_profile_failure","parameters":"(\n msg: str,\n should_raise: bool,\n exception: Exception = None,\n)","argument_list":"","return_statement":"","docstring":"An exception handler for create_rekall_profile\n\n Parameters:\n msg (str): Message to raise\n should_raise (bool): Should it raise an exception or log a warning\n exception (Exception): Exception object which is used for tracebacks\n\n Returns:\n None","docstring_summary":"An exception handler for create_rekall_profile","docstring_tokens":["An","exception","handler","for","create_rekall_profile"],"function":"def on_create_rekall_profile_failure(\n msg: str,\n should_raise: bool,\n exception: Exception = None,\n):\n \"\"\"\n An exception handler for create_rekall_profile\n\n Parameters:\n msg (str): Message to raise\n should_raise (bool): Should it raise an exception or log a warning\n exception (Exception): Exception object which is used for tracebacks\n\n Returns:\n None\n \"\"\"\n if should_raise:\n raise Exception(f\"[REQUIRED DLL] {msg}\") from exception\n else:\n logging.warning(f\"[SKIPPING DLL] {msg}\")\n logging.debug(traceback.format_exc())","function_tokens":["def","on_create_rekall_profile_failure","(","msg",":","str",",","should_raise",":","bool",",","exception",":","Exception","=","None",",",")",":","if","should_raise",":","raise","Exception","(","f\"[REQUIRED DLL] {msg}\"",")","from","exception","else",":","logging",".","warning","(","f\"[SKIPPING DLL] {msg}\"",")","logging",".","debug","(","traceback",".","format_exc","(",")",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L552-L572"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"extract_explorer_pid","parameters":"(\n domain: str, kernel_profile: str, offsets: VmiOffsets, timeout: int = 30\n)","argument_list":"","return_statement":"","docstring":"Call get-explorer-pid helper and get its PID","docstring_summary":"Call get-explorer-pid helper and get its PID","docstring_tokens":["Call","get","-","explorer","-","pid","helper","and","get","its","PID"],"function":"def extract_explorer_pid(\n domain: str, kernel_profile: str, offsets: VmiOffsets, timeout: int = 30\n) -> int:\n \"\"\"Call get-explorer-pid helper and get its PID\"\"\"\n module_dir = os.path.dirname(os.path.realpath(__file__))\n pid_tool = os.path.join(module_dir, \"tools\", \"get-explorer-pid\")\n try:\n explorer_pid_s = subprocess.check_output(\n [pid_tool, domain, kernel_profile, hex(offsets.kpgd)], timeout=timeout\n ).decode(\"utf-8\", \"ignore\")\n\n m = re.search(r\"explorer\\.exe:([0-9]+)\", explorer_pid_s)\n if m is not None:\n return int(m.group(1))\n\n except subprocess.CalledProcessError:\n logging.exception(\"get-explorer-pid exited with an error\")\n except subprocess.TimeoutExpired:\n logging.exception(\"get-explorer-pid timed out\")\n\n raise RuntimeError(\"Extracting explorer PID failed\")","function_tokens":["def","extract_explorer_pid","(","domain",":","str",",","kernel_profile",":","str",",","offsets",":","VmiOffsets",",","timeout",":","int","=","30",")","->","int",":","module_dir","=","os",".","path",".","dirname","(","os",".","path",".","realpath","(","__file__",")",")","pid_tool","=","os",".","path",".","join","(","module_dir",",","\"tools\"",",","\"get-explorer-pid\"",")","try",":","explorer_pid_s","=","subprocess",".","check_output","(","[","pid_tool",",","domain",",","kernel_profile",",","hex","(","offsets",".","kpgd",")","]",",","timeout","=","timeout",")",".","decode","(","\"utf-8\"",",","\"ignore\"",")","m","=","re",".","search","(","r\"explorer\\.exe:([0-9]+)\"",",","explorer_pid_s",")","if","m","is","not","None",":","return","int","(","m",".","group","(","1",")",")","except","subprocess",".","CalledProcessError",":","logging",".","exception","(","\"get-explorer-pid exited with an error\"",")","except","subprocess",".","TimeoutExpired",":","logging",".","exception","(","\"get-explorer-pid timed out\"",")","raise","RuntimeError","(","\"Extracting explorer PID failed\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L658-L678"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"extract_vmi_offsets","parameters":"(\n domain: str, kernel_profile: str, timeout: int = 30\n)","argument_list":"","return_statement":"","docstring":"Call vmi-win-offsets helper and obtain VmiOffsets values","docstring_summary":"Call vmi-win-offsets helper and obtain VmiOffsets values","docstring_tokens":["Call","vmi","-","win","-","offsets","helper","and","obtain","VmiOffsets","values"],"function":"def extract_vmi_offsets(\n domain: str, kernel_profile: str, timeout: int = 30\n) -> VmiOffsets:\n \"\"\"Call vmi-win-offsets helper and obtain VmiOffsets values\"\"\"\n try:\n output = subprocess.check_output(\n [\"vmi-win-offsets\", \"--name\", domain, \"--json-kernel\", kernel_profile],\n timeout=timeout,\n ).decode(\"utf-8\", \"ignore\")\n\n return VmiOffsets.from_tool_output(output)\n except TypeError:\n logging.exception(\"Invalid output of vmi-win-offsets\")\n except subprocess.CalledProcessError:\n logging.exception(\"vmi-win-offsets exited with an error\")\n except subprocess.TimeoutExpired:\n logging.exception(\"vmi-win-offsets timed out\")\n\n raise RuntimeError(\"Extracting VMI offsets failed\")","function_tokens":["def","extract_vmi_offsets","(","domain",":","str",",","kernel_profile",":","str",",","timeout",":","int","=","30",")","->","VmiOffsets",":","try",":","output","=","subprocess",".","check_output","(","[","\"vmi-win-offsets\"",",","\"--name\"",",","domain",",","\"--json-kernel\"",",","kernel_profile","]",",","timeout","=","timeout",",",")",".","decode","(","\"utf-8\"",",","\"ignore\"",")","return","VmiOffsets",".","from_tool_output","(","output",")","except","TypeError",":","logging",".","exception","(","\"Invalid output of vmi-win-offsets\"",")","except","subprocess",".","CalledProcessError",":","logging",".","exception","(","\"vmi-win-offsets exited with an error\"",")","except","subprocess",".","TimeoutExpired",":","logging",".","exception","(","\"vmi-win-offsets timed out\"",")","raise","RuntimeError","(","\"Extracting VMI offsets failed\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L681-L699"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"create_missing_profiles","parameters":"()","argument_list":"","return_statement":"","docstring":"Creates usermode profiles by restoring vm-1 and extracting the DLLs.\n Assumes that injector is configured properly, i.e. kernel and runtime\n profiles exist and that vm-1 is free to use.","docstring_summary":"Creates usermode profiles by restoring vm-1 and extracting the DLLs.\n Assumes that injector is configured properly, i.e. kernel and runtime\n profiles exist and that vm-1 is free to use.","docstring_tokens":["Creates","usermode","profiles","by","restoring","vm","-","1","and","extracting","the","DLLs",".","Assumes","that","injector","is","configured","properly","i",".","e",".","kernel","and","runtime","profiles","exist","and","that","vm","-","1","is","free","to","use","."],"function":"def create_missing_profiles():\n \"\"\"\n Creates usermode profiles by restoring vm-1 and extracting the DLLs.\n Assumes that injector is configured properly, i.e. kernel and runtime\n profiles exist and that vm-1 is free to use.\n \"\"\"\n\n # Prepare injector\n with open(os.path.join(PROFILE_DIR, \"runtime.json\"), \"r\") as runtime_f:\n runtime_info = RuntimeInfo.load(runtime_f)\n kernel_profile = os.path.join(PROFILE_DIR, \"kernel.json\")\n injector = Injector(\"vm-1\", runtime_info, kernel_profile)\n\n # restore vm-1\n out_interface = conf[\"drakrun\"].get(\"out_interface\", \"\")\n dns_server = conf[\"drakrun\"].get(\"dns_server\", \"\")\n install_info = InstallInfo.load()\n backend = get_storage_backend(install_info)\n\n generate_vm_conf(install_info, 1)\n setup_vm_network(\n vm_id=1, net_enable=False, out_interface=out_interface, dns_server=dns_server\n )\n vm = VirtualMachine(backend, 1)\n vm.restore()\n\n # Ensure that all declared usermode profiles exist\n # This is important when upgrade defines new entries in dll_file_list and compulsory_dll_file_list\n for profile in compulsory_dll_file_list:\n if not profiles_exist(profile.dest):\n create_rekall_profile(injector, profile, True)\n\n for profile in dll_file_list:\n if not profiles_exist(profile.dest):\n try:\n create_rekall_profile(injector, profile)\n except Exception:\n log.exception(\"Unexpected exception from create_rekall_profile!\")\n\n build_os_info(APISCOUT_PROFILE_DIR, vmi_win_guid(vm.vm_name), backend)\n\n dll_basename_list = [dll.dest for dll in dll_file_list]\n static_apiscout_profile = build_static_apiscout_profile(\n APISCOUT_PROFILE_DIR, dll_basename_list\n )\n with open(Path(APISCOUT_PROFILE_DIR) \/ \"static_apiscout_profile.json\", \"w\") as f:\n json.dump(static_apiscout_profile, f)\n\n vm.destroy()\n delete_vm_network(\n vm_id=1, net_enable=False, out_interface=out_interface, dns_server=dns_server\n )","function_tokens":["def","create_missing_profiles","(",")",":","# Prepare injector","with","open","(","os",".","path",".","join","(","PROFILE_DIR",",","\"runtime.json\"",")",",","\"r\"",")","as","runtime_f",":","runtime_info","=","RuntimeInfo",".","load","(","runtime_f",")","kernel_profile","=","os",".","path",".","join","(","PROFILE_DIR",",","\"kernel.json\"",")","injector","=","Injector","(","\"vm-1\"",",","runtime_info",",","kernel_profile",")","# restore vm-1","out_interface","=","conf","[","\"drakrun\"","]",".","get","(","\"out_interface\"",",","\"\"",")","dns_server","=","conf","[","\"drakrun\"","]",".","get","(","\"dns_server\"",",","\"\"",")","install_info","=","InstallInfo",".","load","(",")","backend","=","get_storage_backend","(","install_info",")","generate_vm_conf","(","install_info",",","1",")","setup_vm_network","(","vm_id","=","1",",","net_enable","=","False",",","out_interface","=","out_interface",",","dns_server","=","dns_server",")","vm","=","VirtualMachine","(","backend",",","1",")","vm",".","restore","(",")","# Ensure that all declared usermode profiles exist","# This is important when upgrade defines new entries in dll_file_list and compulsory_dll_file_list","for","profile","in","compulsory_dll_file_list",":","if","not","profiles_exist","(","profile",".","dest",")",":","create_rekall_profile","(","injector",",","profile",",","True",")","for","profile","in","dll_file_list",":","if","not","profiles_exist","(","profile",".","dest",")",":","try",":","create_rekall_profile","(","injector",",","profile",")","except","Exception",":","log",".","exception","(","\"Unexpected exception from create_rekall_profile!\"",")","build_os_info","(","APISCOUT_PROFILE_DIR",",","vmi_win_guid","(","vm",".","vm_name",")",",","backend",")","dll_basename_list","=","[","dll",".","dest","for","dll","in","dll_file_list","]","static_apiscout_profile","=","build_static_apiscout_profile","(","APISCOUT_PROFILE_DIR",",","dll_basename_list",")","with","open","(","Path","(","APISCOUT_PROFILE_DIR",")","\/","\"static_apiscout_profile.json\"",",","\"w\"",")","as","f",":","json",".","dump","(","static_apiscout_profile",",","f",")","vm",".","destroy","(",")","delete_vm_network","(","vm_id","=","1",",","net_enable","=","False",",","out_interface","=","out_interface",",","dns_server","=","dns_server",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L833-L884"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"scale","parameters":"(scale_count)","argument_list":"","return_statement":"","docstring":"Enable or disable additional parallel instances of drakrun service..","docstring_summary":"Enable or disable additional parallel instances of drakrun service..","docstring_tokens":["Enable","or","disable","additional","parallel","instances","of","drakrun","service",".."],"function":"def scale(scale_count):\n \"\"\"Enable or disable additional parallel instances of drakrun service..\"\"\"\n if scale_count < 1:\n raise RuntimeError(\"Invalid value of scale parameter. Must be at least 1.\")\n\n cur_services = set(list(get_enabled_drakruns()))\n new_services = set([f\"drakrun@{i}.service\" for i in range(1, scale_count + 1)])\n\n disable_services = cur_services - new_services\n enable_services = new_services\n\n wait_processes(\n \"disable services\",\n [\n subprocess.Popen(\n [\"systemctl\", \"disable\", service],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n for service in disable_services\n ],\n )\n wait_processes(\n \"enable services\",\n [\n subprocess.Popen(\n [\"systemctl\", \"enable\", service],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n for service in enable_services\n ],\n )\n wait_processes(\n \"start services\",\n [\n subprocess.Popen(\n [\"systemctl\", \"start\", service],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n for service in enable_services\n ],\n )\n wait_processes(\n \"stop services\",\n [\n subprocess.Popen(\n [\"systemctl\", \"stop\", service],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n for service in disable_services\n ],\n )","function_tokens":["def","scale","(","scale_count",")",":","if","scale_count","<","1",":","raise","RuntimeError","(","\"Invalid value of scale parameter. Must be at least 1.\"",")","cur_services","=","set","(","list","(","get_enabled_drakruns","(",")",")",")","new_services","=","set","(","[","f\"drakrun@{i}.service\"","for","i","in","range","(","1",",","scale_count","+","1",")","]",")","disable_services","=","cur_services","-","new_services","enable_services","=","new_services","wait_processes","(","\"disable services\"",",","[","subprocess",".","Popen","(","[","\"systemctl\"",",","\"disable\"",",","service","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",",",")","for","service","in","disable_services","]",",",")","wait_processes","(","\"enable services\"",",","[","subprocess",".","Popen","(","[","\"systemctl\"",",","\"enable\"",",","service","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",",",")","for","service","in","enable_services","]",",",")","wait_processes","(","\"start services\"",",","[","subprocess",".","Popen","(","[","\"systemctl\"",",","\"start\"",",","service","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",",",")","for","service","in","enable_services","]",",",")","wait_processes","(","\"stop services\"",",","[","subprocess",".","Popen","(","[","\"systemctl\"",",","\"stop\"",",","service","]",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",",",")","for","service","in","disable_services","]",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L949-L1003"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"mount","parameters":"(iso_path, domain_name)","argument_list":"","return_statement":"","docstring":"Inject ISO file into specified guest vm.\n Domain can be retrieved by running \"xl list\" command on the host.","docstring_summary":"Inject ISO file into specified guest vm.\n Domain can be retrieved by running \"xl list\" command on the host.","docstring_tokens":["Inject","ISO","file","into","specified","guest","vm",".","Domain","can","be","retrieved","by","running","xl","list","command","on","the","host","."],"function":"def mount(iso_path, domain_name):\n \"\"\"Inject ISO file into specified guest vm.\n Domain can be retrieved by running \"xl list\" command on the host.\n \"\"\"\n iso_path_full = os.path.abspath(iso_path)\n insert_cd(domain_name, FIRST_CDROM_DRIVE, iso_path_full)","function_tokens":["def","mount","(","iso_path",",","domain_name",")",":","iso_path_full","=","os",".","path",".","abspath","(","iso_path",")","insert_cd","(","domain_name",",","FIRST_CDROM_DRIVE",",","iso_path_full",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L1016-L1021"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"do_export_minimal","parameters":"(mc, bucket, name)","argument_list":"","return_statement":"","docstring":"Perform minimal snapshot export, symmetric to do_import_minimal","docstring_summary":"Perform minimal snapshot export, symmetric to do_import_minimal","docstring_tokens":["Perform","minimal","snapshot","export","symmetric","to","do_import_minimal"],"function":"def do_export_minimal(mc, bucket, name):\n \"\"\"Perform minimal snapshot export, symmetric to do_import_minimal\"\"\"\n logging.info(\"Uploading installation info\")\n install_info = InstallInfo.load()\n install_data = json.dumps(install_info.to_dict()).encode()\n mc.put_object(\n bucket, f\"{name}\/install.json\", io.BytesIO(install_data), len(install_data)\n )\n\n logging.info(\"Uploading VM template\")\n mc.fput_object(\n bucket, f\"{name}\/cfg.template\", os.path.join(ETC_DIR, \"scripts\", \"cfg.template\")\n )\n\n with tempfile.NamedTemporaryFile() as disk_image:\n logging.info(\"Exporting VM hard drive\")\n storage = get_storage_backend(install_info)\n storage.export_vm0(disk_image.name)\n\n logging.info(\"Uploading disk.img\")\n mc.fput_object(bucket, f\"{name}\/disk.img\", disk_image.name)","function_tokens":["def","do_export_minimal","(","mc",",","bucket",",","name",")",":","logging",".","info","(","\"Uploading installation info\"",")","install_info","=","InstallInfo",".","load","(",")","install_data","=","json",".","dumps","(","install_info",".","to_dict","(",")",")",".","encode","(",")","mc",".","put_object","(","bucket",",","f\"{name}\/install.json\"",",","io",".","BytesIO","(","install_data",")",",","len","(","install_data",")",")","logging",".","info","(","\"Uploading VM template\"",")","mc",".","fput_object","(","bucket",",","f\"{name}\/cfg.template\"",",","os",".","path",".","join","(","ETC_DIR",",","\"scripts\"",",","\"cfg.template\"",")",")","with","tempfile",".","NamedTemporaryFile","(",")","as","disk_image",":","logging",".","info","(","\"Exporting VM hard drive\"",")","storage","=","get_storage_backend","(","install_info",")","storage",".","export_vm0","(","disk_image",".","name",")","logging",".","info","(","\"Uploading disk.img\"",")","mc",".","fput_object","(","bucket",",","f\"{name}\/disk.img\"",",","disk_image",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L1229-L1249"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"do_import_minimal","parameters":"(mc, name, bucket, zpool)","argument_list":"","return_statement":"","docstring":"Perform minimal snapshot import, symmetric to do_export_minimal","docstring_summary":"Perform minimal snapshot import, symmetric to do_export_minimal","docstring_tokens":["Perform","minimal","snapshot","import","symmetric","to","do_export_minimal"],"function":"def do_import_minimal(mc, name, bucket, zpool):\n \"\"\"Perform minimal snapshot import, symmetric to do_export_minimal\"\"\"\n logging.info(\"Downloading installation info\")\n mc.fget_object(\n bucket,\n f\"{name}\/install.json\",\n os.path.join(ETC_DIR, InstallInfo._INSTALL_FILENAME),\n )\n\n logging.info(\"Downloading VM config\")\n mc.fget_object(\n bucket, f\"{name}\/cfg.template\", os.path.join(ETC_DIR, \"scripts\", \"cfg.template\")\n )\n\n # Now we have imported InstallInfo object\n install_info = InstallInfo.load()\n\n # Patch ZFS pool name\n if zpool is not None:\n install_info.zfs_tank_name = zpool\n # Save patched ZFS dataset name (storage backend has to know it)\n install_info.save()\n\n storage = get_storage_backend(install_info)\n\n with tempfile.NamedTemporaryFile() as disk_image:\n logging.info(\"Downloading VM disk image\")\n mc.fget_object(bucket, f\"{name}\/disk.img\", disk_image.name)\n\n logging.info(\"Importing VM disk\")\n storage.import_vm0(disk_image.name)","function_tokens":["def","do_import_minimal","(","mc",",","name",",","bucket",",","zpool",")",":","logging",".","info","(","\"Downloading installation info\"",")","mc",".","fget_object","(","bucket",",","f\"{name}\/install.json\"",",","os",".","path",".","join","(","ETC_DIR",",","InstallInfo",".","_INSTALL_FILENAME",")",",",")","logging",".","info","(","\"Downloading VM config\"",")","mc",".","fget_object","(","bucket",",","f\"{name}\/cfg.template\"",",","os",".","path",".","join","(","ETC_DIR",",","\"scripts\"",",","\"cfg.template\"",")",")","# Now we have imported InstallInfo object","install_info","=","InstallInfo",".","load","(",")","# Patch ZFS pool name","if","zpool","is","not","None",":","install_info",".","zfs_tank_name","=","zpool","# Save patched ZFS dataset name (storage backend has to know it)","install_info",".","save","(",")","storage","=","get_storage_backend","(","install_info",")","with","tempfile",".","NamedTemporaryFile","(",")","as","disk_image",":","logging",".","info","(","\"Downloading VM disk image\"",")","mc",".","fget_object","(","bucket",",","f\"{name}\/disk.img\"",",","disk_image",".","name",")","logging",".","info","(","\"Importing VM disk\"",")","storage",".","import_vm0","(","disk_image",".","name",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L1252-L1282"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"do_export_full","parameters":"(mc, bucket, name)","argument_list":"","return_statement":"","docstring":"Perform full snapshot export, symmetric to do_import_full","docstring_summary":"Perform full snapshot export, symmetric to do_import_full","docstring_tokens":["Perform","full","snapshot","export","symmetric","to","do_import_full"],"function":"def do_export_full(mc, bucket, name):\n \"\"\"Perform full snapshot export, symmetric to do_import_full\"\"\"\n do_export_minimal(mc, bucket, name)\n\n with tempfile.NamedTemporaryFile() as compressed_snapshot:\n # Compress snapshot\n logging.info(\"Compressing snapshot.sav\")\n subprocess.check_call(\n [\"gzip\", \"-c\", os.path.join(VOLUME_DIR, \"snapshot.sav\")],\n stdout=compressed_snapshot,\n )\n\n logging.info(\"Uploading snapshot.sav.gz\")\n mc.fput_object(bucket, f\"{name}\/snapshot.sav.gz\", compressed_snapshot.name)\n\n # Upload profiles\n for file in os.listdir(PROFILE_DIR):\n logging.info(\"Uploading profile %s\", file)\n mc.fput_object(\n bucket, f\"{name}\/profiles\/{file}\", os.path.join(PROFILE_DIR, file)\n )\n\n # Upload ApiScout profile\n for file in os.listdir(APISCOUT_PROFILE_DIR):\n logging.info(\"Uploading file %s\", file)\n mc.fput_object(\n bucket,\n f\"{name}\/apiscout_profile\/{file}\",\n os.path.join(APISCOUT_PROFILE_DIR, file),\n )","function_tokens":["def","do_export_full","(","mc",",","bucket",",","name",")",":","do_export_minimal","(","mc",",","bucket",",","name",")","with","tempfile",".","NamedTemporaryFile","(",")","as","compressed_snapshot",":","# Compress snapshot","logging",".","info","(","\"Compressing snapshot.sav\"",")","subprocess",".","check_call","(","[","\"gzip\"",",","\"-c\"",",","os",".","path",".","join","(","VOLUME_DIR",",","\"snapshot.sav\"",")","]",",","stdout","=","compressed_snapshot",",",")","logging",".","info","(","\"Uploading snapshot.sav.gz\"",")","mc",".","fput_object","(","bucket",",","f\"{name}\/snapshot.sav.gz\"",",","compressed_snapshot",".","name",")","# Upload profiles","for","file","in","os",".","listdir","(","PROFILE_DIR",")",":","logging",".","info","(","\"Uploading profile %s\"",",","file",")","mc",".","fput_object","(","bucket",",","f\"{name}\/profiles\/{file}\"",",","os",".","path",".","join","(","PROFILE_DIR",",","file",")",")","# Upload ApiScout profile","for","file","in","os",".","listdir","(","APISCOUT_PROFILE_DIR",")",":","logging",".","info","(","\"Uploading file %s\"",",","file",")","mc",".","fput_object","(","bucket",",","f\"{name}\/apiscout_profile\/{file}\"",",","os",".","path",".","join","(","APISCOUT_PROFILE_DIR",",","file",")",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L1285-L1314"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/draksetup.py","language":"python","identifier":"do_import_full","parameters":"(mc, name, bucket, zpool)","argument_list":"","return_statement":"","docstring":"Perform full snapshot import, symmetric to do_export_full","docstring_summary":"Perform full snapshot import, symmetric to do_export_full","docstring_tokens":["Perform","full","snapshot","import","symmetric","to","do_export_full"],"function":"def do_import_full(mc, name, bucket, zpool):\n \"\"\"Perform full snapshot import, symmetric to do_export_full\"\"\"\n do_import_minimal(mc, name, bucket, zpool)\n\n with tempfile.NamedTemporaryFile() as compressed_snapshot:\n mc.fget_object(bucket, f\"{name}\/snapshot.sav.gz\", compressed_snapshot.name)\n\n logging.info(\"Decompressing VM snapshot\")\n with open(os.path.join(VOLUME_DIR, \"snapshot.sav\"), \"wb\") as snapshot:\n subprocess.run(\n [\"zcat\", compressed_snapshot.name], stdout=snapshot, check=True\n )\n\n profiles_prefix = f\"{name}\/profiles\/\"\n for object in mc.list_objects(bucket, prefix=profiles_prefix):\n # Strip profiles prefix\n profile_name = object.object_name[len(profiles_prefix) :]\n mc.fget_object(\n bucket, object.object_name, os.path.join(PROFILE_DIR, profile_name)\n )\n\n apiscout_profile_prefix = f\"{name}\/apiscout_profile\/\"\n for object in mc.list_objects(bucket, prefix=apiscout_profile_prefix):\n # Strip apiscout profile prefix\n filename = object.object_name[len(apiscout_profile_prefix) :]\n mc.fget_object(\n bucket, object.object_name, os.path.join(APISCOUT_PROFILE_DIR, filename)\n )","function_tokens":["def","do_import_full","(","mc",",","name",",","bucket",",","zpool",")",":","do_import_minimal","(","mc",",","name",",","bucket",",","zpool",")","with","tempfile",".","NamedTemporaryFile","(",")","as","compressed_snapshot",":","mc",".","fget_object","(","bucket",",","f\"{name}\/snapshot.sav.gz\"",",","compressed_snapshot",".","name",")","logging",".","info","(","\"Decompressing VM snapshot\"",")","with","open","(","os",".","path",".","join","(","VOLUME_DIR",",","\"snapshot.sav\"",")",",","\"wb\"",")","as","snapshot",":","subprocess",".","run","(","[","\"zcat\"",",","compressed_snapshot",".","name","]",",","stdout","=","snapshot",",","check","=","True",")","profiles_prefix","=","f\"{name}\/profiles\/\"","for","object","in","mc",".","list_objects","(","bucket",",","prefix","=","profiles_prefix",")",":","# Strip profiles prefix","profile_name","=","object",".","object_name","[","len","(","profiles_prefix",")",":","]","mc",".","fget_object","(","bucket",",","object",".","object_name",",","os",".","path",".","join","(","PROFILE_DIR",",","profile_name",")",")","apiscout_profile_prefix","=","f\"{name}\/apiscout_profile\/\"","for","object","in","mc",".","list_objects","(","bucket",",","prefix","=","apiscout_profile_prefix",")",":","# Strip apiscout profile prefix","filename","=","object",".","object_name","[","len","(","apiscout_profile_prefix",")",":","]","mc",".","fget_object","(","bucket",",","object",".","object_name",",","os",".","path",".","join","(","APISCOUT_PROFILE_DIR",",","filename",")",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/draksetup.py#L1317-L1344"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"get_storage_backend","parameters":"(install_info: InstallInfo)","argument_list":"","return_statement":"return REGISTERED_BACKENDS[install_info.storage_backend](install_info)","docstring":"Return installed storage backend or throw InvalidStorageBackend","docstring_summary":"Return installed storage backend or throw InvalidStorageBackend","docstring_tokens":["Return","installed","storage","backend","or","throw","InvalidStorageBackend"],"function":"def get_storage_backend(install_info: InstallInfo) -> StorageBackendBase:\n \"\"\"Return installed storage backend or throw InvalidStorageBackend\"\"\"\n if install_info.storage_backend not in REGISTERED_BACKEND_NAMES:\n raise InvalidStorageBackend\n\n return REGISTERED_BACKENDS[install_info.storage_backend](install_info)","function_tokens":["def","get_storage_backend","(","install_info",":","InstallInfo",")","->","StorageBackendBase",":","if","install_info",".","storage_backend","not","in","REGISTERED_BACKEND_NAMES",":","raise","InvalidStorageBackend","return","REGISTERED_BACKENDS","[","install_info",".","storage_backend","]","(","install_info",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L499-L504"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.initialize_vm0_volume","parameters":"(self, disk_size: str)","argument_list":"","return_statement":"","docstring":"Create base volume for vm-0 with given size\n\n disk_size - string representing volume size with M\/G\/T suffix, eg. 100G","docstring_summary":"Create base volume for vm-0 with given size","docstring_tokens":["Create","base","volume","for","vm","-","0","with","given","size"],"function":"def initialize_vm0_volume(self, disk_size: str):\n \"\"\"Create base volume for vm-0 with given size\n\n disk_size - string representing volume size with M\/G\/T suffix, eg. 100G\n \"\"\"\n raise NotImplementedError","function_tokens":["def","initialize_vm0_volume","(","self",",","disk_size",":","str",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L32-L37"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.snapshot_vm0_volume","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Saves or snapshots base vm-0 volume for later use by other VMs","docstring_summary":"Saves or snapshots base vm-0 volume for later use by other VMs","docstring_tokens":["Saves","or","snapshots","base","vm","-","0","volume","for","later","use","by","other","VMs"],"function":"def snapshot_vm0_volume(self):\n \"\"\"Saves or snapshots base vm-0 volume for later use by other VMs\"\"\"\n raise NotImplementedError","function_tokens":["def","snapshot_vm0_volume","(","self",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L39-L41"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.get_vm_disk_path","parameters":"(self, vm_id: int)","argument_list":"","return_statement":"","docstring":"Returns disk path for given VM as defined by XL configuration","docstring_summary":"Returns disk path for given VM as defined by XL configuration","docstring_tokens":["Returns","disk","path","for","given","VM","as","defined","by","XL","configuration"],"function":"def get_vm_disk_path(self, vm_id: int) -> str:\n \"\"\"Returns disk path for given VM as defined by XL configuration\"\"\"\n raise NotImplementedError","function_tokens":["def","get_vm_disk_path","(","self",",","vm_id",":","int",")","->","str",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L43-L45"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.rollback_vm_storage","parameters":"(self, vm_id: int)","argument_list":"","return_statement":"","docstring":"Rolls back changes and prepares fresh storage for new run of this VM","docstring_summary":"Rolls back changes and prepares fresh storage for new run of this VM","docstring_tokens":["Rolls","back","changes","and","prepares","fresh","storage","for","new","run","of","this","VM"],"function":"def rollback_vm_storage(self, vm_id: int):\n \"\"\"Rolls back changes and prepares fresh storage for new run of this VM\"\"\"\n raise NotImplementedError","function_tokens":["def","rollback_vm_storage","(","self",",","vm_id",":","int",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L47-L49"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.get_vm0_snapshot_time","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get UNIX timestamp of when vm-0 snapshot was last modified","docstring_summary":"Get UNIX timestamp of when vm-0 snapshot was last modified","docstring_tokens":["Get","UNIX","timestamp","of","when","vm","-","0","snapshot","was","last","modified"],"function":"def get_vm0_snapshot_time(self):\n \"\"\"Get UNIX timestamp of when vm-0 snapshot was last modified\"\"\"\n raise NotImplementedError","function_tokens":["def","get_vm0_snapshot_time","(","self",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L51-L53"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.export_vm0","parameters":"(self, file)","argument_list":"","return_statement":"","docstring":"Export vm-0 disk into a file (symmetric to import_vm0)","docstring_summary":"Export vm-0 disk into a file (symmetric to import_vm0)","docstring_tokens":["Export","vm","-","0","disk","into","a","file","(","symmetric","to","import_vm0",")"],"function":"def export_vm0(self, file):\n \"\"\"Export vm-0 disk into a file (symmetric to import_vm0)\"\"\"\n raise NotImplementedError","function_tokens":["def","export_vm0","(","self",",","file",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L55-L57"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.import_vm0","parameters":"(self, file)","argument_list":"","return_statement":"","docstring":"Import vm-0 disk from a file (symmetric to export_vm0)","docstring_summary":"Import vm-0 disk from a file (symmetric to export_vm0)","docstring_tokens":["Import","vm","-","0","disk","from","a","file","(","symmetric","to","export_vm0",")"],"function":"def import_vm0(self, file):\n \"\"\"Import vm-0 disk from a file (symmetric to export_vm0)\"\"\"\n raise NotImplementedError","function_tokens":["def","import_vm0","(","self",",","file",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L59-L61"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"StorageBackendBase.delete_vm_volume","parameters":"(self, vm_id: int)","argument_list":"","return_statement":"","docstring":"Delete vm_id disk volume","docstring_summary":"Delete vm_id disk volume","docstring_tokens":["Delete","vm_id","disk","volume"],"function":"def delete_vm_volume(self, vm_id: int):\n \"\"\"Delete vm_id disk volume\"\"\"\n raise NotImplementedError","function_tokens":["def","delete_vm_volume","(","self",",","vm_id",":","int",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L63-L65"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"ZfsStorageBackend.check_tools","parameters":"()","argument_list":"","return_statement":"","docstring":"Verify existence of zfs command utility","docstring_summary":"Verify existence of zfs command utility","docstring_tokens":["Verify","existence","of","zfs","command","utility"],"function":"def check_tools():\n \"\"\"Verify existence of zfs command utility\"\"\"\n try:\n subprocess.check_output(\"zfs -?\", shell=True)\n except subprocess.CalledProcessError:\n raise RuntimeError(\n \"Failed to execute zfs command. \"\n \"Make sure you have ZFS support installed.\"\n )","function_tokens":["def","check_tools","(",")",":","try",":","subprocess",".","check_output","(","\"zfs -?\"",",","shell","=","True",")","except","subprocess",".","CalledProcessError",":","raise","RuntimeError","(","\"Failed to execute zfs command. \"","\"Make sure you have ZFS support installed.\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L79-L87"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"Qcow2StorageBackend.check_tools","parameters":"()","argument_list":"","return_statement":"","docstring":"Verify existence of qemu-img","docstring_summary":"Verify existence of qemu-img","docstring_tokens":["Verify","existence","of","qemu","-","img"],"function":"def check_tools():\n \"\"\"Verify existence of qemu-img\"\"\"\n try:\n subprocess.check_output(\"qemu-img --version\", shell=True)\n except subprocess.CalledProcessError:\n raise RuntimeError(\n \"Failed to determine qemu-img version. \"\n \"Make sure you have qemu-utils installed.\"\n )","function_tokens":["def","check_tools","(",")",":","try",":","subprocess",".","check_output","(","\"qemu-img --version\"",",","shell","=","True",")","except","subprocess",".","CalledProcessError",":","raise","RuntimeError","(","\"Failed to determine qemu-img version. \"","\"Make sure you have qemu-utils installed.\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L210-L218"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.check_tools","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Verify existence of lvm command utility","docstring_summary":"Verify existence of lvm command utility","docstring_tokens":["Verify","existence","of","lvm","command","utility"],"function":"def check_tools(self):\n \"\"\"Verify existence of lvm command utility\"\"\"\n try:\n subprocess.run(\n [\"vgs\", self.lvm_volume_group], check=True, stdout=subprocess.DEVNULL\n )\n except subprocess.CalledProcessError:\n raise RuntimeError(\n \"Failed to execute vgs command\"\n f\"Make sure you have LVM support installed with {self.lvm_volume_group} as a volume group\"\n )","function_tokens":["def","check_tools","(","self",")",":","try",":","subprocess",".","run","(","[","\"vgs\"",",","self",".","lvm_volume_group","]",",","check","=","True",",","stdout","=","subprocess",".","DEVNULL",")","except","subprocess",".","CalledProcessError",":","raise","RuntimeError","(","\"Failed to execute vgs command\"","f\"Make sure you have LVM support installed with {self.lvm_volume_group} as a volume group\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L295-L305"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.initialize_vm0_volume","parameters":"(self, disk_size: str)","argument_list":"","return_statement":"","docstring":"Create base volume for vm-0 with given size\n\n disk_size - string representing volume size with M\/G\/T suffix, eg. 100G","docstring_summary":"Create base volume for vm-0 with given size","docstring_tokens":["Create","base","volume","for","vm","-","0","with","given","size"],"function":"def initialize_vm0_volume(self, disk_size: str):\n \"\"\"Create base volume for vm-0 with given size\n\n disk_size - string representing volume size with M\/G\/T suffix, eg. 100G\n \"\"\"\n try:\n logging.info(\"Deleting existing logical volume and snapshot\")\n subprocess.check_output(\n [\n \"lvremove\",\n \"-v\",\n \"-y\",\n # \"--noudevsync\",\n f\"{self.lvm_volume_group}\/vm-0\",\n ],\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n if b\"Failed to find logical volume\" not in exc.output:\n raise RuntimeError(\n f\"Failed to destroy logical volume {self.lvm_volume_group}\/vm-0\"\n )\n try:\n logging.info(\"Creating new volume vm-0\")\n subprocess.run(\n [\n \"lvcreate\",\n \"-y\",\n \"-L\",\n disk_size,\n \"-n\",\n \"vm-0\",\n self.lvm_volume_group,\n ],\n check=True,\n )\n except subprocess.CalledProcessError:\n raise RuntimeError(\"Failed to create a new volume using lvcreate.\")","function_tokens":["def","initialize_vm0_volume","(","self",",","disk_size",":","str",")",":","try",":","logging",".","info","(","\"Deleting existing logical volume and snapshot\"",")","subprocess",".","check_output","(","[","\"lvremove\"",",","\"-v\"",",","\"-y\"",",","# \"--noudevsync\",","f\"{self.lvm_volume_group}\/vm-0\"",",","]",",","stderr","=","subprocess",".","STDOUT",",",")","except","subprocess",".","CalledProcessError","as","exc",":","if","b\"Failed to find logical volume\"","not","in","exc",".","output",":","raise","RuntimeError","(","f\"Failed to destroy logical volume {self.lvm_volume_group}\/vm-0\"",")","try",":","logging",".","info","(","\"Creating new volume vm-0\"",")","subprocess",".","run","(","[","\"lvcreate\"",",","\"-y\"",",","\"-L\"",",","disk_size",",","\"-n\"",",","\"vm-0\"",",","self",".","lvm_volume_group",",","]",",","check","=","True",",",")","except","subprocess",".","CalledProcessError",":","raise","RuntimeError","(","\"Failed to create a new volume using lvcreate.\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L307-L344"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.snapshot_vm0_volume","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Saves or snapshots base vm-0 volume for later use by other VMs","docstring_summary":"Saves or snapshots base vm-0 volume for later use by other VMs","docstring_tokens":["Saves","or","snapshots","base","vm","-","0","volume","for","later","use","by","other","VMs"],"function":"def snapshot_vm0_volume(self):\n \"\"\"Saves or snapshots base vm-0 volume for later use by other VMs\"\"\"\n # vm-0 is the original disk being treated as a snapshot\n # vm-0-snap is being created just for the access time of the change in vm snapshot\n subprocess.run(\n [\"lvremove\", f\"{self.lvm_volume_group}\/vm-0-snap\"],\n stderr=subprocess.DEVNULL,\n )\n try:\n subprocess.check_output(\n [\n \"lvcreate\",\n \"-s\",\n \"-L\",\n self.snapshot_disksize,\n \"-n\",\n \"vm-0-snap\",\n f\"{self.lvm_volume_group}\/vm-0\",\n ],\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n logging.debug(exc.output)\n raise RuntimeError(\"Couldn't create snapshot\")","function_tokens":["def","snapshot_vm0_volume","(","self",")",":","# vm-0 is the original disk being treated as a snapshot","# vm-0-snap is being created just for the access time of the change in vm snapshot","subprocess",".","run","(","[","\"lvremove\"",",","f\"{self.lvm_volume_group}\/vm-0-snap\"","]",",","stderr","=","subprocess",".","DEVNULL",",",")","try",":","subprocess",".","check_output","(","[","\"lvcreate\"",",","\"-s\"",",","\"-L\"",",","self",".","snapshot_disksize",",","\"-n\"",",","\"vm-0-snap\"",",","f\"{self.lvm_volume_group}\/vm-0\"",",","]",",","stderr","=","subprocess",".","STDOUT",",",")","except","subprocess",".","CalledProcessError","as","exc",":","logging",".","debug","(","exc",".","output",")","raise","RuntimeError","(","\"Couldn't create snapshot\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L346-L369"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.get_vm_disk_path","parameters":"(self, vm_id: int)","argument_list":"","return_statement":"return f\"phy:\/dev\/{self.lvm_volume_group}\/vm-{vm_id},hda,w\"","docstring":"Returns disk path for given VM as defined by XL configuration","docstring_summary":"Returns disk path for given VM as defined by XL configuration","docstring_tokens":["Returns","disk","path","for","given","VM","as","defined","by","XL","configuration"],"function":"def get_vm_disk_path(self, vm_id: int) -> str:\n \"\"\"Returns disk path for given VM as defined by XL configuration\"\"\"\n return f\"phy:\/dev\/{self.lvm_volume_group}\/vm-{vm_id},hda,w\"","function_tokens":["def","get_vm_disk_path","(","self",",","vm_id",":","int",")","->","str",":","return","f\"phy:\/dev\/{self.lvm_volume_group}\/vm-{vm_id},hda,w\""],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L371-L373"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.rollback_vm_storage","parameters":"(self, vm_id: int)","argument_list":"","return_statement":"","docstring":"Rolls back changes and prepares fresh storage for new run of this VM","docstring_summary":"Rolls back changes and prepares fresh storage for new run of this VM","docstring_tokens":["Rolls","back","changes","and","prepares","fresh","storage","for","new","run","of","this","VM"],"function":"def rollback_vm_storage(self, vm_id: int):\n \"\"\"Rolls back changes and prepares fresh storage for new run of this VM\"\"\"\n vm_id_vol = os.path.join(\"\/dev\", f\"{self.lvm_volume_group}\", f\"vm-{vm_id}\")\n\n if vm_id == 0:\n raise Exception(\"vm-0 should not be rollbacked\")\n\n logging.info(f\"Rolling back changes to vm-{vm_id} disk\")\n if os.path.exists(vm_id_vol):\n try:\n subprocess.check_output(\n [\n \"lvremove\",\n \"-v\",\n \"-y\",\n # \"--noudevsync\",\n f\"{self.lvm_volume_group}\/vm-{vm_id}\",\n ],\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n logging.debug(exc.output)\n raise RuntimeError(\n f\"Failed to discard previous logical volume {self.lvm_volume_group}\/vm-{vm_id}\"\n )\n\n try:\n subprocess.check_output(\n [\n \"lvcreate\",\n \"-s\",\n \"-L\",\n self.snapshot_disksize,\n \"-n\",\n f\"vm-{vm_id}\",\n f\"{self.lvm_volume_group}\/vm-0\",\n ],\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n logging.debug(exc.output)\n raise RuntimeError(\"Couldn't rollback disk\")","function_tokens":["def","rollback_vm_storage","(","self",",","vm_id",":","int",")",":","vm_id_vol","=","os",".","path",".","join","(","\"\/dev\"",",","f\"{self.lvm_volume_group}\"",",","f\"vm-{vm_id}\"",")","if","vm_id","==","0",":","raise","Exception","(","\"vm-0 should not be rollbacked\"",")","logging",".","info","(","f\"Rolling back changes to vm-{vm_id} disk\"",")","if","os",".","path",".","exists","(","vm_id_vol",")",":","try",":","subprocess",".","check_output","(","[","\"lvremove\"",",","\"-v\"",",","\"-y\"",",","# \"--noudevsync\",","f\"{self.lvm_volume_group}\/vm-{vm_id}\"",",","]",",","stderr","=","subprocess",".","STDOUT",",",")","except","subprocess",".","CalledProcessError","as","exc",":","logging",".","debug","(","exc",".","output",")","raise","RuntimeError","(","f\"Failed to discard previous logical volume {self.lvm_volume_group}\/vm-{vm_id}\"",")","try",":","subprocess",".","check_output","(","[","\"lvcreate\"",",","\"-s\"",",","\"-L\"",",","self",".","snapshot_disksize",",","\"-n\"",",","f\"vm-{vm_id}\"",",","f\"{self.lvm_volume_group}\/vm-0\"",",","]",",","stderr","=","subprocess",".","STDOUT",",",")","except","subprocess",".","CalledProcessError","as","exc",":","logging",".","debug","(","exc",".","output",")","raise","RuntimeError","(","\"Couldn't rollback disk\"",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L375-L416"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.get_vm0_snapshot_time","parameters":"(self)","argument_list":"","return_statement":"return int(dt.timestamp())","docstring":"Get UNIX timestamp of when vm-0 snapshot was last modified","docstring_summary":"Get UNIX timestamp of when vm-0 snapshot was last modified","docstring_tokens":["Get","UNIX","timestamp","of","when","vm","-","0","snapshot","was","last","modified"],"function":"def get_vm0_snapshot_time(self):\n \"\"\"Get UNIX timestamp of when vm-0 snapshot was last modified\"\"\"\n\n p = subprocess.run(\n [\"lvs\", \"-o\", \"lv_name,lv_time\", \"--reportformat\", \"json\"],\n capture_output=True,\n check=True,\n )\n\n lvs = json.loads(p.stdout.decode(\"utf-8\"))[\"report\"][0][\"lv\"]\n target_lvs = list(filter(lambda x: x[\"lv_name\"] == \"vm-0-snap\", lvs))\n\n if len(target_lvs) > 1:\n raise RuntimeError(\"Found multiple lvs named vm-0-snap!\")\n\n if len(target_lvs) == 0:\n raise RuntimeError(\"Failed to find LV vm-0-snap!\")\n\n dt = datetime.datetime.strptime(\n target_lvs[0][\"lv_time\"], \"%Y-%m-%d %H:%M:%S %z\"\n )\n return int(dt.timestamp())","function_tokens":["def","get_vm0_snapshot_time","(","self",")",":","p","=","subprocess",".","run","(","[","\"lvs\"",",","\"-o\"",",","\"lv_name,lv_time\"",",","\"--reportformat\"",",","\"json\"","]",",","capture_output","=","True",",","check","=","True",",",")","lvs","=","json",".","loads","(","p",".","stdout",".","decode","(","\"utf-8\"",")",")","[","\"report\"","]","[","0","]","[","\"lv\"","]","target_lvs","=","list","(","filter","(","lambda","x",":","x","[","\"lv_name\"","]","==","\"vm-0-snap\"",",","lvs",")",")","if","len","(","target_lvs",")",">","1",":","raise","RuntimeError","(","\"Found multiple lvs named vm-0-snap!\"",")","if","len","(","target_lvs",")","==","0",":","raise","RuntimeError","(","\"Failed to find LV vm-0-snap!\"",")","dt","=","datetime",".","datetime",".","strptime","(","target_lvs","[","0","]","[","\"lv_time\"","]",",","\"%Y-%m-%d %H:%M:%S %z\"",")","return","int","(","dt",".","timestamp","(",")",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L418-L439"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.export_vm0","parameters":"(self, path: str)","argument_list":"","return_statement":"","docstring":"Export vm-0 disk into a file (symmetric to import_vm0)","docstring_summary":"Export vm-0 disk into a file (symmetric to import_vm0)","docstring_tokens":["Export","vm","-","0","disk","into","a","file","(","symmetric","to","import_vm0",")"],"function":"def export_vm0(self, path: str):\n \"\"\"Export vm-0 disk into a file (symmetric to import_vm0)\"\"\"\n # As dd copies empty spaces also\n # Should we use compressions in this? Will it have any issues while importing?\n subprocess.run(\n [\n \"dd\",\n f\"if=\/dev\/{self.lvm_volume_group}\/vm-0\",\n f\"of={path}\",\n \"bs=4k\",\n \"status=progress\",\n ],\n check=True,\n )","function_tokens":["def","export_vm0","(","self",",","path",":","str",")",":","# As dd copies empty spaces also","# Should we use compressions in this? Will it have any issues while importing?","subprocess",".","run","(","[","\"dd\"",",","f\"if=\/dev\/{self.lvm_volume_group}\/vm-0\"",",","f\"of={path}\"",",","\"bs=4k\"",",","\"status=progress\"",",","]",",","check","=","True",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L441-L454"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/storage.py","language":"python","identifier":"LvmStorageBackend.import_vm0","parameters":"(self, path: str)","argument_list":"","return_statement":"","docstring":"Import vm-0 disk from a file (symmetric to export_vm0)","docstring_summary":"Import vm-0 disk from a file (symmetric to export_vm0)","docstring_tokens":["Import","vm","-","0","disk","from","a","file","(","symmetric","to","export_vm0",")"],"function":"def import_vm0(self, path: str):\n \"\"\"Import vm-0 disk from a file (symmetric to export_vm0)\"\"\"\n subprocess.run(\n [\n \"dd\",\n f\"of=\/dev\/{self.lvm_volume_group}\/vm-0\",\n f\"if={path}\",\n \"bs=4k\",\n \"status=progress\",\n ],\n check=True,\n )","function_tokens":["def","import_vm0","(","self",",","path",":","str",")",":","subprocess",".","run","(","[","\"dd\"",",","f\"of=\/dev\/{self.lvm_volume_group}\/vm-0\"",",","f\"if={path}\"",",","\"bs=4k\"",",","\"status=progress\"",",","]",",","check","=","True",",",")"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/storage.py#L456-L467"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/config.py","language":"python","identifier":"is_installed","parameters":"()","argument_list":"","return_statement":"return InstallInfo.try_load() is not None","docstring":"Returns true when install.json is present","docstring_summary":"Returns true when install.json is present","docstring_tokens":["Returns","true","when","install",".","json","is","present"],"function":"def is_installed() -> bool:\n \"\"\"Returns true when install.json is present\"\"\"\n return InstallInfo.try_load() is not None","function_tokens":["def","is_installed","(",")","->","bool",":","return","InstallInfo",".","try_load","(",")","is","not","None"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/config.py#L60-L62"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/vba_graph.py","language":"python","identifier":"vba_extract_functions","parameters":"(vba_content_lines)","argument_list":"","return_statement":"return vba_func_dict","docstring":"Seperates the input VBA code into functions\n\n Args:\n vba_content_lines (string[]): VBA code lines without comments, metadata or spaces\n\n Returns:\n dict[func_name]=func_code: Dictionary of VBA functions found","docstring_summary":"Seperates the input VBA code into functions","docstring_tokens":["Seperates","the","input","VBA","code","into","functions"],"function":"def vba_extract_functions(vba_content_lines):\n \"\"\"Seperates the input VBA code into functions\n\n Args:\n vba_content_lines (string[]): VBA code lines without comments, metadata or spaces\n\n Returns:\n dict[func_name]=func_code: Dictionary of VBA functions found\n \"\"\"\n vba_func_dict = {}\n inside_function = False\n func_name = \"\"\n\n for vba_line in vba_content_lines:\n # I) Handle External Function Declaration.\n\n # Create dummpy empty function with func_name:\n # mcvWGqJifEVHwB (URLDownloadToFileA)\n # Examples:\n # Private Declare Function NyKQpQhtmrFfWX Lib \"kernel32\" Alias \"lstrcmpA\" (ByVal pCaller As Long,..\n # - would become: NyKQpQhtmrFfWX (lstrcmpA) (External)\n # Private Declare PtrSafe Function mcvWGqJifEVHwB Lib \"urlmon\" Alias \"URLDownloadToFileA\" (ByVal pfsseerwseer As Long,...\n # - would become: mcvWGqJifEVHwB (URLDownloadToFileA) (External)\n if \" Lib \" in vba_line and \" Alias \" in vba_line and not inside_function:\n if \" Function \" in vba_line:\n func_type = \" Function \"\n else:\n func_type = \" Sub \"\n\n declared_func_name = vba_line[\n vba_line.find(func_type) + len(func_type) : vba_line.find(\" Lib \")\n ]\n external_func_name = vba_line[\n vba_line.find(' Alias \"')\n + len(' Alias \"') : vba_line.find(\n '\" (', vba_line.find(' Alias \"') + len(' Alias \"')\n )\n ]\n func_name = (\n declared_func_name + \" (\" + external_func_name + \")\" + \" (External)\"\n )\n\n if \"libc.dylib\" in vba_line:\n func_name += \"(Mac)\"\n\n vba_func_dict[func_name] = \"\"\n continue\n\n # Create dummy empty function with func_name that do not have Alias:\n # Examples:\n # Public Declare PtrSafe Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As LongPtr)\n # - would become: Sleep\n # Public Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n # - would become: Sleep\n if \" Lib \" in vba_line and not inside_function:\n if \" Function \" in vba_line:\n func_type = \" Function \"\n else:\n func_type = \" Sub \"\n func_name = (\n vba_line[\n vba_line.find(func_type) + len(func_type) : vba_line.find(\" Lib \")\n ]\n + \" (External)\"\n )\n\n if \"libc.dylib\" in vba_line:\n func_name += \"(Mac)\"\n\n vba_func_dict[func_name] = \"\"\n continue\n\n # II) Handle Regular Function Declaration.\n # Look for function start keywords.\n func_start_pos = max(vba_line.find(\"Sub \"), vba_line.find(\"Function \"))\n\n # Some macros have the word \"Function\" as string inside a code line.\n # This should remove FP funtions, by checking the line start.\n legit_declare_line_start = False\n if (\n vba_line.startswith(\"Sub\")\n or vba_line.startswith(\"Function\")\n or vba_line.startswith(\"Private\")\n or vba_line.startswith(\"Public\")\n ):\n legit_declare_line_start = True\n\n is_func_end = vba_line.startswith(\"End Sub\") or vba_line.startswith(\n \"End Function\"\n )\n\n # Check if we've reached the end of a function.\n if is_func_end:\n inside_function = False\n continue\n\n # Check if we've hit a new function.\n elif legit_declare_line_start and func_start_pos > -1:\n inside_function = True\n\n # Extract function name from declaration.\n if \"Function \" in vba_line:\n func_name = vba_line[\n (func_start_pos + len(\"Function \")) : vba_line.find(\"(\")\n ]\n elif \"Sub \" in vba_line:\n func_name = vba_line[\n (func_start_pos + len(\"Sub \")) : vba_line.find(\"(\")\n ]\n else:\n logging.error(\"Error parsing function name\")\n sys.exit(1)\n\n elif inside_function:\n if func_name in vba_func_dict:\n # Append code to to an existing function.\n vba_func_dict[func_name] += LINE_SEP + vba_line\n else:\n # Create a new function name inside the dict\n # & add the first line of code.\n vba_func_dict[func_name] = vba_line\n\n # We are in a global section code line.\n else:\n pass\n return vba_func_dict","function_tokens":["def","vba_extract_functions","(","vba_content_lines",")",":","vba_func_dict","=","{","}","inside_function","=","False","func_name","=","\"\"","for","vba_line","in","vba_content_lines",":","# I) Handle External Function Declaration.","# Create dummpy empty function with func_name:","# mcvWGqJifEVHwB (URLDownloadToFileA)","# Examples:","# Private Declare Function NyKQpQhtmrFfWX Lib \"kernel32\" Alias \"lstrcmpA\" (ByVal pCaller As Long,..","# - would become: NyKQpQhtmrFfWX (lstrcmpA) (External)","# Private Declare PtrSafe Function mcvWGqJifEVHwB Lib \"urlmon\" Alias \"URLDownloadToFileA\" (ByVal pfsseerwseer As Long,...","# - would become: mcvWGqJifEVHwB (URLDownloadToFileA) (External)","if","\" Lib \"","in","vba_line","and","\" Alias \"","in","vba_line","and","not","inside_function",":","if","\" Function \"","in","vba_line",":","func_type","=","\" Function \"","else",":","func_type","=","\" Sub \"","declared_func_name","=","vba_line","[","vba_line",".","find","(","func_type",")","+","len","(","func_type",")",":","vba_line",".","find","(","\" Lib \"",")","]","external_func_name","=","vba_line","[","vba_line",".","find","(","' Alias \"'",")","+","len","(","' Alias \"'",")",":","vba_line",".","find","(","'\" ('",",","vba_line",".","find","(","' Alias \"'",")","+","len","(","' Alias \"'",")",")","]","func_name","=","(","declared_func_name","+","\" (\"","+","external_func_name","+","\")\"","+","\" (External)\"",")","if","\"libc.dylib\"","in","vba_line",":","func_name","+=","\"(Mac)\"","vba_func_dict","[","func_name","]","=","\"\"","continue","# Create dummy empty function with func_name that do not have Alias:","# Examples:","# Public Declare PtrSafe Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As LongPtr)","# - would become: Sleep","# Public Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)","# - would become: Sleep","if","\" Lib \"","in","vba_line","and","not","inside_function",":","if","\" Function \"","in","vba_line",":","func_type","=","\" Function \"","else",":","func_type","=","\" Sub \"","func_name","=","(","vba_line","[","vba_line",".","find","(","func_type",")","+","len","(","func_type",")",":","vba_line",".","find","(","\" Lib \"",")","]","+","\" (External)\"",")","if","\"libc.dylib\"","in","vba_line",":","func_name","+=","\"(Mac)\"","vba_func_dict","[","func_name","]","=","\"\"","continue","# II) Handle Regular Function Declaration.","# Look for function start keywords.","func_start_pos","=","max","(","vba_line",".","find","(","\"Sub \"",")",",","vba_line",".","find","(","\"Function \"",")",")","# Some macros have the word \"Function\" as string inside a code line.","# This should remove FP funtions, by checking the line start.","legit_declare_line_start","=","False","if","(","vba_line",".","startswith","(","\"Sub\"",")","or","vba_line",".","startswith","(","\"Function\"",")","or","vba_line",".","startswith","(","\"Private\"",")","or","vba_line",".","startswith","(","\"Public\"",")",")",":","legit_declare_line_start","=","True","is_func_end","=","vba_line",".","startswith","(","\"End Sub\"",")","or","vba_line",".","startswith","(","\"End Function\"",")","# Check if we've reached the end of a function.","if","is_func_end",":","inside_function","=","False","continue","# Check if we've hit a new function.","elif","legit_declare_line_start","and","func_start_pos",">","-","1",":","inside_function","=","True","# Extract function name from declaration.","if","\"Function \"","in","vba_line",":","func_name","=","vba_line","[","(","func_start_pos","+","len","(","\"Function \"",")",")",":","vba_line",".","find","(","\"(\"",")","]","elif","\"Sub \"","in","vba_line",":","func_name","=","vba_line","[","(","func_start_pos","+","len","(","\"Sub \"",")",")",":","vba_line",".","find","(","\"(\"",")","]","else",":","logging",".","error","(","\"Error parsing function name\"",")","sys",".","exit","(","1",")","elif","inside_function",":","if","func_name","in","vba_func_dict",":","# Append code to to an existing function.","vba_func_dict","[","func_name","]","+=","LINE_SEP","+","vba_line","else",":","# Create a new function name inside the dict","# & add the first line of code.","vba_func_dict","[","func_name","]","=","vba_line","# We are in a global section code line.","else",":","pass","return","vba_func_dict"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/vba_graph.py#L94-L219"}
{"nwo":"CERT-Polska\/drakvuf-sandbox","sha":"765f58cc14ac822a70e605da1c935bc50bd02923","path":"drakrun\/drakrun\/vba_graph.py","language":"python","identifier":"vba_extract_properties","parameters":"(vba_content_lines)","argument_list":"","return_statement":"return vba_prop_dict","docstring":"Find and extract the use of VBA Properties, in order to obfuscate macros\n\n Args:\n vba_content_lines (string[]): VBA code lines without comments, metadata or spaces\n\n Returns:\n dict[property_name]=property_code: Dictionary of VBA Properties found","docstring_summary":"Find and extract the use of VBA Properties, in order to obfuscate macros","docstring_tokens":["Find","and","extract","the","use","of","VBA","Properties","in","order","to","obfuscate","macros"],"function":"def vba_extract_properties(vba_content_lines):\n \"\"\"Find and extract the use of VBA Properties, in order to obfuscate macros\n\n Args:\n vba_content_lines (string[]): VBA code lines without comments, metadata or spaces\n\n Returns:\n dict[property_name]=property_code: Dictionary of VBA Properties found\n \"\"\"\n vba_prop_dict = {}\n inside_property = False\n prop_name = \"\"\n\n for vba_line in vba_content_lines:\n # Look for property start keywords.\n prop_start_pos = max(\n vba_line.find(\"Property Let \"), vba_line.find(\"Property Get \")\n )\n\n # Look for property end keywords.\n is_prop_end = vba_line.startswith(\"End Property\")\n\n # Check if we've reached the end of a property.\n if is_prop_end:\n inside_property = False\n continue\n\n # Check if we've hit a new property.\n elif prop_start_pos > -1:\n inside_property = True\n\n # Extract property name from declaration.\n if \"Property Let \" in vba_line or \"Property Get \" in vba_line:\n prop_name = (\n vba_line[\n (prop_start_pos + len(\"Property Let \")) : vba_line.find(\"(\")\n ]\n + \" (Property)\"\n )\n\n else:\n logging.error(\"Error parsing property name\")\n sys.exit(1)\n\n # Check if we are inside a property code.\n elif inside_property:\n if prop_name in vba_prop_dict:\n # Append code to to an existing property.\n vba_prop_dict[prop_name] += LINE_SEP + vba_line\n else:\n # Create a new property name inside the dict\n # & add the first line of code.\n vba_prop_dict[prop_name] = vba_line\n\n # We are in a global section code line.\n else:\n pass\n\n return vba_prop_dict","function_tokens":["def","vba_extract_properties","(","vba_content_lines",")",":","vba_prop_dict","=","{","}","inside_property","=","False","prop_name","=","\"\"","for","vba_line","in","vba_content_lines",":","# Look for property start keywords.","prop_start_pos","=","max","(","vba_line",".","find","(","\"Property Let \"",")",",","vba_line",".","find","(","\"Property Get \"",")",")","# Look for property end keywords.","is_prop_end","=","vba_line",".","startswith","(","\"End Property\"",")","# Check if we've reached the end of a property.","if","is_prop_end",":","inside_property","=","False","continue","# Check if we've hit a new property.","elif","prop_start_pos",">","-","1",":","inside_property","=","True","# Extract property name from declaration.","if","\"Property Let \"","in","vba_line","or","\"Property Get \"","in","vba_line",":","prop_name","=","(","vba_line","[","(","prop_start_pos","+","len","(","\"Property Let \"",")",")",":","vba_line",".","find","(","\"(\"",")","]","+","\" (Property)\"",")","else",":","logging",".","error","(","\"Error parsing property name\"",")","sys",".","exit","(","1",")","# Check if we are inside a property code.","elif","inside_property",":","if","prop_name","in","vba_prop_dict",":","# Append code to to an existing property.","vba_prop_dict","[","prop_name","]","+=","LINE_SEP","+","vba_line","else",":","# Create a new property name inside the dict","# & add the first line of code.","vba_prop_dict","[","prop_name","]","=","vba_line","# We are in a global section code line.","else",":","pass","return","vba_prop_dict"],"url":"https:\/\/github.com\/CERT-Polska\/drakvuf-sandbox\/blob\/765f58cc14ac822a70e605da1c935bc50bd02923\/drakrun\/drakrun\/vba_graph.py#L222-L280"}