apply unsafe fixes (ruff check --unsafe-fixes --fix)

This commit is contained in:
Arthur Deierlein
2024-12-17 22:55:38 +01:00
parent ad7daafc50
commit a63ea662f4
28 changed files with 129 additions and 125 deletions
+1 -2
View File
@@ -84,8 +84,7 @@ class TestActionsDecoding(unittest.TestCase):
self.assertEqual(actions[0].action_type, scheduled_tasks.ActionType.Exe)
except Exception:
self.fail(
"ActionDecoder.decode should not raise exception:\n%s"
% traceback.format_exc()
f"ActionDecoder.decode should not raise exception:\n{traceback.format_exc()}"
)
+4 -5
View File
@@ -97,8 +97,7 @@ def class_subclasses(cls: Type[T]) -> Generator[Type[T], None, None]:
# The typing system is not clever enough to realize that clazz has a hidden attr after the hasattr check
if not hasattr(clazz, "hidden") or not clazz.hidden: # type: ignore
yield clazz
for return_value in class_subclasses(clazz):
yield return_value
yield from class_subclasses(clazz)
def import_files(base_module, ignore_errors: bool = False) -> List[str]:
@@ -159,9 +158,9 @@ def import_files(base_module, ignore_errors: bool = False) -> List[str]:
def _filter_files(filename: str):
"""Ensures that a filename traversed is an importable python file"""
return (
filename.endswith(".py") or filename.endswith(".pyc")
) and not filename.startswith("__")
return (filename.endswith((".py", ".pyc"))) and not filename.startswith(
"__"
)
def import_file(module: str, path: str, ignore_errors: bool = False) -> List[str]:
+1 -2
View File
@@ -54,8 +54,7 @@ class Lsmod(plugins.PluginInterface):
table_name = modules.vol.type_name.split(constants.BANG)[0]
for module in modules.to_list(table_name + constants.BANG + "module", "list"):
yield module
yield from modules.to_list(table_name + constants.BANG + "module", "list")
def _generator(self):
try:
+3 -1
View File
@@ -163,7 +163,9 @@ class Maps(plugins.PluginInterface):
address_list = self.config.get("address", None)
if not address_list:
# do not filter as no address_list was supplied
vma_filter_func = lambda _: True
def vma_filter_func(_):
return True
else:
# filter for any vm_start that matches the supplied address config
def vma_filter_function(x: interfaces.objects.ObjectInterface) -> bool:
@@ -372,7 +372,7 @@ class SockHandlers(interfaces.configuration.VersionableInterface):
bt_sock = sock.cast("bt_sock")
def bt_addr(addr):
return ":".join(reversed(["%02x" % x for x in addr.b]))
return ":".join(reversed([f"{x:02x}" for x in addr.b]))
src_addr = src_port = dst_addr = dst_port = None
bt_protocol = bt_sock.get_protocol()
@@ -93,10 +93,9 @@ class Check_sysctl(plugins.PluginInterface):
val = self._parse_global_variable_sysctls(kernel, name)
elif ctltype == "CTLTYPE_NODE":
if sysctl.oid_handler == 0:
for info in self._process_sysctl_list(
yield from self._process_sysctl_list(
kernel, sysctl.oid_arg1, recursive=1
):
yield info
)
val = "Node"
+1 -2
View File
@@ -119,8 +119,7 @@ class Kevents(interfaces.plugins.PluginInterface):
return None
for klist in klist_array:
for kn in mac.MacUtilities.walk_slist(klist, "kn_link"):
yield kn
yield from mac.MacUtilities.walk_slist(klist, "kn_link")
@classmethod
def _get_task_kevents(cls, kernel, task):
+1 -2
View File
@@ -49,8 +49,7 @@ class Mount(plugins.PluginInterface):
list_head = kernel.object_from_symbol(symbol_name="mountlist")
for mount in mac.MacUtilities.walk_tailq(list_head, "mnt_list"):
yield mount
yield from mac.MacUtilities.walk_tailq(list_head, "mnt_list")
def _generator(self):
for mount in self.list_mounts(self.context, self.config["kernel"]):
@@ -152,7 +152,9 @@ class Maps(interfaces.plugins.PluginInterface):
address_list = self.config.get("address", None)
if not address_list:
# do not filter as no address_list was supplied
vma_filter_func = lambda _: True
def vma_filter_func(_):
return True
else:
# filter for any vm_start that matches the supplied address config
def vma_filter_function(task: interfaces.objects.ObjectInterface) -> bool:
+3 -1
View File
@@ -83,7 +83,9 @@ class PsList(interfaces.plugins.PluginInterface):
@classmethod
def create_pid_filter(cls, pid_list: List[int] = None) -> Callable[[int], bool]:
filter_func = lambda _: False
def filter_func(_):
return False
# FIXME: mypy #4973 or #2608
pid_list = pid_list or []
filter_list = [x for x in pid_list if x is not None]
+1 -2
View File
@@ -204,8 +204,7 @@ class Timeliner(interfaces.plugins.PluginInterface):
)
vollog.log(logging.DEBUG, traceback.format_exc())
for data_item in sorted(data, key=self._sort_function):
yield data_item
yield from sorted(data, key=self._sort_function)
# Write out a body file if necessary
if self.config.get("create-bodyfile", True):
@@ -227,8 +227,7 @@ class Handles(interfaces.plugins.PluginInterface):
for entry in table:
if level > 0:
for x in self._make_handle_array(entry, level - 1, depth):
yield x
yield from self._make_handle_array(entry, level - 1, depth)
depth += 1
else:
handle_multiplier = 4
@@ -264,8 +263,7 @@ class Handles(interfaces.plugins.PluginInterface):
)
return None
for handle_table_entry in self._make_handle_array(TableCode, table_levels):
yield handle_table_entry
yield from self._make_handle_array(TableCode, table_levels)
def _generator(self, procs):
kernel = self.context.modules[self.config["kernel"]]
@@ -248,8 +248,7 @@ class Modules(interfaces.plugins.PluginInterface):
object_type=type_name, offset=list_entry.vol.offset - reloff, absolute=True
)
for mod in module.InLoadOrderLinks:
yield mod
yield from module.InLoadOrderLinks
def run(self):
return renderers.TreeGrid(
@@ -488,14 +488,13 @@ class NetStat(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterface):
"""
# first, TCP endpoints by parsing the partition table
for endpoint in cls.parse_partitions(
yield from cls.parse_partitions(
context,
layer_name,
net_symbol_table,
tcpip_symbol_table,
tcpip_module_offset,
):
yield endpoint
)
# then, towards the UDP and TCP port pools
# first, find their addresses
+24 -11
View File
@@ -126,15 +126,24 @@ class PsList(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterface):
Returns:
Filter function for passing to the `list_processes` method
"""
filter_func = lambda _: False
def filter_func(_):
return False
# FIXME: mypy #4973 or #2608
pid_list = pid_list or []
filter_list = [x for x in pid_list if x is not None]
if filter_list:
if exclude:
filter_func = lambda x: x.UniqueProcessId in filter_list
def filter_func(x):
return x.UniqueProcessId in filter_list
else:
filter_func = lambda x: x.UniqueProcessId not in filter_list
def filter_func(x):
return x.UniqueProcessId not in filter_list
return filter_func
@classmethod
@@ -173,20 +182,24 @@ class PsList(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterface):
Returns:
Filter function for passing to the `list_processes` method
"""
filter_func = lambda _: False
def filter_func(_):
return False
# FIXME: mypy #4973 or #2608
name_list = name_list or []
filter_list = [x for x in name_list if x is not None]
if filter_list:
if exclude:
filter_func = (
lambda x: utility.array_to_string(x.ImageFileName) in filter_list
)
def filter_func(x):
return utility.array_to_string(x.ImageFileName) in filter_list
else:
filter_func = (
lambda x: utility.array_to_string(x.ImageFileName)
not in filter_list
)
def filter_func(x):
return utility.array_to_string(x.ImageFileName) not in filter_list
return filter_func
@classmethod
+22 -13
View File
@@ -102,29 +102,38 @@ class PsScan(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterface):
Returns:
Filter function to be passed to the list of processes.
"""
filter_func = lambda _: False
def filter_func(_):
return False
if offset:
if physical:
if exclude:
filter_func = (
lambda proc: cls.physical_offset_from_virtual(
context, layer_name, proc
def filter_func(proc):
return (
cls.physical_offset_from_virtual(context, layer_name, proc)
== offset
)
== offset
)
else:
filter_func = (
lambda proc: cls.physical_offset_from_virtual(
context, layer_name, proc
def filter_func(proc):
return (
cls.physical_offset_from_virtual(context, layer_name, proc)
!= offset
)
!= offset
)
else:
if exclude:
filter_func = lambda proc: proc.vol.offset == offset
def filter_func(proc):
return proc.vol.offset == offset
else:
filter_func = lambda proc: proc.vol.offset != offset
def filter_func(proc):
return proc.vol.offset != offset
return filter_func
@@ -285,10 +285,9 @@ class ShimcacheMem(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterf
if not shim_head:
return
for shim_entry in shim_head.ListEntry.to_list(
yield from shim_head.ListEntry.to_list(
shimcache_symbol_table + constants.BANG + "SHIM_CACHE_ENTRY", "ListEntry"
):
yield shim_entry
)
@classmethod
def try_get_shim_head_at_offset(
@@ -333,7 +332,7 @@ class ShimcacheMem(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterf
eresource_rel_off = ersrc_size + ((offset - ersrc_size) % ersrc_alignment)
eresource_offset = offset - eresource_rel_off
vollog.debug("Constructing ERESOURCE at %s" % hex(eresource_offset))
vollog.debug(f"Constructing ERESOURCE at {hex(eresource_offset)}")
eresource = context.object(
kernel_symbol_table + constants.BANG + "_ERESOURCE",
layer_name,
@@ -103,11 +103,10 @@ class SvcList(svcscan.SvcScan):
scanner=scanners.BytesScanner(needle=b"Sc27"),
sections=exe_range,
):
for record in cls.enumerate_vista_or_later_header(
yield from cls.enumerate_vista_or_later_header(
context,
service_table_name,
service_binary_dll_map,
layer_name,
offset,
):
yield record
)
@@ -82,5 +82,4 @@ class Threads(thrdscan.ThrdScan):
symbol_table=symbol_table_name,
filter_func=filter_func,
):
for thread in cls.list_threads(module, proc):
yield thread
yield from cls.list_threads(module, proc)
@@ -116,8 +116,7 @@ class UnloadedModules(interfaces.plugins.PluginInterface, timeliner.TimeLinerInt
)
unloadedmodules_array.UnloadedDrivers.count = unloaded_count
for mod in unloadedmodules_array.UnloadedDrivers:
yield mod
yield from unloadedmodules_array.UnloadedDrivers
def _generator(self):
kernel = self.context.modules[self.config["kernel"]]
@@ -138,8 +138,7 @@ class VirtMap(interfaces.plugins.PluginInterface):
mapping = cls.determine_map(module)
for entry in mapping:
if "Unused" not in entry:
for value in mapping[entry]:
yield value
yield from mapping[entry]
def run(self):
kernel = self.context.modules[self.config["kernel"]]
+18 -12
View File
@@ -70,15 +70,21 @@ class MultiTypeData(bytes):
)
BinOrAbsent = lambda x: (
Bin(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
)
HexOrAbsent = lambda x: (
Hex(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
)
HexBytesOrAbsent = lambda x: (
HexBytes(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
)
MultiTypeDataOrAbsent = lambda x: (
MultiTypeData(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
)
def BinOrAbsent(x):
return Bin(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
def HexOrAbsent(x):
return Hex(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
def HexBytesOrAbsent(x):
return HexBytes(x) if not isinstance(x, interfaces.renderers.BaseAbsentValue) else x
def MultiTypeDataOrAbsent(x):
return (
MultiTypeData(x)
if not isinstance(x, interfaces.renderers.BaseAbsentValue)
else x
)
@@ -629,8 +629,7 @@ class IDStorage(ABC):
if self.is_valid_node(nodep):
yield nodep
else:
for child_node in self._iter_node(nodep, height - 1):
yield child_node
yield from self._iter_node(nodep, height - 1)
def get_entries(self, root: interfaces.objects.ObjectInterface) -> Iterator[int]:
"""Walks the tree data structure
@@ -659,8 +658,7 @@ class IDStorage(ABC):
if self.is_valid_node(nodep):
yield nodep
else:
for child_node in self._iter_node(nodep, height):
yield child_node
yield from self._iter_node(nodep, height)
class XArray(IDStorage):
@@ -200,8 +200,7 @@ class module(generic.GenericIntelProcess):
count=num_sects,
)
for attr in arr:
yield attr
yield from arr
def get_elf_table_name(self):
elf_table_name = intermed.IntermediateSymbolTable.create(
@@ -237,8 +236,7 @@ class module(generic.GenericIntelProcess):
count=self.num_symtab + 1,
)
if self.section_strtab:
for sym in syms:
yield sym
yield from syms
def get_symbols_names_and_addresses(self) -> Iterable[Tuple[str, int]]:
"""Get names and addresses for each symbol of the module
@@ -2665,8 +2663,7 @@ class IDR(objects.StructType):
id_storage = linux.IDStorage.choose_id_storage(
self._context, kernel_module_name="kernel"
)
for page_addr in id_storage.get_entries(root=self.idr_rt):
yield page_addr
yield from id_storage.get_entries(root=self.idr_rt)
def get_entries(self) -> Iterable[int]:
"""Walks the IDR and yield a pointer associated with each element.
@@ -2684,8 +2681,7 @@ class IDR(objects.StructType):
# Kernels < 4.11
get_entries_func = self._old_kernel_get_entries
for page_addr in get_entries_func():
yield page_addr
yield from get_entries_func()
class rb_root(objects.StructType):
@@ -232,10 +232,9 @@ class MacUtilities(interfaces.configuration.VersionableInterface):
next_member: str,
max_elements: int = 4096,
) -> Iterable[interfaces.objects.ObjectInterface]:
for element in cls._walk_iterable(
yield from cls._walk_iterable(
queue, "tqh_first", "tqe_next", next_member, max_elements
):
yield element
)
@classmethod
def walk_list_head(
@@ -244,10 +243,9 @@ class MacUtilities(interfaces.configuration.VersionableInterface):
next_member: str,
max_elements: int = 4096,
) -> Iterable[interfaces.objects.ObjectInterface]:
for element in cls._walk_iterable(
yield from cls._walk_iterable(
queue, "lh_first", "le_next", next_member, max_elements
):
yield element
)
@classmethod
def walk_slist(
@@ -256,7 +254,6 @@ class MacUtilities(interfaces.configuration.VersionableInterface):
next_member: str,
max_elements: int = 4096,
) -> Iterable[interfaces.objects.ObjectInterface]:
for element in cls._walk_iterable(
yield from cls._walk_iterable(
queue, "slh_first", "sle_next", next_member, max_elements
):
yield element
)
@@ -749,11 +749,10 @@ class EPROCESS(generic.GenericIntelProcess, pool.ExecutiveObject):
try:
peb = self.get_peb()
for entry in peb.Ldr.InLoadOrderModuleList.to_list(
yield from peb.Ldr.InLoadOrderModuleList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_LDR_DATA_TABLE_ENTRY",
"InLoadOrderLinks",
):
yield entry
)
except exceptions.InvalidAddressException:
return None
@@ -762,11 +761,10 @@ class EPROCESS(generic.GenericIntelProcess, pool.ExecutiveObject):
try:
peb = self.get_peb()
for entry in peb.Ldr.InInitializationOrderModuleList.to_list(
yield from peb.Ldr.InInitializationOrderModuleList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_LDR_DATA_TABLE_ENTRY",
"InInitializationOrderLinks",
):
yield entry
)
except exceptions.InvalidAddressException:
return None
@@ -775,11 +773,10 @@ class EPROCESS(generic.GenericIntelProcess, pool.ExecutiveObject):
try:
peb = self.get_peb()
for entry in peb.Ldr.InMemoryOrderModuleList.to_list(
yield from peb.Ldr.InMemoryOrderModuleList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_LDR_DATA_TABLE_ENTRY",
"InMemoryOrderLinks",
):
yield entry
)
except exceptions.InvalidAddressException:
return None
@@ -107,11 +107,10 @@ class EXE_ALIAS_LIST(objects.StructType):
def get_aliases(self) -> Generator[interfaces.objects.ObjectInterface, None, None]:
"""Generator for the individual aliases for a
particular executable."""
for alias in self.AliasList.to_list(
yield from self.AliasList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_ALIAS",
"ListEntry",
):
yield alias
)
class SCREEN_INFORMATION(objects.StructType):
@@ -245,11 +244,10 @@ class CONSOLE_INFORMATION(objects.StructType):
def get_histories(
self,
) -> Generator[interfaces.objects.ObjectInterface, None, None]:
for cmd_hist in self.HistoryList.to_list(
yield from self.HistoryList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_COMMAND_HISTORY",
"ListEntry",
):
yield cmd_hist
)
def get_exe_aliases(
self,
@@ -258,20 +256,18 @@ class CONSOLE_INFORMATION(objects.StructType):
# Windows 10 22000 and Server 20348 made this a Pointer
if isinstance(exe_alias_list, objects.Pointer):
exe_alias_list = exe_alias_list.dereference()
for exe_alias_list_item in exe_alias_list.to_list(
yield from exe_alias_list.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_EXE_ALIAS_LIST",
"ListEntry",
):
yield exe_alias_list_item
)
def get_processes(
self,
) -> Generator[interfaces.objects.ObjectInterface, None, None]:
for proc in self.ConsoleProcessList.to_list(
yield from self.ConsoleProcessList.to_list(
f"{self.get_symbol_table_name()}{constants.BANG}_CONSOLE_PROCESS_LIST",
"ListEntry",
):
yield proc
)
def get_title(self) -> Union[str, None]:
try:
@@ -393,8 +389,7 @@ class COMMAND_HISTORY(objects.StructType):
rest are coalesced.
"""
for i, cmd in self.scan_command_bucket(self.CommandBucket.End):
yield i, cmd
yield from self.scan_command_bucket(self.CommandBucket.End)
win10_x64_class_types = {
@@ -128,7 +128,10 @@ class PdbReader:
self._layer_name, self._context = self.load_pdb_layer(context, location)
self._dbiheader: Optional[interfaces.objects.ObjectInterface] = None
if not progress_callback:
progress_callback = lambda x, y: None
def progress_callback(x, y):
return None
self._progress_callback = progress_callback
self.types: List[
Tuple[