Skip to content

Commit f89c890

Browse files
authored
ruff
1 parent 4451402 commit f89c890

File tree

109 files changed

+958
-665
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

109 files changed

+958
-665
lines changed

.github/workflows/python-package.yml

+3-8
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ jobs:
3737
poetry run pip install git+https://github.com/CAPESandbox/pyattck maco
3838
3939
- name: Run Ruff
40-
run: poetry run ruff check . --line-length 132 --ignore E501,E402
40+
run: poetry run ruff check . --output-format=github .
4141

4242
- name: Run unit tests
4343
run: poetry run python -m pytest --import-mode=append
@@ -63,20 +63,15 @@ jobs:
6363
with:
6464
python-version: ${{ matrix.python-version }}
6565

66-
- name: Format with black
67-
run: poetry run black .
68-
69-
# to be replaced with ruff
70-
- name: Format imports with isort
71-
run: poetry run isort .
72-
7366
- name: Commit changes if any
7467
# Skip this step if being run by nektos/act
7568
if: ${{ !env.ACT }}
7669
run: |
7770
git config user.name "GitHub Actions"
7871
git config user.email "[email protected]"
7972
if output=$(git status --porcelain) && [ ! -z "$output" ]; then
73+
git pull
74+
git add .
8075
git commit -m "style: Automatic code formatting" -a
8176
git push
8277
fi

agent/agent.py

-1
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,6 @@ def handle(self, obj):
227227
self.close_connection = True
228228

229229
def shutdown(self):
230-
231230
# BaseServer also features a .shutdown() method, but you can't use
232231
# that from the same thread as that will deadlock the whole thing.
233232
if hasattr(self, "s"):

analyzer/linux/analyzer.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def monitor_new_processes(parent_pid, interval=0.25):
7171
new_processes = current_processes - known_processes
7272

7373
for pid in new_processes:
74-
log.info(f"New child process detected: {pid}")
74+
log.info("New child process detected: %s", str(pid))
7575
dump_memory(pid)
7676
add_pids(pid) # Add the new process to PROCESS_LIST
7777

@@ -118,20 +118,20 @@ def dump_memory(pid):
118118
chunk = mem_file.read(end - start)
119119
output_file.write(chunk)
120120
except (OSError, ValueError) as e:
121-
log.error(f"Could not read memory range {start:x}-{end:x}: {e}")
121+
log.error("Could not read memory range %s: {e}", f"{start:x}-{end:x}", str(e))
122122
maps_file.close()
123123
mem_file.close()
124124
output_file.close()
125125
except FileNotFoundError:
126-
log.error(f"Process with PID {pid} not found.")
126+
log.error("Process with PID %s not found.", str(pid))
127127
except PermissionError:
128-
log.error(f"Permission denied to access process with PID {pid}.")
128+
log.error("Permission denied to access process with PID %s.", str(pid))
129129

130130
if os.path.exists(f"{MEM_PATH}/{pid}.dmp"):
131131
upload_to_host(f"{MEM_PATH}/{pid}.dmp", f"memory/{pid}.dmp")
132132
DUMPED_LIST.add(pid)
133133
else:
134-
log.error(f"Memdump file not found in guest machine for PID {pid}")
134+
log.error("Memdump file not found in guest machine for PID %s", str(pid))
135135

136136

137137
class Analyzer:

