Skip to content

Commit d7022f3

Browse files
committed
Refactor file handling to use context managers
Replaced manual open/close file operations with 'with' statements across multiple modules for safer and cleaner resource management. This change improves code readability, ensures files are properly closed, and reduces the risk of resource leaks. Also includes minor logic improvements in modules/processing/tracee.py for process tree construction and log parsing.
1 parent 6ae1f9f commit d7022f3

File tree

15 files changed

+207
-188
lines changed

15 files changed

+207
-188
lines changed

analyzer/linux/modules/auxiliary/sysmon.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,11 @@ def collect_logs(self):
5050
'"Linux-Sysmon"',
5151
]
5252
try:
53-
_ = subprocess.run(
54-
args,
55-
stdout=open(SYSMON_LOG_PATH, "wb"),
56-
)
53+
with open(SYSMON_LOG_PATH, "wb") as f:
54+
_ = subprocess.run(
55+
args,
56+
stdout=f,
57+
)
5758
except Exception as e:
5859
log.error("Could not create sysmon log file - %s", e)
5960

analyzer/windows/modules/auxiliary/curtain.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,20 @@ def __init__(self, options=None, config=None):
2727

2828
def collectLogs(self):
2929
try:
30-
subprocess.call(
31-
[
32-
"C:\\Windows\\System32\\wevtutil.exe",
33-
"query-events",
34-
"microsoft-windows-powershell/operational",
35-
"/rd:true",
36-
"/e:root",
37-
"/format:xml",
38-
"/uni:true",
39-
],
40-
startupinfo=self.startupinfo,
41-
stdout=open("C:\\curtain.log", "w"),
42-
)
30+
with open("C:\\curtain.log", "w") as f:
31+
subprocess.call(
32+
[
33+
"C:\\Windows\\System32\\wevtutil.exe",
34+
"query-events",
35+
"microsoft-windows-powershell/operational",
36+
"/rd:true",
37+
"/e:root",
38+
"/format:xml",
39+
"/uni:true",
40+
],
41+
startupinfo=self.startupinfo,
42+
stdout=f,
43+
)
4344
except Exception as e:
4445
log.error("Curtain - Error collecting PowerShell events - %s", e)
4546

analyzer/windows/modules/auxiliary/hollowshunter.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,8 @@ def stop(self):
108108
# We first care about modules that contain PEs
109109
if scan_report_json in only_files:
110110
scan_report_path = os.path.join(dirpath, scan_report_json)
111-
report_json = json.loads(open(scan_report_path, "rb").read())
111+
with open(scan_report_path, "rb") as f:
112+
report_json = json.loads(f.read())
112113
scans = report_json["scans"]
113114
for scan in scans:
114115
if "workingset_scan" in scan:
@@ -142,7 +143,8 @@ def stop(self):
142143

143144
log.debug(file_path)
144145
try:
145-
file_contents = open(file_path, "rb").read()
146+
with open(file_path, "rb") as f:
147+
file_contents = f.read()
146148
if any(item in file_contents for item in strings_of_interest):
147149
# We got a hit!
148150
files_to_upload.add(file_path)

analyzer/windows/modules/auxiliary/sysmon.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,19 @@ def clear_log(self):
4141
def collect_logs(self):
4242
sysmon_xml_path = "C:\\sysmon.xml"
4343
try:
44-
subprocess.call(
45-
(
46-
"C:\\Windows\\System32\\wevtutil.exe",
47-
"query-events",
48-
"microsoft-windows-sysmon/operational",
49-
"/rd:true",
50-
"/e:Events",
51-
"/format:xml",
52-
),
53-
startupinfo=self.startupinfo,
54-
stdout=open(sysmon_xml_path, "w"),
55-
)
44+
with open(sysmon_xml_path, "w") as f:
45+
subprocess.call(
46+
(
47+
"C:\\Windows\\System32\\wevtutil.exe",
48+
"query-events",
49+
"microsoft-windows-sysmon/operational",
50+
"/rd:true",
51+
"/e:Events",
52+
"/format:xml",
53+
),
54+
startupinfo=self.startupinfo,
55+
stdout=f,
56+
)
5657
except Exception as e:
5758
log.error("Could not create sysmon log file - %s", e)
5859

data/trid/tridupdate.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,9 @@ def MD5digest(filename=None, data=None):
3939
"""Return an MD5 digest for a file or a string."""
4040
h = hashlib.md5()
4141
if filename:
42-
f = open(filename, "rb")
43-
for data in chunked(f, 1024 * 1024):
44-
h.update(data)
45-
f.close()
42+
with open(filename, "rb") as f:
43+
for data in chunked(f, 1024 * 1024):
44+
h.update(data)
4645
elif data:
4746
h.update(data)
4847
return h.hexdigest()
@@ -104,9 +103,8 @@ def main():
104103

105104
print("Checking defs integrity...")
106105
if MD5digest(data=trdpack) == newdigest:
107-
f = open(trdfilename, "wb")
108-
f.write(trdpack)
109-
f.close()
106+
with open(trdfilename, "wb") as f:
107+
f.write(trdpack)
110108
print("OK.")
111109
else:
112110
errexit("Digest don't match. Retry!")

modules/processing/hollowshunter.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ def run(self):
3333
for report in report_list:
3434
report_path = os.path.join(hh_path, report)
3535
try:
36-
report_contents = open(report_path).read()
36+
with open(report_path) as f:
37+
report_contents = f.read()
3738
report_json = json.loads(report_contents)
3839
except Exception as e:
3940
raise CuckooProcessingError("Failed parsing report %s due to %s" % (report_path, str(e)))

modules/processing/sysmon.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,13 @@ def run(self):
8585
data = None
8686
try:
8787
if windows:
88-
xml = open(sysmon_path, "rb").read()
88+
with open(sysmon_path, "rb") as f:
89+
xml = f.read()
8990
xml = xml.decode("latin1").encode("utf8")
9091
data = xmltodict.parse(xml)["Events"]["Event"]
9192
elif linux:
92-
journalctl_output = open(sysmon_path, "rb").readlines()
93+
with open(sysmon_path, "rb") as f:
94+
journalctl_output = f.readlines()
9395
xml = massage_linux_data(journalctl_output)
9496
data = xmltodict.parse(xml)["Events"]["Event"]
9597
else:

0 commit comments

Comments
 (0)