analyzer/linux/lib/api/screenshot.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ async def is_gnome(self):
139139
log.info("Detected non-Gnome desktop environment.")
140140
else:
141141
self._is_gnome = True
142-
log.info(f"Detected Gnome version {version}")
142+
log.info("Detected Gnome version %s", str(version))
143143
name = "org.gnome.Screenshot"
144144
resp = await self.bus.request_name(name)
145145
if resp not in (
@@ -205,8 +205,8 @@ async def take_screenshot_gnome(self):
205205
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
206206
<node>
207207
<interface name="org.gnome.Shell.Screenshot">
208-
<method name="Screenshot">
209-
<arg name="include_cursor" direction="in" type="b" />
208+
<method name="Screenshot">
209+
<arg name="include_cursor" direction="in" type="b" />
210210
<arg name="flash" direction="in" type="b" />
211211
<arg name="filename" direction="in" type="s" />
212212
<arg name="success" direction="out" type="b" />
@@ -260,7 +260,7 @@ async def handler(response, results):
260260
if response == 0:
261261
await queue.put(urllib.parse.urlparse(results["uri"].value).path)
262262
else:
263-
log.warning(f"Received non-zero response when taking screenshot: {response}")
263+
log.warning("Received non-zero response when taking screenshot: %s", str(response))
264264
await queue.put(None)
265265

266266
# Set up the signal handler

analyzer/linux/lib/common/results.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def upload_to_host(file_path, dump_path, pids="", ppids="", metadata="", categor
3838
nc.send(buf, retry=True)
3939
buf = infd.read(BUFSIZE)
4040
except Exception as e:
41-
log.error("Exception uploading file %s to host: %s", file_path, e, exc_info=True)
41+
log.exception("Exception uploading file %s to host: %s", file_path, e)
4242
finally:
4343
if nc:
4444
nc.close()

analyzer/linux/modules/auxiliary/filecollector.py

-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ def __init__(self, options, config):
5151
self.thread.join(0.5)
5252

5353
def run(self):
54-
5554
if not HAVE_PYINOTIFY:
5655
log.info("Missed dependency: pip3 install pyinotify")
5756
return False

analyzer/linux/modules/auxiliary/screenshots.py

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
if HAVE_PIL and HAVE_DBUS_NEXT:
1313
from PIL import Image
14+
1415
from lib.api.screenshot import Screenshot, ScreenshotGrabber, ScreenshotsUnsupported
1516

1617
from lib.common.abstracts import Auxiliary

analyzer/linux/modules/packages/zip.py

-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818

1919
class Zip(Package):
20-
2120
real_package = None
2221

2322
def prepare(self):

analyzer/windows/analyzer.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,7 @@ def analysis_loop(self, aux_modules):
691691
try:
692692
Process(pid=pid).upload_memdump()
693693
except Exception as e:
694-
log.error(e, exc_info=True)
694+
log.exception(e)
695695
log.info("Process with pid %s appears to have terminated", pid)
696696
if pid in self.process_list.pids:
697697
self.process_list.remove_pid(pid)
@@ -915,7 +915,7 @@ def dump_file(self, filepath, metadata="", pids="", ppids="", category="files"):
915915
except (IOError, socket.error) as e:
916916
log.error('Unable to upload dropped file at path "%s": %s', filepath, e)
917917
except Exception as e:
918-
log.error(e, exc_info=True)
918+
log.exception(e)
919919

920920
def delete_file(self, filepath, pid=None):
921921
"""A file is about to removed and thus should be dumped right away."""
@@ -1508,8 +1508,7 @@ def dispatch(self, data):
15081508
try:
15091509
response = fn(arguments)
15101510
except Exception as e:
1511-
log.error(e, exc_info=True)
1512-
log.exception("Pipe command handler exception occurred (command %s args %s)", command, arguments)
1511+
log.exception("Pipe command handler exception occurred (command %s args %s). %s", command, arguments, str(e))
15131512

15141513
return response
15151514

@@ -1536,7 +1535,7 @@ def dispatch(self, data):
15361535

15371536
# When user set wrong package, Example: Emotet package when submit doc, package only is for EXE!
15381537
except CuckooError:
1539-
log.info("You probably submitted the job with wrong package", exc_info=True)
1538+
log.exception("You probably submitted the job with wrong package")
15401539
data["status"] = "exception"
15411540
data["description"] = "You probably submitted the job with wrong package"
15421541
try:

analyzer/windows/lib/api/process.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@
4343
CAPEMON64_NAME,
4444
LOADER32_NAME,
4545
LOADER64_NAME,
46-
TTD32_NAME,
47-
TTD64_NAME,
4846
LOGSERVER_PREFIX,
4947
PATHS,
5048
PIPE,
5149
SHUTDOWN_MUTEX,
5250
TERMINATE_EVENT,
51+
TTD32_NAME,
52+
TTD64_NAME,
5353
)
5454
from lib.common.defines import (
5555
KERNEL32,
@@ -601,7 +601,6 @@ def is_64bit(self):
601601
return False
602602

603603
def write_monitor_config(self, interest=None, nosleepskip=False):
604-
605604
config_path = os.path.join(Path.cwd(), "dll", f"{self.pid}.ini")
606605
log.info("Monitor config for %s: %s", self, config_path)
607606

@@ -759,7 +758,7 @@ def upload_memdump(self):
759758
try:
760759
upload_to_host(file_path, os.path.join("memory", f"{self.pid}.dmp"), category="memory")
761760
except Exception as e:
762-
log.error(e, exc_info=True)
761+
log.exception(e)
763762
log.error(os.path.join("memory", f"{self.pid}.dmp"))
764763
log.error(file_path)
765764
log.info("Memory dump of %s uploaded", self)

analyzer/windows/lib/common/results.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def upload_to_host(file_path, dump_path, pids="", ppids="", metadata="", categor
6161
size -= read_size
6262
buf = infd.read(BUFSIZE)
6363
except Exception as e:
64-
log.error("Exception uploading file %s to host: %s", file_path, e, exc_info=True)
64+
log.exception("Exception uploading file %s to host: %s", file_path, e)
6565

6666

6767
def upload_buffer_to_host(buffer, dump_path, filepath=False, pids="", ppids="", metadata="", category="", duplicated=False):

analyzer/windows/lib/common/zip_utils.py

+10-14
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
11
import hashlib
22
import logging
33
import os
4+
import re
45
import shutil
56
import subprocess
67
from pathlib import Path
78
from zipfile import BadZipfile, ZipFile
89

9-
try:
10-
import re2 as re
11-
except ImportError:
12-
import re
13-
1410
from lib.common.constants import OPT_MULTI_PASSWORD
1511
from lib.common.exceptions import CuckooPackageError
1612
from lib.common.hashing import hash_file
@@ -61,7 +57,7 @@ def extract_archive(seven_zip_path, archive_path, extract_path, password="infect
6157
stdout=subprocess.PIPE,
6258
)
6359
stdoutput, stderr = p.stdout, p.stderr
64-
log.debug(f"{p.stdout} {p.stderr}")
60+
log.debug("%s %s", p.stdout, p.stderr)
6561

6662
if try_multiple_passwords:
6763
passwords = password.split(":")
@@ -85,9 +81,9 @@ def extract_archive(seven_zip_path, archive_path, extract_path, password="infect
8581
stdout=subprocess.PIPE,
8682
)
8783
stdoutput, stderr = p.stdout, p.stderr
88-
log.debug(f"{p.stdout} {p.stderr}")
84+
log.debug("%s - %s", p.stdout, p.stderr)
8985
if b"Wrong password" in stderr:
90-
log.debug(f"The provided password '{pword}' was incorrect")
86+
log.debug("The provided password '%s' was incorrect", str(pword))
9187
continue
9288
else:
9389
# We did it!
@@ -196,15 +192,15 @@ def extract_zip(zip_path, extract_path, password=b"infected", recursion_depth=1,
196192
raise CuckooPackageError("Invalid Zip file") from e
197193
except RuntimeError as e:
198194
if "Bad password for file" in repr(e):
199-
log.debug(f"Password '{pword}' was unsuccessful in extracting the archive.")
195+
log.debug("Password '%s' was unsuccessful in extracting the archive.", str(pword))
200196
password_fail = True
201197
continue
202198
else:
203199
# Try twice, just for kicks
204200
try:
205201
archive.extractall(path=extract_path, pwd=pword)
206202
except RuntimeError as e:
207-
raise CuckooPackageError(f"Unable to extract Zip file: {e}") from e
203+
raise CuckooPackageError("Unable to extract Zip file: %s", str(e)) from e
208204
finally:
209205
if recursion_depth < 4:
210206
# Extract nested archives.
@@ -228,7 +224,7 @@ def extract_zip(zip_path, extract_path, password=b"infected", recursion_depth=1,
228224
log.error("Error extracting nested Zip file %s with details: %s", name, run_err)
229225

230226
if password_fail:
231-
raise CuckooPackageError(f"Unable to extract password-protected Zip file with the password(s): {passwords}")
227+
raise CuckooPackageError("Unable to extract password-protected Zip file with the password(s): %s", str(passwords))
232228

233229

234230
def is_overwritten(zip_path):
@@ -265,7 +261,7 @@ def winrar_extractor(winrar_binary, extract_path, archive_path):
265261
stdout=subprocess.PIPE,
266262
)
267263
# stdoutput, stderr = p.stdout, p.stderr
268-
log.debug(p.stdout + p.stderr)
264+
log.debug("%s - %s", p.stdout, p.stderr)
269265

270266
return os.listdir(extract_path)
271267

@@ -290,11 +286,11 @@ def upload_extracted_files(root, files_at_root):
290286
for entry in files_at_root:
291287
try:
292288
file_path = os.path.join(root, entry)
293-
log.info("Uploading {0} to host".format(file_path))
289+
log.info("Uploading %s to host", str(file_path))
294290
filename = f"files/{hash_file(hashlib.sha256, file_path)}"
295291
upload_to_host(file_path, filename, metadata=Path(entry).name, duplicated=False)
296292
except Exception as e:
297-
log.warning(f"Couldn't upload file {Path(entry).name} to host {e}")
293+
log.warning("Couldn't upload file %s to host %s", str(Path(entry).name), str(e))
298294

299295

300296
def attempt_multiple_passwords(options: dict, password: str) -> bool:

analyzer/windows/lib/core/pipe.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def stop(self):
224224
if h.is_alive():
225225
h.stop()
226226
except Exception as e:
227-
log.error(e, exc_info=True)
227+
log.exception(e)
228228

229229

230230
def disconnect_pipes():

analyzer/windows/modules/auxiliary/amsi.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
import logging
3131
import sys
3232
import threading
33-
import traceback
3433
import uuid
3534

3635
logger = logging.getLogger(__name__)
@@ -945,7 +944,7 @@ def _unpackSimpleType(self, record, info, event_property):
945944

946945
# if there is no data remaining then return
947946
if user_data_remaining <= 0:
948-
logger.warning("No more user data left, returning none for field {:s}".format(name_field))
947+
logger.warning("No more user data left, returning none for field %s", str(name_field))
949948
return {name_field: None}
950949

951950
in_type = event_property.epi_u1.nonStructType.InType
@@ -986,7 +985,7 @@ def _unpackSimpleType(self, record, info, event_property):
986985

987986
if status != ERROR_SUCCESS:
988987
# We can handle this error and still capture the data.
989-
logger.warning("Failed to get data field data for {:s}, incrementing by reported size".format(name_field))
988+
logger.warning("Failed to get data field data for %s, incrementing by reported size", str(name_field))
990989
self.index += property_length
991990
return {name_field: None}
992991

@@ -1135,16 +1134,15 @@ def _processEvent(self, record):
11351134
if record.contents.EventHeader.Flags & EVENT_HEADER_FLAG_EXTENDED_INFO:
11361135
parsed_data["EventExtendedData"] = self._parseExtendedData(record)
11371136
except Exception as e:
1138-
logger.warning("Unable to parse event: {}".format(e))
1137+
logger.warning("Unable to parse event: %s", str(e))
11391138

11401139
try:
11411140
out.update(parsed_data)
11421141
# Call the user's specified callback function
11431142
if self.event_callback:
11441143
self.event_callback(out)
11451144
except Exception as e:
1146-
logger.error("Exception during callback: {}".format(e))
1147-
logger.error(traceback.format_exc())
1145+
logger.exception("Exception during callback: %s", str(e))
11481146

11491147

11501148
class TraceProperties:
@@ -1170,7 +1168,7 @@ def __init__(self, event_callback=None):
11701168
raise OSError("AMSI not supported on this platform") from err
11711169
self.provider = None
11721170
self.properties = TraceProperties()
1173-
self.session_name = "{:s}".format(str(uuid.uuid4()))
1171+
self.session_name = str(uuid.uuid4())
11741172
self.running = False
11751173
self.event_callback = event_callback
11761174
self.trace_logfile = None

analyzer/windows/modules/auxiliary/browsermonitor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def _find_browser_extension(self):
3535
for directory in temp_dir_list:
3636
# TOR Browser saves directly to %temp%
3737
if directory.startswith("bext_") and directory.endswith(".json"):
38-
log.debug(f"Found extension logs: {self.browser_logfile}")
38+
log.debug("Found extension logs: %s", self.browser_logfile)
3939
self.browser_logfile = os.path.join(temp_dir, directory)
4040
break
4141
tmp_directory_path = os.path.join(temp_dir, directory)
@@ -47,7 +47,7 @@ def _find_browser_extension(self):
4747
for file in tmp_dir_files:
4848
if file.startswith("bext_") and file.endswith(".json"):
4949
self.browser_logfile = os.path.join(temp_dir, directory, file)
50-
log.debug(f"Found extension logs: {self.browser_logfile}")
50+
log.debug("Found extension logs: %s", self.browser_logfile)
5151
break
5252
time.sleep(1)
5353

analyzer/windows/modules/auxiliary/disguise.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def add_persistent_route(self, gateway: str):
248248

249249
def start(self):
250250
if self.config.windows_static_route:
251-
log.info(f"Config for route is: {str(self.config.windows_static_route)}")
251+
log.info("Config for route is: %s", str(self.config.windows_static_route))
252252
self.add_persistent_route(self.config.windows_static_route_gateway)
253253
self.change_productid()
254254
self.set_office_mrus()

0 commit comments

Comments
 (0)