From e0abdd92f2889e3841197573393d87c8c31d2a68 Mon Sep 17 00:00:00 2001 From: David McDonald Date: Tue, 13 May 2025 17:52:12 -0500 Subject: [PATCH 01/25] Windows Thrdscan: Fix broken tuple unpacking Timeliner fails due to an incorrect unpacking of this tuple, which needs 3 additional dictionary items for start path, win32 start path, and win32 start address. --- volatility3/framework/plugins/windows/thrdscan.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/volatility3/framework/plugins/windows/thrdscan.py b/volatility3/framework/plugins/windows/thrdscan.py index d5a1a0b07..082b82284 100644 --- a/volatility3/framework/plugins/windows/thrdscan.py +++ b/volatility3/framework/plugins/windows/thrdscan.py @@ -190,6 +190,9 @@ class ThrdScan(interfaces.plugins.PluginInterface, timeliner.TimeLinerInterface) row_dict["PID"], row_dict["TID"], row_dict["StartAddress"], + row_dict["StartPath"], + row_dict["Win32StartAddress"], + row_dict["Win32StartPath"], row_dict["CreateTime"], row_dict["ExitTime"], ) = row_data From 90a3829ee766f3ef5530ef061389e7f343ba96b8 Mon Sep 17 00:00:00 2001 From: David McDonald Date: Thu, 15 May 2025 17:28:26 -0500 Subject: [PATCH 02/25] Windows Timeliner: Add basic test This is enough to ensure that the return code is nonzero and there was some valid output. --- test/plugins/windows/windows.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/plugins/windows/windows.py b/test/plugins/windows/windows.py index 4272b64d2..0f44ba533 100644 --- a/test/plugins/windows/windows.py +++ b/test/plugins/windows/windows.py @@ -58,6 +58,14 @@ class TestWindowsPslist: } assert test_volatility.match_output_row(expected_row, json.loads(out)) +class TestWindowsTimeliner: + def test_windows_specific_timeliner(self, volatility, python): + image = WindowsSamples.WINDOWSXP_GENERIC.value.path + rc, out, _err = test_volatility.runvol_plugin( + "timeliner.Timeliner", image, volatility, python + ) + assert rc == 0 + assert out.count(b"\n") > 10 class TestWindowsPsscan: def test_windows_specific_psscan(self, volatility, python): From e5738c126380a7624702ec4ee95fdb53dc7ed81d Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 14:03:36 +0300 Subject: [PATCH 03/25] categorize windows.psxview as malware plugin --- .../plugins/windows/malware/psxview.py | 241 ++++++++++++++++++ .../framework/plugins/windows/psxview.py | 237 +---------------- 2 files changed, 255 insertions(+), 223 deletions(-) create mode 100644 volatility3/framework/plugins/windows/malware/psxview.py diff --git a/volatility3/framework/plugins/windows/malware/psxview.py b/volatility3/framework/plugins/windows/malware/psxview.py new file mode 100644 index 000000000..51616a22c --- /dev/null +++ b/volatility3/framework/plugins/windows/malware/psxview.py @@ -0,0 +1,241 @@ +import datetime +import logging +import string +from itertools import chain +from typing import Dict, Iterable, List + +from volatility3.framework import constants, exceptions, renderers +from volatility3.framework.configuration import requirements +from volatility3.framework.interfaces import plugins +from volatility3.framework.renderers import format_hints +from volatility3.framework.symbols.windows import extensions +from volatility3.plugins.windows import handles, pslist, psscan, thrdscan + +vollog = logging.getLogger(__name__) + + +class PsXView(plugins.PluginInterface): + """Lists all processes found via four of the methods described in \"The Art of Memory Forensics\" which may help \ +identify processes that are trying to hide themselves. + +We recommend using -r pretty if you are looking at this plugin's output in a terminal.""" + + # I've omitted the desktop thread scanning method because Volatility3 doesn't appear to have the functionality + # which the original plugin used to do it. + + # The sessions method is omitted because it begins with the list of processes found by Pslist anyway. + + # Lastly, I've omitted the pspcid method because I could not for the life of me get it to work. I saved the + # code I do have from it, and will happily share it if anyone else wants to add it. + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 0) + + valid_proc_name_chars = set( + string.ascii_lowercase + string.ascii_uppercase + "." + " " + ) + + @classmethod + def get_requirements(cls): + return [ + requirements.ModuleRequirement( + name="kernel", + description="Windows kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="pslist", component=pslist.PsList, version=(3, 0, 0) + ), + requirements.VersionRequirement( + name="psscan", component=psscan.PsScan, version=(2, 0, 0) + ), + requirements.VersionRequirement( + name="thrdscan", component=thrdscan.ThrdScan, version=(2, 0, 0) + ), + requirements.VersionRequirement( + name="handles", component=handles.Handles, version=(4, 0, 0) + ), + requirements.BooleanRequirement( + name="physical-offsets", + description="List processes with physical offsets instead of virtual offsets.", + optional=True, + ), + ] + + def _proc_name_to_string(self, proc): + return proc.ImageFileName.cast( + "string", max_length=proc.ImageFileName.vol.count, errors="replace" + ) + + def _is_valid_proc_name(self, string: str) -> bool: + return all(c in self.valid_proc_name_chars for c in string) + + def _filter_garbage_procs( + self, proc_list: Iterable[extensions.EPROCESS] + ) -> List[extensions.EPROCESS]: + return [ + p + for p in proc_list + if p.is_valid() and self._is_valid_proc_name(self._proc_name_to_string(p)) + ] + + def _translate_offset(self, offset: int) -> int: + if not self.config["physical-offsets"]: + return offset + + kernel = self.context.modules[self.config["kernel"]] + layer_name = kernel.layer_name + + try: + _original_offset, _original_length, offset, _length, _layer_name = list( + self.context.layers[layer_name].mapping(offset=offset, length=0) + )[0] + except exceptions.PagedInvalidAddressException: + vollog.debug(f"Page fault: unable to translate {offset:0x}") + + return offset + + def _proc_list_to_dict( + self, tasks: Iterable[extensions.EPROCESS] + ) -> Dict[int, extensions.EPROCESS]: + tasks = self._filter_garbage_procs(tasks) + return {self._translate_offset(proc.vol.offset): proc for proc in tasks} + + def _check_pslist(self, tasks): + return self._proc_list_to_dict(tasks) + + def _check_psscan( + self, + ) -> Dict[int, extensions.EPROCESS]: + res = psscan.PsScan.scan_processes( + context=self.context, kernel_module_name=self.config["kernel"] + ) + + return self._proc_list_to_dict(res) + + def _check_thrdscan(self) -> Dict[int, extensions.EPROCESS]: + ret = [] + + for ethread in thrdscan.ThrdScan.scan_threads( + self.context, module_name="kernel" + ): + process = None + try: + process = ethread.owning_process() + if not process.is_valid(): + continue + + ret.append(process) + except AttributeError: + vollog.log( + constants.LOGLEVEL_VVV, + "Unable to find the owning process of ethread", + ) + + return self._proc_list_to_dict(ret) + + def _check_csrss_handles( + self, tasks: Iterable[extensions.EPROCESS] + ) -> Dict[int, extensions.EPROCESS]: + ret: List[extensions.EPROCESS] = [] + + type_map = handles.Handles.get_type_map( + context=self.context, kernel_module_name=self.config["kernel"] + ) + + cookie = handles.Handles.find_cookie( + context=self.context, kernel_module_name=self.config["kernel"] + ) + + for p in tasks: + name = self._proc_name_to_string(p) + if name != "csrss.exe": + continue + + try: + ret += [ + handle.Body.cast("_EPROCESS") + for handle in handles.Handles.handles( + context=self.context, + kernel_module_name=self.config["kernel"], + handle_table=p.ObjectTable, + ) + if handle.get_object_type(type_map, cookie) == "Process" + ] + except exceptions.InvalidAddressException: + vollog.log( + constants.LOGLEVEL_VVV, "Cannot access eprocess object table" + ) + + return self._proc_list_to_dict(ret) + + def _generator(self): + kdbg_list_processes = list( + pslist.PsList.list_processes( + context=self.context, kernel_module_name=self.config["kernel"] + ) + ) + + # get processes from each source + processes: Dict[str, Dict[int, extensions.EPROCESS]] = {} + + processes["pslist"] = self._check_pslist(kdbg_list_processes) + processes["psscan"] = self._check_psscan() + processes["thrdscan"] = self._check_thrdscan() + processes["csrss"] = self._check_csrss_handles(kdbg_list_processes) + + # Unique set of all offsets from all sources + offsets = set(chain(*(mapping.keys() for mapping in processes.values()))) + + for offset in offsets: + # We know there will be at least one process mapped to each offset + proc: extensions.EPROCESS = next( + mapping[offset] for mapping in processes.values() if offset in mapping + ) + + in_sources = {src: False for src in processes} + + for source, process_mapping in processes.items(): + if offset in process_mapping: + in_sources[source] = True + + pid = proc.UniqueProcessId + name = self._proc_name_to_string(proc) + + exit_time = proc.get_exit_time() + if type(exit_time) is not datetime.datetime: + exit_time = "" + else: + exit_time = str(exit_time) + + yield ( + 0, + ( + format_hints.Hex(offset), + name, + pid, + in_sources["pslist"], + in_sources["psscan"], + in_sources["thrdscan"], + in_sources["csrss"], + exit_time, + ), + ) + + def run(self): + offset_type = "(Physical)" if self.config["physical-offsets"] else "(Virtual)" + offset_str = "Offset" + offset_type + + return renderers.TreeGrid( + [ + (offset_str, format_hints.Hex), + ("Name", str), + ("PID", int), + ("pslist", bool), + ("psscan", bool), + ("thrdscan", bool), + ("csrss", bool), + ("Exit Time", str), + ], + self._generator(), + ) diff --git a/volatility3/framework/plugins/windows/psxview.py b/volatility3/framework/plugins/windows/psxview.py index 51616a22c..625f02387 100644 --- a/volatility3/framework/plugins/windows/psxview.py +++ b/volatility3/framework/plugins/windows/psxview.py @@ -1,24 +1,24 @@ -import datetime +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# import logging -import string -from itertools import chain -from typing import Dict, Iterable, List - -from volatility3.framework import constants, exceptions, renderers -from volatility3.framework.configuration import requirements -from volatility3.framework.interfaces import plugins -from volatility3.framework.renderers import format_hints -from volatility3.framework.symbols.windows import extensions -from volatility3.plugins.windows import handles, pslist, psscan, thrdscan +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.windows.malware import psxview vollog = logging.getLogger(__name__) -class PsXView(plugins.PluginInterface): +class PsXView( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=psxview.PsXView, + removal_date="2026-06-07", +): """Lists all processes found via four of the methods described in \"The Art of Memory Forensics\" which may help \ -identify processes that are trying to hide themselves. + identify processes that are trying to hide themselves. -We recommend using -r pretty if you are looking at this plugin's output in a terminal.""" + We recommend using -r pretty if you are looking at this plugin's output in a terminal. + deprecated.""" # I've omitted the desktop thread scanning method because Volatility3 doesn't appear to have the functionality # which the original plugin used to do it. @@ -30,212 +30,3 @@ We recommend using -r pretty if you are looking at this plugin's output in a ter _required_framework_version = (2, 0, 0) _version = (1, 0, 0) - - valid_proc_name_chars = set( - string.ascii_lowercase + string.ascii_uppercase + "." + " " - ) - - @classmethod - def get_requirements(cls): - return [ - requirements.ModuleRequirement( - name="kernel", - description="Windows kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="pslist", component=pslist.PsList, version=(3, 0, 0) - ), - requirements.VersionRequirement( - name="psscan", component=psscan.PsScan, version=(2, 0, 0) - ), - requirements.VersionRequirement( - name="thrdscan", component=thrdscan.ThrdScan, version=(2, 0, 0) - ), - requirements.VersionRequirement( - name="handles", component=handles.Handles, version=(4, 0, 0) - ), - requirements.BooleanRequirement( - name="physical-offsets", - description="List processes with physical offsets instead of virtual offsets.", - optional=True, - ), - ] - - def _proc_name_to_string(self, proc): - return proc.ImageFileName.cast( - "string", max_length=proc.ImageFileName.vol.count, errors="replace" - ) - - def _is_valid_proc_name(self, string: str) -> bool: - return all(c in self.valid_proc_name_chars for c in string) - - def _filter_garbage_procs( - self, proc_list: Iterable[extensions.EPROCESS] - ) -> List[extensions.EPROCESS]: - return [ - p - for p in proc_list - if p.is_valid() and self._is_valid_proc_name(self._proc_name_to_string(p)) - ] - - def _translate_offset(self, offset: int) -> int: - if not self.config["physical-offsets"]: - return offset - - kernel = self.context.modules[self.config["kernel"]] - layer_name = kernel.layer_name - - try: - _original_offset, _original_length, offset, _length, _layer_name = list( - self.context.layers[layer_name].mapping(offset=offset, length=0) - )[0] - except exceptions.PagedInvalidAddressException: - vollog.debug(f"Page fault: unable to translate {offset:0x}") - - return offset - - def _proc_list_to_dict( - self, tasks: Iterable[extensions.EPROCESS] - ) -> Dict[int, extensions.EPROCESS]: - tasks = self._filter_garbage_procs(tasks) - return {self._translate_offset(proc.vol.offset): proc for proc in tasks} - - def _check_pslist(self, tasks): - return self._proc_list_to_dict(tasks) - - def _check_psscan( - self, - ) -> Dict[int, extensions.EPROCESS]: - res = psscan.PsScan.scan_processes( - context=self.context, kernel_module_name=self.config["kernel"] - ) - - return self._proc_list_to_dict(res) - - def _check_thrdscan(self) -> Dict[int, extensions.EPROCESS]: - ret = [] - - for ethread in thrdscan.ThrdScan.scan_threads( - self.context, module_name="kernel" - ): - process = None - try: - process = ethread.owning_process() - if not process.is_valid(): - continue - - ret.append(process) - except AttributeError: - vollog.log( - constants.LOGLEVEL_VVV, - "Unable to find the owning process of ethread", - ) - - return self._proc_list_to_dict(ret) - - def _check_csrss_handles( - self, tasks: Iterable[extensions.EPROCESS] - ) -> Dict[int, extensions.EPROCESS]: - ret: List[extensions.EPROCESS] = [] - - type_map = handles.Handles.get_type_map( - context=self.context, kernel_module_name=self.config["kernel"] - ) - - cookie = handles.Handles.find_cookie( - context=self.context, kernel_module_name=self.config["kernel"] - ) - - for p in tasks: - name = self._proc_name_to_string(p) - if name != "csrss.exe": - continue - - try: - ret += [ - handle.Body.cast("_EPROCESS") - for handle in handles.Handles.handles( - context=self.context, - kernel_module_name=self.config["kernel"], - handle_table=p.ObjectTable, - ) - if handle.get_object_type(type_map, cookie) == "Process" - ] - except exceptions.InvalidAddressException: - vollog.log( - constants.LOGLEVEL_VVV, "Cannot access eprocess object table" - ) - - return self._proc_list_to_dict(ret) - - def _generator(self): - kdbg_list_processes = list( - pslist.PsList.list_processes( - context=self.context, kernel_module_name=self.config["kernel"] - ) - ) - - # get processes from each source - processes: Dict[str, Dict[int, extensions.EPROCESS]] = {} - - processes["pslist"] = self._check_pslist(kdbg_list_processes) - processes["psscan"] = self._check_psscan() - processes["thrdscan"] = self._check_thrdscan() - processes["csrss"] = self._check_csrss_handles(kdbg_list_processes) - - # Unique set of all offsets from all sources - offsets = set(chain(*(mapping.keys() for mapping in processes.values()))) - - for offset in offsets: - # We know there will be at least one process mapped to each offset - proc: extensions.EPROCESS = next( - mapping[offset] for mapping in processes.values() if offset in mapping - ) - - in_sources = {src: False for src in processes} - - for source, process_mapping in processes.items(): - if offset in process_mapping: - in_sources[source] = True - - pid = proc.UniqueProcessId - name = self._proc_name_to_string(proc) - - exit_time = proc.get_exit_time() - if type(exit_time) is not datetime.datetime: - exit_time = "" - else: - exit_time = str(exit_time) - - yield ( - 0, - ( - format_hints.Hex(offset), - name, - pid, - in_sources["pslist"], - in_sources["psscan"], - in_sources["thrdscan"], - in_sources["csrss"], - exit_time, - ), - ) - - def run(self): - offset_type = "(Physical)" if self.config["physical-offsets"] else "(Virtual)" - offset_str = "Offset" + offset_type - - return renderers.TreeGrid( - [ - (offset_str, format_hints.Hex), - ("Name", str), - ("PID", int), - ("pslist", bool), - ("psscan", bool), - ("thrdscan", bool), - ("csrss", bool), - ("Exit Time", str), - ], - self._generator(), - ) From 66473ac644a89e685f050463f44e04f3a7eb07ab Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 18:00:36 +0300 Subject: [PATCH 04/25] categorize windows.unhooked_system_calls as a malware plugin --- .../windows/malware/unhooked_system_calls.py | 202 +++++++++++++++++ .../plugins/windows/unhooked_system_calls.py | 204 +----------------- 2 files changed, 213 insertions(+), 193 deletions(-) create mode 100644 volatility3/framework/plugins/windows/malware/unhooked_system_calls.py diff --git a/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py b/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py new file mode 100644 index 000000000..5723ce0fd --- /dev/null +++ b/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py @@ -0,0 +1,202 @@ +# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 + +# Full details on the techniques used in these plugins to detect EDR-evading malware +# can be found in our 20 page whitepaper submitted to DEFCON along with the presentation +# https://www.volexity.com/wp-content/uploads/2024/08/Defcon24_EDR_Evasion_Detection_White-Paper_Andrew-Case.pdf + +import logging + +from typing import Dict, Tuple, List, Generator + +from volatility3.framework import interfaces, exceptions +from volatility3.framework import renderers +from volatility3.framework.configuration import requirements +from volatility3.framework.objects import utility +from volatility3.plugins.windows import pslist, pe_symbols + +vollog = logging.getLogger(__name__) + + +class unhooked_system_calls(interfaces.plugins.PluginInterface): + """Detects hooked ntdll.dll stub functions in Windows processes.""" + + _required_framework_version = (2, 4, 0) + _version = (2, 0, 0) + + system_calls = { + "ntdll.dll": { + pe_symbols.wanted_names_identifier: [ + "NtCreateThread", + "NtProtectVirtualMemory", + "NtReadVirtualMemory", + "NtOpenProcess", + "NtWriteFile", + "NtQueryVirtualMemory", + "NtAllocateVirtualMemory", + "NtWorkerFactoryWorkerReady", + "NtAcceptConnectPort", + "NtAddDriverEntry", + "NtAdjustPrivilegesToken", + "NtAlpcCreatePort", + "NtClose", + "NtCreateFile", + "NtCreateMutant", + "NtOpenFile", + "NtOpenIoCompletion", + "NtOpenJobObject", + "NtOpenKey", + "NtOpenKeyEx", + "NtOpenThread", + "NtOpenThreadToken", + "NtOpenThreadTokenEx", + "NtWriteVirtualMemory", + "NtTraceEvent", + "NtTranslateFilePath", + "NtUmsThreadYield", + "NtUnloadDriver", + "NtUnloadKey", + "NtUnloadKey2", + "NtUnloadKeyEx", + "NtCreateKey", + "NtCreateSection", + "NtDeleteKey", + "NtDeleteValueKey", + "NtDuplicateObject", + "NtQueryValueKey", + "NtReplaceKey", + "NtRequestWaitReplyPort", + "NtRestoreKey", + "NtSetContextThread", + "NtSetSecurityObject", + "NtSetValueKey", + "NtSystemDebugControl", + "NtTerminateProcess", + ] + } + } + + # This data structure is used to track unique implementations of functions across processes + # The outer dictionary holds the module name (e.g., ntdll.dll) + # The next dictionary holds the function names (NtTerminateProcess, NtSetValueKey, etc.) inside a module + # The innermost dictionary holds the unique implementation (bytes) of a function across processes + # Each implementation is tracked along with the process(es) that host it + # For systems without malware, all functions should have the same implementation + # When API hooking/module unhooking is done, the victim (infected) processes will have unique implementations + _code_bytes_type = Dict[str, Dict[str, Dict[bytes, List[Tuple[int, str]]]]] + + @classmethod + def get_requirements(cls) -> List: + # Since we're calling the plugin, make sure we have the plugin's requirements + return [ + requirements.ModuleRequirement( + name="kernel", + description="Windows kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="pslist", component=pslist.PsList, version=(3, 0, 0) + ), + requirements.VersionRequirement( + name="pe_symbols", component=pe_symbols.PESymbols, version=(3, 0, 0) + ), + ] + + def _gather_code_bytes( + self, + kernel_module_name: str, + found_symbols: pe_symbols.found_symbols_type, + ) -> _code_bytes_type: + """ + Enumerates the desired DLLs and function implementations in each process + Groups based on unique implementations of each DLLs' functions + The purpose is to detect when a function has different implementations (code) + in different processes. + This very effectively detects code injection. + """ + code_bytes: unhooked_system_calls._code_bytes_type = {} + + procs = pslist.PsList.list_processes(self.context, kernel_module_name) + + for proc in procs: + try: + proc_id = proc.UniqueProcessId + proc_name = utility.array_to_string(proc.ImageFileName) + proc_layer_name = proc.add_process_layer() + except exceptions.InvalidAddressException: + continue + + for dll_name, functions in found_symbols.items(): + for func_name, func_addr in functions: + try: + fbytes = self.context.layers[proc_layer_name].read( + func_addr, 0x20 + ) + except exceptions.InvalidAddressException: + continue + + # see the definition of _code_bytes_type for details of this data structure + if dll_name not in code_bytes: + code_bytes[dll_name] = {} + + if func_name not in code_bytes[dll_name]: + code_bytes[dll_name][func_name] = {} + + if fbytes not in code_bytes[dll_name][func_name]: + code_bytes[dll_name][func_name][fbytes] = [] + + code_bytes[dll_name][func_name][fbytes].append((proc_id, proc_name)) + + return code_bytes + + def _generator(self) -> Generator[Tuple[int, Tuple[str, str, int]], None, None]: + found_symbols = pe_symbols.PESymbols.addresses_for_process_symbols( + context=self.context, + config_path=self.config_path, + kernel_module_name=self.config["kernel"], + symbols=unhooked_system_calls.system_calls, + ) + + # code_bytes[dll_name][func_name][func_bytes] + code_bytes = self._gather_code_bytes(self.config["kernel"], found_symbols) + + # walk the functions that were evaluated + for functions in code_bytes.values(): + # cbb is the distinct groups of bytes (instructions) + # for this function across processes + for func_name, cbb in functions.items(): + # the dict key here is the raw instructions, which is not helpful to look at + # the values are the list of tuples for the (proc_id, proc_name) pairs for this set of bytes (instructions) + cb = list(cbb.values()) + + # if all processes map to the same implementation, then no malware is present + if len(cb) == 1: + yield 0, (func_name, "", len(cb[0])) + else: + # if there are differing implementations then it means + # that malware has overwritten system call(s) in infected processes + # max_idx and small_idx find which implementation of a system call has the least processes + # as all observed malware and open source projects only infected a few targets, leaving the + # rest with the original EDR hooks in place + max_idx = 0 if len(cb[0]) > len(cb[1]) else 1 + small_idx = (~max_idx) & 1 + + ps = [] + + # gather processes on small_idx since these are the malware infected ones + for pid, pname in cb[small_idx]: + ps.append(f"{pid:d}:{pname}") + + proc_names = ", ".join(ps) + + yield 0, (func_name, proc_names, len(cb[max_idx])) + + def run(self) -> renderers.TreeGrid: + return renderers.TreeGrid( + [ + ("Function", str), + ("Distinct Implementations", str), + ("Total Implementations", int), + ], + self._generator(), + ) diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index 3ff0aa158..0c42415b6 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -1,202 +1,20 @@ -# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 - -# Full details on the techniques used in these plugins to detect EDR-evading malware -# can be found in our 20 page whitepaper submitted to DEFCON along with the presentation -# https://www.volexity.com/wp-content/uploads/2024/08/Defcon24_EDR_Evasion_Detection_White-Paper_Andrew-Case.pdf - +# import logging - -from typing import Dict, Tuple, List, Generator - -from volatility3.framework import interfaces, exceptions -from volatility3.framework import renderers -from volatility3.framework.configuration import requirements -from volatility3.framework.objects import utility -from volatility3.plugins.windows import pslist, pe_symbols +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.windows.malware import unhooked_system_calls vollog = logging.getLogger(__name__) -class unhooked_system_calls(interfaces.plugins.PluginInterface): - """Looks for signs of Skeleton Key malware""" +class unhooked_system_calls( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=unhooked_system_calls.unhooked_system_calls, + removal_date="2026-06-07", +): + """Detects hooked ntdll.dll stub functions in Windows processes (deprecated).""" _required_framework_version = (2, 4, 0) _version = (2, 0, 0) - - system_calls = { - "ntdll.dll": { - pe_symbols.wanted_names_identifier: [ - "NtCreateThread", - "NtProtectVirtualMemory", - "NtReadVirtualMemory", - "NtOpenProcess", - "NtWriteFile", - "NtQueryVirtualMemory", - "NtAllocateVirtualMemory", - "NtWorkerFactoryWorkerReady", - "NtAcceptConnectPort", - "NtAddDriverEntry", - "NtAdjustPrivilegesToken", - "NtAlpcCreatePort", - "NtClose", - "NtCreateFile", - "NtCreateMutant", - "NtOpenFile", - "NtOpenIoCompletion", - "NtOpenJobObject", - "NtOpenKey", - "NtOpenKeyEx", - "NtOpenThread", - "NtOpenThreadToken", - "NtOpenThreadTokenEx", - "NtWriteVirtualMemory", - "NtTraceEvent", - "NtTranslateFilePath", - "NtUmsThreadYield", - "NtUnloadDriver", - "NtUnloadKey", - "NtUnloadKey2", - "NtUnloadKeyEx", - "NtCreateKey", - "NtCreateSection", - "NtDeleteKey", - "NtDeleteValueKey", - "NtDuplicateObject", - "NtQueryValueKey", - "NtReplaceKey", - "NtRequestWaitReplyPort", - "NtRestoreKey", - "NtSetContextThread", - "NtSetSecurityObject", - "NtSetValueKey", - "NtSystemDebugControl", - "NtTerminateProcess", - ] - } - } - - # This data structure is used to track unique implementations of functions across processes - # The outer dictionary holds the module name (e.g., ntdll.dll) - # The next dictionary holds the function names (NtTerminateProcess, NtSetValueKey, etc.) inside a module - # The innermost dictionary holds the unique implementation (bytes) of a function across processes - # Each implementation is tracked along with the process(es) that host it - # For systems without malware, all functions should have the same implementation - # When API hooking/module unhooking is done, the victim (infected) processes will have unique implementations - _code_bytes_type = Dict[str, Dict[str, Dict[bytes, List[Tuple[int, str]]]]] - - @classmethod - def get_requirements(cls) -> List: - # Since we're calling the plugin, make sure we have the plugin's requirements - return [ - requirements.ModuleRequirement( - name="kernel", - description="Windows kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="pslist", component=pslist.PsList, version=(3, 0, 0) - ), - requirements.VersionRequirement( - name="pe_symbols", component=pe_symbols.PESymbols, version=(3, 0, 0) - ), - ] - - def _gather_code_bytes( - self, - kernel_module_name: str, - found_symbols: pe_symbols.found_symbols_type, - ) -> _code_bytes_type: - """ - Enumerates the desired DLLs and function implementations in each process - Groups based on unique implementations of each DLLs' functions - The purpose is to detect when a function has different implementations (code) - in different processes. - This very effectively detects code injection. - """ - code_bytes: unhooked_system_calls._code_bytes_type = {} - - procs = pslist.PsList.list_processes(self.context, kernel_module_name) - - for proc in procs: - try: - proc_id = proc.UniqueProcessId - proc_name = utility.array_to_string(proc.ImageFileName) - proc_layer_name = proc.add_process_layer() - except exceptions.InvalidAddressException: - continue - - for dll_name, functions in found_symbols.items(): - for func_name, func_addr in functions: - try: - fbytes = self.context.layers[proc_layer_name].read( - func_addr, 0x20 - ) - except exceptions.InvalidAddressException: - continue - - # see the definition of _code_bytes_type for details of this data structure - if dll_name not in code_bytes: - code_bytes[dll_name] = {} - - if func_name not in code_bytes[dll_name]: - code_bytes[dll_name][func_name] = {} - - if fbytes not in code_bytes[dll_name][func_name]: - code_bytes[dll_name][func_name][fbytes] = [] - - code_bytes[dll_name][func_name][fbytes].append((proc_id, proc_name)) - - return code_bytes - - def _generator(self) -> Generator[Tuple[int, Tuple[str, str, int]], None, None]: - found_symbols = pe_symbols.PESymbols.addresses_for_process_symbols( - context=self.context, - config_path=self.config_path, - kernel_module_name=self.config["kernel"], - symbols=unhooked_system_calls.system_calls, - ) - - # code_bytes[dll_name][func_name][func_bytes] - code_bytes = self._gather_code_bytes(self.config["kernel"], found_symbols) - - # walk the functions that were evaluated - for functions in code_bytes.values(): - # cbb is the distinct groups of bytes (instructions) - # for this function across processes - for func_name, cbb in functions.items(): - # the dict key here is the raw instructions, which is not helpful to look at - # the values are the list of tuples for the (proc_id, proc_name) pairs for this set of bytes (instructions) - cb = list(cbb.values()) - - # if all processes map to the same implementation, then no malware is present - if len(cb) == 1: - yield 0, (func_name, "", len(cb[0])) - else: - # if there are differing implementations then it means - # that malware has overwritten system call(s) in infected processes - # max_idx and small_idx find which implementation of a system call has the least processes - # as all observed malware and open source projects only infected a few targets, leaving the - # rest with the original EDR hooks in place - max_idx = 0 if len(cb[0]) > len(cb[1]) else 1 - small_idx = (~max_idx) & 1 - - ps = [] - - # gather processes on small_idx since these are the malware infected ones - for pid, pname in cb[small_idx]: - ps.append(f"{pid:d}:{pname}") - - proc_names = ", ".join(ps) - - yield 0, (func_name, proc_names, len(cb[max_idx])) - - def run(self) -> renderers.TreeGrid: - return renderers.TreeGrid( - [ - ("Function", str), - ("Distinct Implementations", str), - ("Total Implementations", int), - ], - self._generator(), - ) From f97bc920bbfdbded80e9140b09640298a8249481 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 18:09:26 +0300 Subject: [PATCH 05/25] Plugins: changed class name due to incorrect resolution --- .../plugins/windows/malware/unhooked_system_calls.py | 6 +++--- .../framework/plugins/windows/unhooked_system_calls.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py b/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py index 5723ce0fd..71dc20021 100644 --- a/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/malware/unhooked_system_calls.py @@ -18,7 +18,7 @@ from volatility3.plugins.windows import pslist, pe_symbols vollog = logging.getLogger(__name__) -class unhooked_system_calls(interfaces.plugins.PluginInterface): +class UnhookedSystemCalls(interfaces.plugins.PluginInterface): """Detects hooked ntdll.dll stub functions in Windows processes.""" _required_framework_version = (2, 4, 0) @@ -114,7 +114,7 @@ class unhooked_system_calls(interfaces.plugins.PluginInterface): in different processes. This very effectively detects code injection. """ - code_bytes: unhooked_system_calls._code_bytes_type = {} + code_bytes: UnhookedSystemCalls._code_bytes_type = {} procs = pslist.PsList.list_processes(self.context, kernel_module_name) @@ -154,7 +154,7 @@ class unhooked_system_calls(interfaces.plugins.PluginInterface): context=self.context, config_path=self.config_path, kernel_module_name=self.config["kernel"], - symbols=unhooked_system_calls.system_calls, + symbols=UnhookedSystemCalls.system_calls, ) # code_bytes[dll_name][func_name][func_bytes] diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index 0c42415b6..e6fb2fb6c 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -8,10 +8,10 @@ from volatility3.plugins.windows.malware import unhooked_system_calls vollog = logging.getLogger(__name__) -class unhooked_system_calls( +class UnhookedSystemCalls( interfaces.plugins.PluginInterface, deprecation.PluginRenameClass, - replacement_class=unhooked_system_calls.unhooked_system_calls, + replacement_class=unhooked_system_calls.UnhookedSystemCalls, removal_date="2026-06-07", ): """Detects hooked ntdll.dll stub functions in Windows processes (deprecated).""" From ef07b07659a3c2475b36b6d0c26b5e24ee02687a Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 18:25:53 +0300 Subject: [PATCH 06/25] Plugins: categorize windows.drivermodule as a malware plugin --- .../framework/plugins/windows/drivermodule.py | 105 ++---------------- .../plugins/windows/malware/drivermodule.py | 101 +++++++++++++++++ 2 files changed, 113 insertions(+), 93 deletions(-) create mode 100644 volatility3/framework/plugins/windows/malware/drivermodule.py diff --git a/volatility3/framework/plugins/windows/drivermodule.py b/volatility3/framework/plugins/windows/drivermodule.py index c31fe2500..bf8f333f6 100644 --- a/volatility3/framework/plugins/windows/drivermodule.py +++ b/volatility3/framework/plugins/windows/drivermodule.py @@ -1,101 +1,20 @@ -# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # -from typing import Iterator, List, Tuple -from volatility3.framework import renderers, interfaces -from volatility3.framework.configuration import requirements -from volatility3.framework.renderers import format_hints -from volatility3.plugins.windows import ssdt, driverscan, modules +import logging +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.windows.malware import drivermodule -# built in Windows-components that trigger false positives -KNOWN_DRIVERS = ["ACPI_HAL", "PnpManager", "RAW", "WMIxWDM", "Win32k", "Fs_Rec"] +vollog = logging.getLogger(__name__) -class DriverModule(interfaces.plugins.PluginInterface): - """Determines if any loaded drivers were hidden by a rootkit""" +class DriverModule( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=drivermodule.DriverModule, + removal_date="2026-06-07", +): + """Determines if any loaded drivers were hidden by a rootkit (deprecated).""" _required_framework_version = (2, 0, 0) _version = (1, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Windows kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="ssdt", component=ssdt.SSDT, version=(2, 0, 0) - ), - requirements.VersionRequirement( - name="driverscan", component=driverscan.DriverScan, version=(2, 0, 0) - ), - requirements.VersionRequirement( - name="modules", component=modules.Modules, version=(3, 0, 0) - ), - ] - - def _generator(self) -> Iterator[Tuple]: - """ - Attempt to match each driver's start code address to a known kernel module - A common rootkit technique is to register drivers from modules that are hidden, - which allows us to detect the disconnect between a malicious driver and its hidden module. - """ - collection = ssdt.SSDT.build_module_collection( - context=self.context, - kernel_module_name=self.config["kernel"], - ) - - kernel_space_start = modules.Modules.get_kernel_space_start( - self.context, self.config["kernel"] - ) - - for driver in driverscan.DriverScan.scan_drivers( - self.context, - self.config["kernel"], - ): - # We want starts of 0 as rootkits often set this value - # greater than 0 but less than the kernel space start is smear/terminated though - if 0 < driver.DriverStart < kernel_space_start: - continue - - # we do not care about actual symbol names, we just want to know if the driver points to a known module - module_symbols = list( - collection.get_module_symbols_by_absolute_location(driver.DriverStart) - ) - if not module_symbols: - ( - driver_name, - service_key, - name, - ) = driverscan.DriverScan.get_names_for_driver(driver) - - # drivers without any names will not produce useful output - if not driver_name and not service_key and not name: - continue - - known_exception = driver_name in KNOWN_DRIVERS - - yield ( - 0, - ( - format_hints.Hex(driver.vol.offset), - known_exception, - driver_name or renderers.NotAvailableValue(), - service_key or renderers.NotAvailableValue(), - name or renderers.NotAvailableValue(), - ), - ) - - def run(self) -> renderers.TreeGrid: - return renderers.TreeGrid( - [ - ("Offset", format_hints.Hex), - ("Known Exception", bool), - ("Driver Name", str), - ("Service Key", str), - ("Alternative Name", str), - ], - self._generator(), - ) diff --git a/volatility3/framework/plugins/windows/malware/drivermodule.py b/volatility3/framework/plugins/windows/malware/drivermodule.py new file mode 100644 index 000000000..c31fe2500 --- /dev/null +++ b/volatility3/framework/plugins/windows/malware/drivermodule.py @@ -0,0 +1,101 @@ +# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +from typing import Iterator, List, Tuple +from volatility3.framework import renderers, interfaces +from volatility3.framework.configuration import requirements +from volatility3.framework.renderers import format_hints +from volatility3.plugins.windows import ssdt, driverscan, modules + +# built in Windows-components that trigger false positives +KNOWN_DRIVERS = ["ACPI_HAL", "PnpManager", "RAW", "WMIxWDM", "Win32k", "Fs_Rec"] + + +class DriverModule(interfaces.plugins.PluginInterface): + """Determines if any loaded drivers were hidden by a rootkit""" + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Windows kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="ssdt", component=ssdt.SSDT, version=(2, 0, 0) + ), + requirements.VersionRequirement( + name="driverscan", component=driverscan.DriverScan, version=(2, 0, 0) + ), + requirements.VersionRequirement( + name="modules", component=modules.Modules, version=(3, 0, 0) + ), + ] + + def _generator(self) -> Iterator[Tuple]: + """ + Attempt to match each driver's start code address to a known kernel module + A common rootkit technique is to register drivers from modules that are hidden, + which allows us to detect the disconnect between a malicious driver and its hidden module. + """ + collection = ssdt.SSDT.build_module_collection( + context=self.context, + kernel_module_name=self.config["kernel"], + ) + + kernel_space_start = modules.Modules.get_kernel_space_start( + self.context, self.config["kernel"] + ) + + for driver in driverscan.DriverScan.scan_drivers( + self.context, + self.config["kernel"], + ): + # We want starts of 0 as rootkits often set this value + # greater than 0 but less than the kernel space start is smear/terminated though + if 0 < driver.DriverStart < kernel_space_start: + continue + + # we do not care about actual symbol names, we just want to know if the driver points to a known module + module_symbols = list( + collection.get_module_symbols_by_absolute_location(driver.DriverStart) + ) + if not module_symbols: + ( + driver_name, + service_key, + name, + ) = driverscan.DriverScan.get_names_for_driver(driver) + + # drivers without any names will not produce useful output + if not driver_name and not service_key and not name: + continue + + known_exception = driver_name in KNOWN_DRIVERS + + yield ( + 0, + ( + format_hints.Hex(driver.vol.offset), + known_exception, + driver_name or renderers.NotAvailableValue(), + service_key or renderers.NotAvailableValue(), + name or renderers.NotAvailableValue(), + ), + ) + + def run(self) -> renderers.TreeGrid: + return renderers.TreeGrid( + [ + ("Offset", format_hints.Hex), + ("Known Exception", bool), + ("Driver Name", str), + ("Service Key", str), + ("Alternative Name", str), + ], + self._generator(), + ) From c36fdd69f6270b449e3d0f32e9f266cdc06813b2 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:22:58 +0300 Subject: [PATCH 07/25] Plugins: categorize linux.check_idt as a malware plugin --- .../framework/plugins/linux/check_idt.py | 166 +---------------- .../plugins/linux/malware/check_idt.py | 168 ++++++++++++++++++ 2 files changed, 177 insertions(+), 157 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/check_idt.py diff --git a/volatility3/framework/plugins/linux/check_idt.py b/volatility3/framework/plugins/linux/check_idt.py index e199d98d3..449f85e1e 100644 --- a/volatility3/framework/plugins/linux/check_idt.py +++ b/volatility3/framework/plugins/linux/check_idt.py @@ -1,168 +1,20 @@ # This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # - import logging -from typing import List, Optional - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules -from volatility3.framework import interfaces, renderers, symbols -from volatility3.framework.configuration import requirements -from volatility3.framework.renderers import format_hints -from volatility3.framework.symbols import linux +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import check_idt vollog = logging.getLogger(__name__) -class Check_idt(interfaces.plugins.PluginInterface): - """Checks if the IDT has been altered""" +class Check_idt( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=check_idt.Check_idt, + removal_date="2026-06-07", +): + """Checks if the IDT has been altered (deprecated).""" _required_framework_version = (2, 0, 0) - - # 2.0.0 - Add versioning at all, add `get_idt_type` _version = (2, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="linux_utilities_modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherers", - component=linux_utilities_modules.ModuleGatherers, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) - ), - ] - - @staticmethod - def get_idt_type(context, vmlinux_name) -> Optional[str]: - """ - Determines the IDT type for this symbol table or returns None - - The original version ended clauses with an `else` leading to bad fall through - of returning a type that did not exist in the symbol table. - - Future updates should not leave fall through cases to avoid this repeating. - """ - - vmlinux = context.modules[vmlinux_name] - - is_32bit = not symbols.symbol_table_is_64bit(context, vmlinux.symbol_table_name) - - # These are in a specific order. Only append to the lists going forward - # or ask Andrew to run tests before merging. - if is_32bit: - idt_types = ["gate_struct", "desc_struct", "gate_struct32"] - else: - idt_types = ["gate_struct64", "gate_struct", "idt_desc"] - - for idt_type in idt_types: - if vmlinux.has_type(idt_type): - return idt_type - - return None - - def _generator(self): - idt_type = self.get_idt_type(self.context, self.config["kernel"]) - if not idt_type: - vollog.error( - "Unable to determine the data structure type for IDT entries. Please file a bug on the GitHub tracker with your kernel version." - ) - return - - vmlinux = self.context.modules[self.config["kernel"]] - - known_modules = linux_utilities_modules.Modules.run_modules_scanners( - context=self.context, - kernel_module_name=self.config["kernel"], - caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, - ) - - idt_table_size = 256 - - kernel_layer = self.context.layers[vmlinux.layer_name] - - address_mask = kernel_layer.address_mask - - # hw handlers + system call - check_idxs = list(range(20)) + [128] - - addrs = vmlinux.object_from_symbol("idt_table") - - table = vmlinux.object( - object_type="array", - offset=addrs.vol.offset, - subtype=vmlinux.get_type(idt_type), - count=idt_table_size, - absolute=True, - ) - - for i in check_idxs: - ent = table[i] - - if not ent or not kernel_layer.is_valid(ent.vol.offset): - continue - - if hasattr(ent, "a"): - idt_addr = (ent.b & 0xFFFF0000) | (ent.a & 0x0000FFFF) - else: - low = ent.offset_low - middle = ent.offset_middle - - # offset_high is for 64bit systems - if hasattr(ent, "offset_high"): - high = ent.offset_high - else: - high = 0 - - idt_addr = (high << 32) | (middle << 16) | low - - idt_addr = idt_addr & address_mask - - # 0 means unintialized/unused, not a rootkit - if idt_addr == 0: - module_name = renderers.NotAvailableValue() - symbol_name = renderers.NotAvailableValue() - else: - module_info, symbol_name = ( - linux_utilities_modules.Modules.module_lookup_by_address( - self.context, vmlinux.name, known_modules, idt_addr - ) - ) - - if module_info: - module_name = module_info.name - else: - module_name = renderers.NotAvailableValue() - - yield ( - 0, - [ - format_hints.Hex(i), - format_hints.Hex(idt_addr), - module_name, - symbol_name or renderers.NotAvailableValue(), - ], - ) - - def run(self): - return renderers.TreeGrid( - [ - ("Index", format_hints.Hex), - ("Address", format_hints.Hex), - ("Module", str), - ("Symbol", str), - ], - self._generator(), - ) diff --git a/volatility3/framework/plugins/linux/malware/check_idt.py b/volatility3/framework/plugins/linux/malware/check_idt.py new file mode 100644 index 000000000..e199d98d3 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/check_idt.py @@ -0,0 +1,168 @@ +# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# + +import logging +from typing import List, Optional + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules +from volatility3.framework import interfaces, renderers, symbols +from volatility3.framework.configuration import requirements +from volatility3.framework.renderers import format_hints +from volatility3.framework.symbols import linux + +vollog = logging.getLogger(__name__) + + +class Check_idt(interfaces.plugins.PluginInterface): + """Checks if the IDT has been altered""" + + _required_framework_version = (2, 0, 0) + + # 2.0.0 - Add versioning at all, add `get_idt_type` + _version = (2, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="linux_utilities_modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherers", + component=linux_utilities_modules.ModuleGatherers, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) + ), + ] + + @staticmethod + def get_idt_type(context, vmlinux_name) -> Optional[str]: + """ + Determines the IDT type for this symbol table or returns None + + The original version ended clauses with an `else` leading to bad fall through + of returning a type that did not exist in the symbol table. + + Future updates should not leave fall through cases to avoid this repeating. + """ + + vmlinux = context.modules[vmlinux_name] + + is_32bit = not symbols.symbol_table_is_64bit(context, vmlinux.symbol_table_name) + + # These are in a specific order. Only append to the lists going forward + # or ask Andrew to run tests before merging. + if is_32bit: + idt_types = ["gate_struct", "desc_struct", "gate_struct32"] + else: + idt_types = ["gate_struct64", "gate_struct", "idt_desc"] + + for idt_type in idt_types: + if vmlinux.has_type(idt_type): + return idt_type + + return None + + def _generator(self): + idt_type = self.get_idt_type(self.context, self.config["kernel"]) + if not idt_type: + vollog.error( + "Unable to determine the data structure type for IDT entries. Please file a bug on the GitHub tracker with your kernel version." + ) + return + + vmlinux = self.context.modules[self.config["kernel"]] + + known_modules = linux_utilities_modules.Modules.run_modules_scanners( + context=self.context, + kernel_module_name=self.config["kernel"], + caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, + ) + + idt_table_size = 256 + + kernel_layer = self.context.layers[vmlinux.layer_name] + + address_mask = kernel_layer.address_mask + + # hw handlers + system call + check_idxs = list(range(20)) + [128] + + addrs = vmlinux.object_from_symbol("idt_table") + + table = vmlinux.object( + object_type="array", + offset=addrs.vol.offset, + subtype=vmlinux.get_type(idt_type), + count=idt_table_size, + absolute=True, + ) + + for i in check_idxs: + ent = table[i] + + if not ent or not kernel_layer.is_valid(ent.vol.offset): + continue + + if hasattr(ent, "a"): + idt_addr = (ent.b & 0xFFFF0000) | (ent.a & 0x0000FFFF) + else: + low = ent.offset_low + middle = ent.offset_middle + + # offset_high is for 64bit systems + if hasattr(ent, "offset_high"): + high = ent.offset_high + else: + high = 0 + + idt_addr = (high << 32) | (middle << 16) | low + + idt_addr = idt_addr & address_mask + + # 0 means unintialized/unused, not a rootkit + if idt_addr == 0: + module_name = renderers.NotAvailableValue() + symbol_name = renderers.NotAvailableValue() + else: + module_info, symbol_name = ( + linux_utilities_modules.Modules.module_lookup_by_address( + self.context, vmlinux.name, known_modules, idt_addr + ) + ) + + if module_info: + module_name = module_info.name + else: + module_name = renderers.NotAvailableValue() + + yield ( + 0, + [ + format_hints.Hex(i), + format_hints.Hex(idt_addr), + module_name, + symbol_name or renderers.NotAvailableValue(), + ], + ) + + def run(self): + return renderers.TreeGrid( + [ + ("Index", format_hints.Hex), + ("Address", format_hints.Hex), + ("Module", str), + ("Symbol", str), + ], + self._generator(), + ) From 4bc1bb818dfb2cb0ca8c2f694ba4f97fdab09208 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:23:13 +0300 Subject: [PATCH 08/25] linux.malware.check_idt - fix doc & test deps --- doc/source/getting-started-linux-tutorial.rst | 2 +- test/plugins/linux/linux.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/source/getting-started-linux-tutorial.rst b/doc/source/getting-started-linux-tutorial.rst index 031b49636..9a04ddcc1 100644 --- a/doc/source/getting-started-linux-tutorial.rst +++ b/doc/source/getting-started-linux-tutorial.rst @@ -38,7 +38,7 @@ For plugin requests, please create an issue with a description of the requested linux.bash.Bash Recovers bash command history from memory. linux.check_afinfo.Check_afinfo linux.check_creds.Check_creds - linux.check_idt.Check_idt + linux.malware.check_idt.Check_idt .. note:: Here the command is piped to grep and head to provide the start of the list of linux plugins. diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..cecf6e80e 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -29,7 +29,7 @@ class TestLinuxPslist: class TestLinuxCheckIdt: def test_linux_generic_check_idt(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.check_idt.Check_idt", image, volatility, python + "linux.malware.check_idt.Check_idt", image, volatility, python ) assert rc == 0 From 832c997e20b7685f772e518d091fdca534a2e2d8 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:29:55 +0300 Subject: [PATCH 09/25] Plugins: categorize linux.check_modules as a malware plugin --- .../framework/plugins/linux/check_modules.py | 68 +++--------------- .../plugins/linux/malware/check_modules.py | 70 +++++++++++++++++++ 2 files changed, 79 insertions(+), 59 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/check_modules.py diff --git a/volatility3/framework/plugins/linux/check_modules.py b/volatility3/framework/plugins/linux/check_modules.py index 7805bbd8a..d8b3ddcf1 100644 --- a/volatility3/framework/plugins/linux/check_modules.py +++ b/volatility3/framework/plugins/linux/check_modules.py @@ -1,70 +1,20 @@ -# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # - import logging -from typing import List, Dict, Generator - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules from volatility3.framework import interfaces, deprecation -from volatility3.framework.configuration import requirements -from volatility3.framework.objects import utility -from volatility3.framework.symbols.linux import extensions -from volatility3.framework.interfaces import plugins +from volatility3.plugins.linux.malware import check_modules vollog = logging.getLogger(__name__) -class Check_modules(plugins.PluginInterface): - """Compares module list to sysfs info, if available""" +class Check_modules( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=check_modules.Check_modules, + removal_date="2026-06-07", +): + """Compares module list to sysfs info, if available (deprecated).""" _version = (3, 0, 1) _required_framework_version = (2, 0, 0) - - @classmethod - def compare_kset_and_lsmod( - cls, context: str, vmlinux_name: str - ) -> Generator[extensions.module, None, None]: - kset_modules = linux_utilities_modules.Modules.get_kset_modules( - context=context, vmlinux_name=vmlinux_name - ) - - lsmod_modules = set( - str(utility.array_to_string(modules.name)) - for modules in linux_utilities_modules.Modules.list_modules( - context=context, vmlinux_module_name=vmlinux_name - ) - ) - - for mod_name in set(kset_modules.keys()).difference(lsmod_modules): - yield kset_modules[mod_name] - - run = linux_utilities_modules.ModuleDisplayPlugin.run - _generator = linux_utilities_modules.ModuleDisplayPlugin.generator - implementation = compare_kset_and_lsmod - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.VersionRequirement( - name="modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 1), - ), - requirements.VersionRequirement( - name="linux_utilities_modules_module_display_plugin", - component=linux_utilities_modules.ModuleDisplayPlugin, - version=(1, 0, 0), - ), - ] + linux_utilities_modules.ModuleDisplayPlugin.get_requirements() - - @classmethod - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.get_kset_modules, - removal_date="2025-09-25", - replacement_version=(3, 0, 0), - ) - def get_kset_modules( - cls, context: interfaces.context.ContextInterface, vmlinux_name: str - ) -> Dict[str, extensions.module]: - return linux_utilities_modules.Modules.get_kset_modules(context, vmlinux_name) diff --git a/volatility3/framework/plugins/linux/malware/check_modules.py b/volatility3/framework/plugins/linux/malware/check_modules.py new file mode 100644 index 000000000..7805bbd8a --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/check_modules.py @@ -0,0 +1,70 @@ +# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# + +import logging +from typing import List, Dict, Generator + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules +from volatility3.framework import interfaces, deprecation +from volatility3.framework.configuration import requirements +from volatility3.framework.objects import utility +from volatility3.framework.symbols.linux import extensions +from volatility3.framework.interfaces import plugins + +vollog = logging.getLogger(__name__) + + +class Check_modules(plugins.PluginInterface): + """Compares module list to sysfs info, if available""" + + _version = (3, 0, 1) + _required_framework_version = (2, 0, 0) + + @classmethod + def compare_kset_and_lsmod( + cls, context: str, vmlinux_name: str + ) -> Generator[extensions.module, None, None]: + kset_modules = linux_utilities_modules.Modules.get_kset_modules( + context=context, vmlinux_name=vmlinux_name + ) + + lsmod_modules = set( + str(utility.array_to_string(modules.name)) + for modules in linux_utilities_modules.Modules.list_modules( + context=context, vmlinux_module_name=vmlinux_name + ) + ) + + for mod_name in set(kset_modules.keys()).difference(lsmod_modules): + yield kset_modules[mod_name] + + run = linux_utilities_modules.ModuleDisplayPlugin.run + _generator = linux_utilities_modules.ModuleDisplayPlugin.generator + implementation = compare_kset_and_lsmod + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.VersionRequirement( + name="modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 1), + ), + requirements.VersionRequirement( + name="linux_utilities_modules_module_display_plugin", + component=linux_utilities_modules.ModuleDisplayPlugin, + version=(1, 0, 0), + ), + ] + linux_utilities_modules.ModuleDisplayPlugin.get_requirements() + + @classmethod + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.get_kset_modules, + removal_date="2025-09-25", + replacement_version=(3, 0, 0), + ) + def get_kset_modules( + cls, context: interfaces.context.ContextInterface, vmlinux_name: str + ) -> Dict[str, extensions.module]: + return linux_utilities_modules.Modules.get_kset_modules(context, vmlinux_name) From 4b279f96339f7d5b00af2abf2c8d7d6041777d75 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:30:04 +0300 Subject: [PATCH 10/25] linux.malware.check_modules - fix test --- test/plugins/linux/linux.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..12309cc59 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -438,7 +438,7 @@ class TestLinuxCheckAfinfo: class TestLinuxCheckModules: def test_linux_generic_check_modules(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.check_modules.Check_modules", image, volatility, python + "linux.malware.check_modules.Check_modules", image, volatility, python ) # linux-sample-1.bin has no suspicious results. From 5b538d16866e8a173093c5934c493c58f0fb810b Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:35:19 +0300 Subject: [PATCH 11/25] Plugins: categorize linux.check_syscall as a malware plugin --- .../framework/plugins/linux/check_syscall.py | 216 +----------------- .../plugins/linux/malware/check_syscall.py | 215 +++++++++++++++++ 2 files changed, 226 insertions(+), 205 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/check_syscall.py diff --git a/volatility3/framework/plugins/linux/check_syscall.py b/volatility3/framework/plugins/linux/check_syscall.py index 724a67810..5e3e40cbb 100644 --- a/volatility3/framework/plugins/linux/check_syscall.py +++ b/volatility3/framework/plugins/linux/check_syscall.py @@ -1,214 +1,20 @@ -# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # -"""A module containing a plugin that checks the system call table for hooks.""" -import contextlib import logging -from typing import List - -from volatility3.framework import constants, exceptions, interfaces, renderers -from volatility3.framework.configuration import requirements -from volatility3.framework.interfaces import plugins -from volatility3.framework.renderers import format_hints +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import check_syscall vollog = logging.getLogger(__name__) -try: - import capstone - has_capstone = True -except ImportError: - has_capstone = False - - -class Check_syscall(plugins.PluginInterface): - """Check system call table for hooks.""" +class Check_syscall( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=check_syscall.Check_syscall, + removal_date="2026-06-07", +): + """Check system call table for hooks (deprecated).""" _required_framework_version = (2, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - ] - - def _get_table_size_next_symbol(self, table_addr, ptr_sz, vmlinux): - """Returns the size of the table based on the next symbol.""" - ret = 0 - - symbol_list = [] - for sn in vmlinux.symbols: - with contextlib.suppress(exceptions.SymbolError): - # When requesting the symbol from the module, a full resolve is performed - symbol_list.append((vmlinux.get_symbol(sn).address, sn)) - sorted_symbols = sorted(symbol_list) - - sym_address = 0 - - for tmp_sym_address, sym_name in sorted_symbols: - if tmp_sym_address > table_addr: - sym_address = tmp_sym_address - break - - if sym_address > 0: - ret = int((sym_address - table_addr) / ptr_sz) - - return ret - - def _get_table_size_meta(self, vmlinux): - """returns the number of symbols that start with __syscall_meta__ this - is a fast way to determine the number of system calls, but not the most - accurate.""" - - return len( - [ - sym - for sym in self.context.symbol_space[vmlinux.symbol_table_name].symbols - if sym.startswith("__syscall_meta__") - ] - ) - - def _get_table_info_other(self, table_addr, ptr_sz, vmlinux): - table_size_meta = self._get_table_size_meta(vmlinux) - table_size_syms = self._get_table_size_next_symbol(table_addr, ptr_sz, vmlinux) - - sizes = [size for size in [table_size_meta, table_size_syms] if size > 0] - - table_size = min(sizes) - - return table_size - - def _get_table_info_disassembly(self, ptr_sz, vmlinux) -> int: - """Find the size of the system call table by disassembling functions - that immediately reference it in their first instruction This is in the - form 'cmp reg,NR_syscalls'.""" - table_size = 0 - - if not has_capstone: - return table_size - - if ptr_sz == 4: - syscall_entry_func = "sysenter_do_call" - mode = capstone.CS_MODE_32 - else: - syscall_entry_func = "system_call_fastpath" - mode = capstone.CS_MODE_64 - - md = capstone.Cs(capstone.CS_ARCH_X86, mode) - - try: - func_addr = vmlinux.get_symbol(syscall_entry_func).address - except exceptions.SymbolError: - # if we can't find the disassemble function then bail and rely on a different method - return 0 - - vmlinux = self.context.modules[self.config["kernel"]] - vmlinux_layer = self.context.layers[vmlinux.layer_name] - try: - data = vmlinux_layer.read(func_addr, 6) - except exceptions.InvalidAddressException: - return 0 - - for _address, _size, mnemonic, op_str in md.disasm_lite(data, func_addr): - if mnemonic == "CMP": - table_size = int(op_str.split(",")[1].strip()) & 0xFFFF - break - - return table_size - - def _get_table_info(self, vmlinux, table_name, ptr_sz): - table_sym = vmlinux.get_symbol(table_name) - - table_size = self._get_table_info_disassembly(ptr_sz, vmlinux) - - if table_size == 0: - table_size = self._get_table_info_other(table_sym.address, ptr_sz, vmlinux) - - if table_size == 0: - vollog.error("Unable to get system call table size") - return 0, 0 - - return table_sym.address, table_size - - # TODO - add finding and parsing unistd.h once cached file enumeration is added - def _generator(self): - vmlinux = self.context.modules[self.config["kernel"]] - - ptr_sz = vmlinux.get_type("pointer").size - if ptr_sz == 4: - table_name = "32bit" - else: - table_name = "64bit" - - try: - table_info = self._get_table_info(vmlinux, "sys_call_table", ptr_sz) - except exceptions.SymbolError: - vollog.error("Unable to find the system call table. Exiting.") - return None - - tables = [(table_name, table_info)] - - # this table is only present on 64 bit systems with 32 bit emulation - # enabled in order to support 32 bit programs and libraries - # if the symbol isn't there then the support isn't in the kernel and so we skip it - try: - ia32_symbol = vmlinux.get_symbol("ia32_sys_call_table") - except exceptions.SymbolError: - ia32_symbol = None - - if ia32_symbol is not None: - ia32_info = self._get_table_info(vmlinux, "ia32_sys_call_table", ptr_sz) - tables.append(("32bit", ia32_info)) - - for table_name, (tableaddr, tblsz) in tables: - table = vmlinux.object( - object_type="array", - subtype=vmlinux.get_type("pointer"), - offset=tableaddr, - count=tblsz, - ) - - for i in range(len(table)): - try: - call_addr = table[i] - except exceptions.InvalidAddressException: - vollog.debug(f"Failed to get system call table entry at index {i}") - continue - - symbols = list(vmlinux.get_symbols_by_absolute_location(call_addr)) - - if len(symbols) > 0: - sym_name = ( - str(symbols[0].split(constants.BANG)[1]) - if constants.BANG in symbols[0] - else str(symbols[0]) - ) - else: - sym_name = "UNKNOWN" - - yield ( - 0, - ( - format_hints.Hex(tableaddr), - table_name, - i, - format_hints.Hex(call_addr), - sym_name, - ), - ) - - def run(self): - return renderers.TreeGrid( - [ - ("Table Address", format_hints.Hex), - ("Table Name", str), - ("Index", int), - ("Handler Address", format_hints.Hex), - ("Handler Symbol", str), - ], - self._generator(), - ) + _version = (1, 0, 0) diff --git a/volatility3/framework/plugins/linux/malware/check_syscall.py b/volatility3/framework/plugins/linux/malware/check_syscall.py new file mode 100644 index 000000000..1188bf250 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/check_syscall.py @@ -0,0 +1,215 @@ +# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +"""A module containing a plugin that checks the system call table for hooks.""" +import contextlib +import logging +from typing import List + +from volatility3.framework import constants, exceptions, interfaces, renderers +from volatility3.framework.configuration import requirements +from volatility3.framework.interfaces import plugins +from volatility3.framework.renderers import format_hints + +vollog = logging.getLogger(__name__) + +try: + import capstone + + has_capstone = True +except ImportError: + has_capstone = False + + +class Check_syscall(plugins.PluginInterface): + """Check system call table for hooks.""" + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + ] + + def _get_table_size_next_symbol(self, table_addr, ptr_sz, vmlinux): + """Returns the size of the table based on the next symbol.""" + ret = 0 + + symbol_list = [] + for sn in vmlinux.symbols: + with contextlib.suppress(exceptions.SymbolError): + # When requesting the symbol from the module, a full resolve is performed + symbol_list.append((vmlinux.get_symbol(sn).address, sn)) + sorted_symbols = sorted(symbol_list) + + sym_address = 0 + + for tmp_sym_address, sym_name in sorted_symbols: + if tmp_sym_address > table_addr: + sym_address = tmp_sym_address + break + + if sym_address > 0: + ret = int((sym_address - table_addr) / ptr_sz) + + return ret + + def _get_table_size_meta(self, vmlinux): + """returns the number of symbols that start with __syscall_meta__ this + is a fast way to determine the number of system calls, but not the most + accurate.""" + + return len( + [ + sym + for sym in self.context.symbol_space[vmlinux.symbol_table_name].symbols + if sym.startswith("__syscall_meta__") + ] + ) + + def _get_table_info_other(self, table_addr, ptr_sz, vmlinux): + table_size_meta = self._get_table_size_meta(vmlinux) + table_size_syms = self._get_table_size_next_symbol(table_addr, ptr_sz, vmlinux) + + sizes = [size for size in [table_size_meta, table_size_syms] if size > 0] + + table_size = min(sizes) + + return table_size + + def _get_table_info_disassembly(self, ptr_sz, vmlinux) -> int: + """Find the size of the system call table by disassembling functions + that immediately reference it in their first instruction This is in the + form 'cmp reg,NR_syscalls'.""" + table_size = 0 + + if not has_capstone: + return table_size + + if ptr_sz == 4: + syscall_entry_func = "sysenter_do_call" + mode = capstone.CS_MODE_32 + else: + syscall_entry_func = "system_call_fastpath" + mode = capstone.CS_MODE_64 + + md = capstone.Cs(capstone.CS_ARCH_X86, mode) + + try: + func_addr = vmlinux.get_symbol(syscall_entry_func).address + except exceptions.SymbolError: + # if we can't find the disassemble function then bail and rely on a different method + return 0 + + vmlinux = self.context.modules[self.config["kernel"]] + vmlinux_layer = self.context.layers[vmlinux.layer_name] + try: + data = vmlinux_layer.read(func_addr, 6) + except exceptions.InvalidAddressException: + return 0 + + for _address, _size, mnemonic, op_str in md.disasm_lite(data, func_addr): + if mnemonic == "CMP": + table_size = int(op_str.split(",")[1].strip()) & 0xFFFF + break + + return table_size + + def _get_table_info(self, vmlinux, table_name, ptr_sz): + table_sym = vmlinux.get_symbol(table_name) + + table_size = self._get_table_info_disassembly(ptr_sz, vmlinux) + + if table_size == 0: + table_size = self._get_table_info_other(table_sym.address, ptr_sz, vmlinux) + + if table_size == 0: + vollog.error("Unable to get system call table size") + return 0, 0 + + return table_sym.address, table_size + + # TODO - add finding and parsing unistd.h once cached file enumeration is added + def _generator(self): + vmlinux = self.context.modules[self.config["kernel"]] + + ptr_sz = vmlinux.get_type("pointer").size + if ptr_sz == 4: + table_name = "32bit" + else: + table_name = "64bit" + + try: + table_info = self._get_table_info(vmlinux, "sys_call_table", ptr_sz) + except exceptions.SymbolError: + vollog.error("Unable to find the system call table. Exiting.") + return None + + tables = [(table_name, table_info)] + + # this table is only present on 64 bit systems with 32 bit emulation + # enabled in order to support 32 bit programs and libraries + # if the symbol isn't there then the support isn't in the kernel and so we skip it + try: + ia32_symbol = vmlinux.get_symbol("ia32_sys_call_table") + except exceptions.SymbolError: + ia32_symbol = None + + if ia32_symbol is not None: + ia32_info = self._get_table_info(vmlinux, "ia32_sys_call_table", ptr_sz) + tables.append(("32bit", ia32_info)) + + for table_name, (tableaddr, tblsz) in tables: + table = vmlinux.object( + object_type="array", + subtype=vmlinux.get_type("pointer"), + offset=tableaddr, + count=tblsz, + ) + + for i in range(len(table)): + try: + call_addr = table[i] + except exceptions.InvalidAddressException: + vollog.debug(f"Failed to get system call table entry at index {i}") + continue + + symbols = list(vmlinux.get_symbols_by_absolute_location(call_addr)) + + if len(symbols) > 0: + sym_name = ( + str(symbols[0].split(constants.BANG)[1]) + if constants.BANG in symbols[0] + else str(symbols[0]) + ) + else: + sym_name = "UNKNOWN" + + yield ( + 0, + ( + format_hints.Hex(tableaddr), + table_name, + i, + format_hints.Hex(call_addr), + sym_name, + ), + ) + + def run(self): + return renderers.TreeGrid( + [ + ("Table Address", format_hints.Hex), + ("Table Name", str), + ("Index", int), + ("Handler Address", format_hints.Hex), + ("Handler Symbol", str), + ], + self._generator(), + ) From 70514396b307ca4f4b43bf1587d02cfe7f7dd1e9 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:35:26 +0300 Subject: [PATCH 12/25] linux.malware.check_syscall - fix test --- test/plugins/linux/linux.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..639cad464 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -41,7 +41,7 @@ class TestLinuxCheckIdt: class TestLinuxCheckSyscall: def test_linux_generic_check_syscall(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.check_syscall.Check_syscall", image, volatility, python + "linux.malware.check_syscall.Check_syscall", image, volatility, python ) assert rc == 0 From 962665b412980b556d4b003659504a42ca7dda7e Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:44:50 +0300 Subject: [PATCH 13/25] Plugins: categorize linux.check_afinfo as a malware plugin + test fix --- doc/source/getting-started-linux-tutorial.rst | 2 +- test/plugins/linux/linux.py | 2 +- .../framework/plugins/linux/check_afinfo.py | 215 +----------------- .../plugins/linux/malware/check_afinfo.py | 215 ++++++++++++++++++ 4 files changed, 227 insertions(+), 207 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/check_afinfo.py diff --git a/doc/source/getting-started-linux-tutorial.rst b/doc/source/getting-started-linux-tutorial.rst index 031b49636..267d3fc06 100644 --- a/doc/source/getting-started-linux-tutorial.rst +++ b/doc/source/getting-started-linux-tutorial.rst @@ -36,7 +36,7 @@ For plugin requests, please create an issue with a description of the requested $ python3 vol.py --help | grep -i linux. | head -n 5 banners.Banners Attempts to identify potential linux banners in an linux.bash.Bash Recovers bash command history from memory. - linux.check_afinfo.Check_afinfo + linux.malware.check_afinfo.Check_afinfo linux.check_creds.Check_creds linux.check_idt.Check_idt diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..6b4ae1363 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -426,7 +426,7 @@ class TestLinuxPageCacheInodepages: class TestLinuxCheckAfinfo: def test_linux_generic_check_afinfo(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.check_afinfo.Check_afinfo", image, volatility, python + "linux.malware.check_afinfo.Check_afinfo", image, volatility, python ) # linux-sample-1.bin has no suspicious results. diff --git a/volatility3/framework/plugins/linux/check_afinfo.py b/volatility3/framework/plugins/linux/check_afinfo.py index 47da21615..3f9e14161 100644 --- a/volatility3/framework/plugins/linux/check_afinfo.py +++ b/volatility3/framework/plugins/linux/check_afinfo.py @@ -1,215 +1,20 @@ -# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # -"""A module containing a plugin that verifies the operation function -pointers of network protocols.""" import logging -from typing import List, Tuple, Generator - -from volatility3.framework import exceptions, interfaces -from volatility3.framework import renderers -from volatility3.framework.configuration import requirements -from volatility3.framework.interfaces import plugins -from volatility3.framework.renderers import format_hints +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import check_afinfo vollog = logging.getLogger(__name__) -class Check_afinfo(plugins.PluginInterface): - """Verifies the operation function pointers of network protocols.""" +class Check_afinfo( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=check_afinfo.Check_afinfo, + removal_date="2026-06-07", +): + """Verifies the operation function pointers of network protocols (deprecated).""" _version = (1, 0, 0) _required_framework_version = (2, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - ] - - @classmethod - def _check_members( - cls, - context: interfaces.context.ContextInterface, - vmlinux_name: str, - var_ops: interfaces.objects.ObjectInterface, - var_name: str, - members: List[str], - ) -> Generator[Tuple[str, str, int], None, None]: - """ - Yields any members that are not pointing inside the kernel - """ - - vmlinux = context.modules[vmlinux_name] - - for check in members: - # redhat-specific garbage - if check.startswith("__UNIQUE_ID_rh_kabi_hide"): - continue - - # These structures have members like `write` and `next`, which are built in Python functions - addr = var_ops.member(attr=check) - - # Unimplemented handlers are set to 0 - if not addr: - continue - - if len(vmlinux.get_symbols_by_absolute_location(addr)) == 0: - yield var_name, check, addr - - @classmethod - def _check_pre_4_18_ops( - cls, - context: interfaces.context.ContextInterface, - vmlinux_name: str, - var_name: str, - var: interfaces.objects.ObjectInterface, - op_members: List[str], - seq_members: List[str], - ): - """ - Finds the correct way to reference `op_members` - """ - vmlinux = context.modules[vmlinux_name] - - if var.has_member("seq_fops"): - yield from cls._check_members( - context, vmlinux_name, var.seq_fops, var_name, op_members - ) - # newer kernels - if var.has_member("seq_ops"): - yield from cls._check_members( - context, vmlinux_name, var.seq_ops, var_name, seq_members - ) - - # this is the most commonly hooked member by rootkits, so a force a check on it - elif var.has_member("seq_show"): - if len(vmlinux.get_symbols_by_location(var.seq_show)) == 0: - yield var_name, "show", var.seq_show - else: - raise exceptions.VolatilityException( - "_check_afinfo_pre_4_18: Unable to find sequence operations members for checking." - ) - - @classmethod - def _check_afinfo_pre_4_18( - cls, - context: interfaces.context.ContextInterface, - vmlinux_name: str, - seq_members: str, - ) -> Generator[Tuple[str, str, int], None, None]: - """ - Checks the operations structures for network protocols of < 4.18 systems - """ - tcp = ("tcp_seq_afinfo", ["tcp6_seq_afinfo", "tcp4_seq_afinfo"]) - udp = ( - "udp_seq_afinfo", - [ - "udplite6_seq_afinfo", - "udp6_seq_afinfo", - "udplite4_seq_afinfo", - "udp4_seq_afinfo", - ], - ) - protocols = [tcp, udp] - - vmlinux = context.modules[vmlinux_name] - - op_members = vmlinux.get_type("file_operations").members - - # loop through all symbols - for struct_type, global_vars in protocols: - for global_var_name in global_vars: - # this will lookup fail for the IPv6 protocols on kernels without IPv6 support - try: - global_var = vmlinux.object_from_symbol(global_var_name) - except exceptions.SymbolError: - continue - - yield from cls._check_pre_4_18_ops( - context, - vmlinux_name, - global_var_name, - global_var, - op_members, - seq_members, - ) - - @classmethod - def _check_afinfo_post_4_18( - cls, - context: interfaces.context.ContextInterface, - vmlinux_name: str, - seq_members: str, - ) -> Generator[Tuple[str, str, int], None, None]: - """ - Checks the operations structures for network protocols of >= 4.18 systems - """ - vmlinux = context.modules[vmlinux_name] - - ops_structs = [ - "raw_seq_ops", - "udp_seq_ops", - "arp_seq_ops", - "unix_seq_ops", - "udp6_seq_ops", - "raw6_seq_ops", - "tcp_seq_ops", - "tcp4_seq_ops", - "tcp6_seq_ops", - "packet_seq_ops", - ] - - for protocol_ops_var in ops_structs: - # These will fail if the particular kernel doesn't have support for a protocol like IPv6 - try: - protocol_ops = vmlinux.object_from_symbol(protocol_ops_var) - except exceptions.SymbolError: - continue - - yield from cls._check_members( - context, vmlinux_name, protocol_ops, protocol_ops_var, seq_members - ) - - @classmethod - def check_afinfo( - cls, context: interfaces.context.ContextInterface, vmlinux_name - ) -> Generator[Tuple[str, str, int], None, None]: - """ - Walks the network protocol operations structures for common network protocols. - Reports any initialized operations members that do not point inside the kernel. - """ - vmlinux = context.modules[vmlinux_name] - - type_check = vmlinux.get_type("tcp_seq_afinfo") - if type_check.has_member("seq_fops"): - checker = cls._check_afinfo_pre_4_18 - else: - checker = cls._check_afinfo_post_4_18 - - seq_members = vmlinux.get_type("seq_operations").members - - yield from checker(context, vmlinux_name, seq_members) - - def _generator(self): - """ - A simple wrapper around `check_afino` - """ - for name, member, address in self.check_afinfo( - self.context, self.config["kernel"] - ): - yield 0, (name, member, format_hints.Hex(address)) - - def run(self): - return renderers.TreeGrid( - [ - ("Symbol Name", str), - ("Member", str), - ("Handler Address", format_hints.Hex), - ], - self._generator(), - ) diff --git a/volatility3/framework/plugins/linux/malware/check_afinfo.py b/volatility3/framework/plugins/linux/malware/check_afinfo.py new file mode 100644 index 000000000..47da21615 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/check_afinfo.py @@ -0,0 +1,215 @@ +# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +"""A module containing a plugin that verifies the operation function +pointers of network protocols.""" +import logging +from typing import List, Tuple, Generator + +from volatility3.framework import exceptions, interfaces +from volatility3.framework import renderers +from volatility3.framework.configuration import requirements +from volatility3.framework.interfaces import plugins +from volatility3.framework.renderers import format_hints + +vollog = logging.getLogger(__name__) + + +class Check_afinfo(plugins.PluginInterface): + """Verifies the operation function pointers of network protocols.""" + + _version = (1, 0, 0) + _required_framework_version = (2, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + ] + + @classmethod + def _check_members( + cls, + context: interfaces.context.ContextInterface, + vmlinux_name: str, + var_ops: interfaces.objects.ObjectInterface, + var_name: str, + members: List[str], + ) -> Generator[Tuple[str, str, int], None, None]: + """ + Yields any members that are not pointing inside the kernel + """ + + vmlinux = context.modules[vmlinux_name] + + for check in members: + # redhat-specific garbage + if check.startswith("__UNIQUE_ID_rh_kabi_hide"): + continue + + # These structures have members like `write` and `next`, which are built in Python functions + addr = var_ops.member(attr=check) + + # Unimplemented handlers are set to 0 + if not addr: + continue + + if len(vmlinux.get_symbols_by_absolute_location(addr)) == 0: + yield var_name, check, addr + + @classmethod + def _check_pre_4_18_ops( + cls, + context: interfaces.context.ContextInterface, + vmlinux_name: str, + var_name: str, + var: interfaces.objects.ObjectInterface, + op_members: List[str], + seq_members: List[str], + ): + """ + Finds the correct way to reference `op_members` + """ + vmlinux = context.modules[vmlinux_name] + + if var.has_member("seq_fops"): + yield from cls._check_members( + context, vmlinux_name, var.seq_fops, var_name, op_members + ) + # newer kernels + if var.has_member("seq_ops"): + yield from cls._check_members( + context, vmlinux_name, var.seq_ops, var_name, seq_members + ) + + # this is the most commonly hooked member by rootkits, so a force a check on it + elif var.has_member("seq_show"): + if len(vmlinux.get_symbols_by_location(var.seq_show)) == 0: + yield var_name, "show", var.seq_show + else: + raise exceptions.VolatilityException( + "_check_afinfo_pre_4_18: Unable to find sequence operations members for checking." + ) + + @classmethod + def _check_afinfo_pre_4_18( + cls, + context: interfaces.context.ContextInterface, + vmlinux_name: str, + seq_members: str, + ) -> Generator[Tuple[str, str, int], None, None]: + """ + Checks the operations structures for network protocols of < 4.18 systems + """ + tcp = ("tcp_seq_afinfo", ["tcp6_seq_afinfo", "tcp4_seq_afinfo"]) + udp = ( + "udp_seq_afinfo", + [ + "udplite6_seq_afinfo", + "udp6_seq_afinfo", + "udplite4_seq_afinfo", + "udp4_seq_afinfo", + ], + ) + protocols = [tcp, udp] + + vmlinux = context.modules[vmlinux_name] + + op_members = vmlinux.get_type("file_operations").members + + # loop through all symbols + for struct_type, global_vars in protocols: + for global_var_name in global_vars: + # this will lookup fail for the IPv6 protocols on kernels without IPv6 support + try: + global_var = vmlinux.object_from_symbol(global_var_name) + except exceptions.SymbolError: + continue + + yield from cls._check_pre_4_18_ops( + context, + vmlinux_name, + global_var_name, + global_var, + op_members, + seq_members, + ) + + @classmethod + def _check_afinfo_post_4_18( + cls, + context: interfaces.context.ContextInterface, + vmlinux_name: str, + seq_members: str, + ) -> Generator[Tuple[str, str, int], None, None]: + """ + Checks the operations structures for network protocols of >= 4.18 systems + """ + vmlinux = context.modules[vmlinux_name] + + ops_structs = [ + "raw_seq_ops", + "udp_seq_ops", + "arp_seq_ops", + "unix_seq_ops", + "udp6_seq_ops", + "raw6_seq_ops", + "tcp_seq_ops", + "tcp4_seq_ops", + "tcp6_seq_ops", + "packet_seq_ops", + ] + + for protocol_ops_var in ops_structs: + # These will fail if the particular kernel doesn't have support for a protocol like IPv6 + try: + protocol_ops = vmlinux.object_from_symbol(protocol_ops_var) + except exceptions.SymbolError: + continue + + yield from cls._check_members( + context, vmlinux_name, protocol_ops, protocol_ops_var, seq_members + ) + + @classmethod + def check_afinfo( + cls, context: interfaces.context.ContextInterface, vmlinux_name + ) -> Generator[Tuple[str, str, int], None, None]: + """ + Walks the network protocol operations structures for common network protocols. + Reports any initialized operations members that do not point inside the kernel. + """ + vmlinux = context.modules[vmlinux_name] + + type_check = vmlinux.get_type("tcp_seq_afinfo") + if type_check.has_member("seq_fops"): + checker = cls._check_afinfo_pre_4_18 + else: + checker = cls._check_afinfo_post_4_18 + + seq_members = vmlinux.get_type("seq_operations").members + + yield from checker(context, vmlinux_name, seq_members) + + def _generator(self): + """ + A simple wrapper around `check_afino` + """ + for name, member, address in self.check_afinfo( + self.context, self.config["kernel"] + ): + yield 0, (name, member, format_hints.Hex(address)) + + def run(self): + return renderers.TreeGrid( + [ + ("Symbol Name", str), + ("Member", str), + ("Handler Address", format_hints.Hex), + ], + self._generator(), + ) From 1d2b78976a9fe0bbe201dba1df810afe837e8863 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:54:44 +0300 Subject: [PATCH 14/25] Plugins: categorize linux.hidden_modules as a malware plugin --- test/plugins/linux/linux.py | 2 +- .../framework/plugins/linux/hidden_modules.py | 196 +---------------- .../plugins/linux/malware/hidden_modules.py | 197 ++++++++++++++++++ 3 files changed, 208 insertions(+), 187 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/hidden_modules.py diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index 6b4ae1363..63ccc3388 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -525,7 +525,7 @@ class TestLinuxHiddenModules: # TODO: this check should be specific, against a distinct infected sample image = LinuxSamples.LINUX_GENERIC.value.path rc, out, _err = test_volatility.runvol_plugin( - "linux.hidden_modules.Hidden_modules", image, volatility, python + "linux.malware.hidden_modules.Hidden_modules", image, volatility, python ) # linux-sample-1.bin has no hidden modules. diff --git a/volatility3/framework/plugins/linux/hidden_modules.py b/volatility3/framework/plugins/linux/hidden_modules.py index dcd602c5d..eab3c19a2 100644 --- a/volatility3/framework/plugins/linux/hidden_modules.py +++ b/volatility3/framework/plugins/linux/hidden_modules.py @@ -1,197 +1,21 @@ -# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # import logging -from typing import List, Set, Tuple, Iterable -from volatility3.framework.symbols.linux.utilities import ( - modules as linux_utilities_modules, -) -from volatility3.framework import interfaces, exceptions, deprecation -from volatility3.framework.configuration import requirements -from volatility3.framework.symbols.linux import extensions -from volatility3.framework.interfaces import plugins +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import hidden_modules vollog = logging.getLogger(__name__) -class Hidden_modules(plugins.PluginInterface): - """Carves memory to find hidden kernel modules""" +class Hidden_modules( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=hidden_modules.Hidden_modules, + removal_date="2026-06-07", +): + """Carves memory to find hidden kernel modules (deprecated).""" _required_framework_version = (2, 25, 0) _version = (3, 0, 2) - @classmethod - def find_hidden_modules( - cls, context, vmlinux_module_name: str - ) -> extensions.module: - if context.symbol_space.verify_table_versions( - "dwarf2json", lambda version, _: (not version) or version < (0, 8, 0) - ): - raise exceptions.SymbolSpaceError( - "Invalid symbol table, please ensure the ISF table produced by dwarf2json was created with version 0.8.0 or later" - ) - - known_module_addresses = cls.get_lsmod_module_addresses( - context, vmlinux_module_name - ) - modules_memory_boundaries = ( - linux_utilities_modules.Modules.get_modules_memory_boundaries( - context, vmlinux_module_name - ) - ) - - yield from linux_utilities_modules.Modules.get_hidden_modules( - context, - vmlinux_module_name, - known_module_addresses, - modules_memory_boundaries, - ) - - @classmethod - def get_hidden_modules( - cls, - context: interfaces.context.ContextInterface, - vmlinux_module_name: str, - known_module_addresses: Set[int], - modules_memory_boundaries: Tuple, - ) -> Iterable[interfaces.objects.ObjectInterface]: - """Enumerate hidden modules by taking advantage of memory address alignment patterns - - This technique is much faster and uses less memory than the traditional scan method - in Volatility2, but it doesn't work with older kernels. - - From kernels 4.2 struct module allocation are aligned to the L1 cache line size. - In i386/amd64/arm64 this is typically 64 bytes. However, this can be changed in - the Linux kernel configuration via CONFIG_X86_L1_CACHE_SHIFT. The alignment can - also be obtained from the DWARF info i.e. DW_AT_alignment<64>, but dwarf2json - doesn't support this feature yet. - In kernels < 4.2, alignment attributes are absent in the struct module, meaning - alignment cannot be guaranteed. Therefore, for older kernels, it's better to use - the traditional scan technique. - - Args: - context: The context to retrieve required elements (layers, symbol tables) from - vmlinux_module_name: The name of the kernel module on which to operate - known_module_addresses: Set with known module addresses - modules_memory_boundaries: Minimum and maximum address boundaries for module allocation. - Yields: - module objects - """ - return linux_utilities_modules.get_hidden_modules( - vmlinux_module_name, known_module_addresses, modules_memory_boundaries - ) - - run = linux_utilities_modules.ModuleDisplayPlugin.run - _generator = linux_utilities_modules.ModuleDisplayPlugin.generator - implementation = find_hidden_modules - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.VersionRequirement( - name="linux_utilities_modules_module_display_plugin", - component=linux_utilities_modules.ModuleDisplayPlugin, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 1), - ), - ] + linux_utilities_modules.ModuleDisplayPlugin.get_requirements() - - @staticmethod - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.get_modules_memory_boundaries, - removal_date="2025-09-25", - replacement_version=(3, 0, 0), - ) - def get_modules_memory_boundaries( - context: interfaces.context.ContextInterface, - vmlinux_module_name: str, - ) -> Tuple[int, int]: - return linux_utilities_modules.Modules.get_modules_memory_boundaries( - context, vmlinux_module_name - ) - - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.get_module_address_alignment, - removal_date="2025-09-25", - replacement_version=(3, 0, 0), - ) - @classmethod - def _get_module_address_alignment( - cls, - context: interfaces.context.ContextInterface, - vmlinux_module_name: str, - ) -> int: - """Obtain the module memory address alignment. - - struct module is aligned to the L1 cache line, which is typically 64 bytes for most - common i386/AMD64/ARM64 configurations. In some cases, it can be 128 bytes, but this - will still work. - - Args: - context: The context to retrieve required elements (layers, symbol tables) from - vmlinux_module_name: The name of the kernel module on which to operate - - Returns: - The struct module alignment - """ - return linux_utilities_modules.get_module_address_alignment( - context, vmlinux_module_name - ) - - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.get_hidden_modules, - removal_date="2025-09-25", - replacement_version=(3, 0, 0), - ) - @staticmethod - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.validate_alignment_patterns, - removal_date="2025-09-25", - replacement_version=(3, 0, 0), - ) - def _validate_alignment_patterns( - addresses: Iterable[int], - address_alignment: int, - ) -> bool: - """Check if the memory addresses meet our alignments patterns - - Args: - addresses: Iterable with the address values - address_alignment: Number of bytes for alignment validation - - Returns: - True if all the addresses meet the alignment - """ - return linux_utilities_modules.validate_alignment_patterns( - addresses, address_alignment - ) - - @classmethod - def get_lsmod_module_addresses( - cls, - context: interfaces.context.ContextInterface, - vmlinux_module_name: str, - ) -> Set[int]: - """Obtain a set the known module addresses from linux.lsmod plugin - - Args: - context: The context to retrieve required elements (layers, symbol tables) from - vmlinux_module_name: The name of the kernel module on which to operate - - Returns: - A set containing known kernel module addresses - """ - vmlinux = context.modules[vmlinux_module_name] - vmlinux_layer = context.layers[vmlinux.layer_name] - - known_module_addresses = { - vmlinux_layer.canonicalize(module.vol.offset) - for module in linux_utilities_modules.Modules.list_modules( - context, vmlinux_module_name - ) - } - return known_module_addresses diff --git a/volatility3/framework/plugins/linux/malware/hidden_modules.py b/volatility3/framework/plugins/linux/malware/hidden_modules.py new file mode 100644 index 000000000..dcd602c5d --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/hidden_modules.py @@ -0,0 +1,197 @@ +# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +import logging +from typing import List, Set, Tuple, Iterable +from volatility3.framework.symbols.linux.utilities import ( + modules as linux_utilities_modules, +) +from volatility3.framework import interfaces, exceptions, deprecation +from volatility3.framework.configuration import requirements +from volatility3.framework.symbols.linux import extensions +from volatility3.framework.interfaces import plugins + +vollog = logging.getLogger(__name__) + + +class Hidden_modules(plugins.PluginInterface): + """Carves memory to find hidden kernel modules""" + + _required_framework_version = (2, 25, 0) + _version = (3, 0, 2) + + @classmethod + def find_hidden_modules( + cls, context, vmlinux_module_name: str + ) -> extensions.module: + if context.symbol_space.verify_table_versions( + "dwarf2json", lambda version, _: (not version) or version < (0, 8, 0) + ): + raise exceptions.SymbolSpaceError( + "Invalid symbol table, please ensure the ISF table produced by dwarf2json was created with version 0.8.0 or later" + ) + + known_module_addresses = cls.get_lsmod_module_addresses( + context, vmlinux_module_name + ) + modules_memory_boundaries = ( + linux_utilities_modules.Modules.get_modules_memory_boundaries( + context, vmlinux_module_name + ) + ) + + yield from linux_utilities_modules.Modules.get_hidden_modules( + context, + vmlinux_module_name, + known_module_addresses, + modules_memory_boundaries, + ) + + @classmethod + def get_hidden_modules( + cls, + context: interfaces.context.ContextInterface, + vmlinux_module_name: str, + known_module_addresses: Set[int], + modules_memory_boundaries: Tuple, + ) -> Iterable[interfaces.objects.ObjectInterface]: + """Enumerate hidden modules by taking advantage of memory address alignment patterns + + This technique is much faster and uses less memory than the traditional scan method + in Volatility2, but it doesn't work with older kernels. + + From kernels 4.2 struct module allocation are aligned to the L1 cache line size. + In i386/amd64/arm64 this is typically 64 bytes. However, this can be changed in + the Linux kernel configuration via CONFIG_X86_L1_CACHE_SHIFT. The alignment can + also be obtained from the DWARF info i.e. DW_AT_alignment<64>, but dwarf2json + doesn't support this feature yet. + In kernels < 4.2, alignment attributes are absent in the struct module, meaning + alignment cannot be guaranteed. Therefore, for older kernels, it's better to use + the traditional scan technique. + + Args: + context: The context to retrieve required elements (layers, symbol tables) from + vmlinux_module_name: The name of the kernel module on which to operate + known_module_addresses: Set with known module addresses + modules_memory_boundaries: Minimum and maximum address boundaries for module allocation. + Yields: + module objects + """ + return linux_utilities_modules.get_hidden_modules( + vmlinux_module_name, known_module_addresses, modules_memory_boundaries + ) + + run = linux_utilities_modules.ModuleDisplayPlugin.run + _generator = linux_utilities_modules.ModuleDisplayPlugin.generator + implementation = find_hidden_modules + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.VersionRequirement( + name="linux_utilities_modules_module_display_plugin", + component=linux_utilities_modules.ModuleDisplayPlugin, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 1), + ), + ] + linux_utilities_modules.ModuleDisplayPlugin.get_requirements() + + @staticmethod + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.get_modules_memory_boundaries, + removal_date="2025-09-25", + replacement_version=(3, 0, 0), + ) + def get_modules_memory_boundaries( + context: interfaces.context.ContextInterface, + vmlinux_module_name: str, + ) -> Tuple[int, int]: + return linux_utilities_modules.Modules.get_modules_memory_boundaries( + context, vmlinux_module_name + ) + + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.get_module_address_alignment, + removal_date="2025-09-25", + replacement_version=(3, 0, 0), + ) + @classmethod + def _get_module_address_alignment( + cls, + context: interfaces.context.ContextInterface, + vmlinux_module_name: str, + ) -> int: + """Obtain the module memory address alignment. + + struct module is aligned to the L1 cache line, which is typically 64 bytes for most + common i386/AMD64/ARM64 configurations. In some cases, it can be 128 bytes, but this + will still work. + + Args: + context: The context to retrieve required elements (layers, symbol tables) from + vmlinux_module_name: The name of the kernel module on which to operate + + Returns: + The struct module alignment + """ + return linux_utilities_modules.get_module_address_alignment( + context, vmlinux_module_name + ) + + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.get_hidden_modules, + removal_date="2025-09-25", + replacement_version=(3, 0, 0), + ) + @staticmethod + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.validate_alignment_patterns, + removal_date="2025-09-25", + replacement_version=(3, 0, 0), + ) + def _validate_alignment_patterns( + addresses: Iterable[int], + address_alignment: int, + ) -> bool: + """Check if the memory addresses meet our alignments patterns + + Args: + addresses: Iterable with the address values + address_alignment: Number of bytes for alignment validation + + Returns: + True if all the addresses meet the alignment + """ + return linux_utilities_modules.validate_alignment_patterns( + addresses, address_alignment + ) + + @classmethod + def get_lsmod_module_addresses( + cls, + context: interfaces.context.ContextInterface, + vmlinux_module_name: str, + ) -> Set[int]: + """Obtain a set the known module addresses from linux.lsmod plugin + + Args: + context: The context to retrieve required elements (layers, symbol tables) from + vmlinux_module_name: The name of the kernel module on which to operate + + Returns: + A set containing known kernel module addresses + """ + vmlinux = context.modules[vmlinux_module_name] + vmlinux_layer = context.layers[vmlinux.layer_name] + + known_module_addresses = { + vmlinux_layer.canonicalize(module.vol.offset) + for module in linux_utilities_modules.Modules.list_modules( + context, vmlinux_module_name + ) + } + return known_module_addresses From 5144f26a8edbe99b90411bfbaa354d4afa1d0b47 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 19:58:12 +0300 Subject: [PATCH 15/25] CI --- volatility3/framework/plugins/linux/hidden_modules.py | 1 - 1 file changed, 1 deletion(-) diff --git a/volatility3/framework/plugins/linux/hidden_modules.py b/volatility3/framework/plugins/linux/hidden_modules.py index eab3c19a2..f7bdd6b0b 100644 --- a/volatility3/framework/plugins/linux/hidden_modules.py +++ b/volatility3/framework/plugins/linux/hidden_modules.py @@ -18,4 +18,3 @@ class Hidden_modules( _required_framework_version = (2, 25, 0) _version = (3, 0, 2) - From 35c4e9f50b3b7dc09af0bb0c7bccbe884bf819db Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 21:52:22 +0300 Subject: [PATCH 16/25] Plugins: change class name to original --- volatility3/framework/plugins/windows/unhooked_system_calls.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index e6fb2fb6c..a0864e38d 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -8,7 +8,7 @@ from volatility3.plugins.windows.malware import unhooked_system_calls vollog = logging.getLogger(__name__) -class UnhookedSystemCalls( +class unhooked_system_calls( interfaces.plugins.PluginInterface, deprecation.PluginRenameClass, replacement_class=unhooked_system_calls.UnhookedSystemCalls, From 21d66839fe942aeb327572f7056850ea813d396d Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 21:56:36 +0300 Subject: [PATCH 17/25] use class name with module name? --- .../framework/plugins/windows/unhooked_system_calls.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index a0864e38d..fa88f5523 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -3,7 +3,7 @@ # import logging from volatility3.framework import interfaces, deprecation -from volatility3.plugins.windows.malware import unhooked_system_calls +from volatility3.plugins.windows import malware vollog = logging.getLogger(__name__) @@ -11,7 +11,7 @@ vollog = logging.getLogger(__name__) class unhooked_system_calls( interfaces.plugins.PluginInterface, deprecation.PluginRenameClass, - replacement_class=unhooked_system_calls.UnhookedSystemCalls, + replacement_class=malware.unhooked_system_calls.UnhookedSystemCalls, removal_date="2026-06-07", ): """Detects hooked ntdll.dll stub functions in Windows processes (deprecated).""" From c71fd30c8a4baa873b27044546822b7e9084ad62 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 21:58:43 +0300 Subject: [PATCH 18/25] shortcut class name --- .../framework/plugins/windows/unhooked_system_calls.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index fa88f5523..70219da13 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -3,7 +3,7 @@ # import logging from volatility3.framework import interfaces, deprecation -from volatility3.plugins.windows import malware +from volatility3.plugins.windows.malware import unhooked_system_calls as unhooked_syscalls vollog = logging.getLogger(__name__) @@ -11,7 +11,7 @@ vollog = logging.getLogger(__name__) class unhooked_system_calls( interfaces.plugins.PluginInterface, deprecation.PluginRenameClass, - replacement_class=malware.unhooked_system_calls.UnhookedSystemCalls, + replacement_class=unhooked_syscalls.UnhookedSystemCalls, removal_date="2026-06-07", ): """Detects hooked ntdll.dll stub functions in Windows processes (deprecated).""" From f9941b5b6ec67d79da687870d727c8ea082cd3e5 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 22:00:03 +0300 Subject: [PATCH 19/25] black --- .../framework/plugins/windows/unhooked_system_calls.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/volatility3/framework/plugins/windows/unhooked_system_calls.py b/volatility3/framework/plugins/windows/unhooked_system_calls.py index 70219da13..3827bbe6e 100644 --- a/volatility3/framework/plugins/windows/unhooked_system_calls.py +++ b/volatility3/framework/plugins/windows/unhooked_system_calls.py @@ -3,7 +3,9 @@ # import logging from volatility3.framework import interfaces, deprecation -from volatility3.plugins.windows.malware import unhooked_system_calls as unhooked_syscalls +from volatility3.plugins.windows.malware import ( + unhooked_system_calls as unhooked_syscalls, +) vollog = logging.getLogger(__name__) From faf7d781be8f7b15d15d28126676dc7d11b2e12e Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 22:55:29 +0300 Subject: [PATCH 20/25] Plugins: categorize linux.keyboard_notifiers as a malware plugin --- test/plugins/linux/linux.py | 2 +- .../plugins/linux/keyboard_notifiers.py | 106 ++---------------- .../linux/malware/keyboard_notifiers.py | 105 +++++++++++++++++ 3 files changed, 117 insertions(+), 96 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/keyboard_notifiers.py diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..9a11d9c95 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -479,7 +479,7 @@ class TestLinuxIomem: class TestLinuxKeyboardNotifiers: def test_linux_generic_keyboard_notifiers(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.keyboard_notifiers.Keyboard_notifiers", image, volatility, python + "linux.malware.keyboard_notifiers.Keyboard_notifiers", image, volatility, python ) # linux-sample-1.bin has no suspicious results for this plugin. diff --git a/volatility3/framework/plugins/linux/keyboard_notifiers.py b/volatility3/framework/plugins/linux/keyboard_notifiers.py index 215704350..72dcc7bad 100644 --- a/volatility3/framework/plugins/linux/keyboard_notifiers.py +++ b/volatility3/framework/plugins/linux/keyboard_notifiers.py @@ -1,104 +1,20 @@ -# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # - import logging - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules -from volatility3.framework import interfaces, renderers, exceptions -from volatility3.framework.configuration import requirements -from volatility3.framework.renderers import format_hints -from volatility3.framework.symbols import linux +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import keyboard_notifiers vollog = logging.getLogger(__name__) -class Keyboard_notifiers(interfaces.plugins.PluginInterface): - """Parses the keyboard notifier call chain""" +class Keyboard_notifiers( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=keyboard_notifiers.Keyboard_notifiers, + removal_date="2026-06-07", +): + """Parses the keyboard notifier call chain (deprecated).""" _required_framework_version = (2, 0, 0) - - @classmethod - def get_requirements(cls): - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="linux_utilities_modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherers", - component=linux_utilities_modules.ModuleGatherers, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) - ), - ] - - def _generator(self): - vmlinux = self.context.modules[self.config["kernel"]] - - try: - knl_addr = vmlinux.object_from_symbol("keyboard_notifier_list") - except exceptions.SymbolError: - knl_addr = None - - if not knl_addr: - raise TypeError( - "This plugin requires the keyboard_notifier_list structure. " - "This structure is not present in the supplied symbol table. " - "This means you are either analyzing an unsupported kernel version or that your symbol table is corrupt." - ) - - if not self.context.layers[vmlinux.layer_name].is_valid(knl_addr.vol.offset): - vollog.error("The head of the keyboard notifier list is paged out.") - return - - known_modules = linux_utilities_modules.Modules.run_modules_scanners( - context=self.context, - kernel_module_name=self.config["kernel"], - caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, - ) - - knl = vmlinux.object( - object_type="atomic_notifier_head", - offset=knl_addr.vol.offset, - absolute=True, - ) - - for call_back in linux.LinuxUtilities.walk_internal_list( - vmlinux, "notifier_block", "next", knl.head - ): - call_addr = call_back.notifier_call - - module_info, symbol_name = ( - linux_utilities_modules.Modules.module_lookup_by_address( - self.context, vmlinux.name, known_modules, call_addr - ) - ) - - if module_info: - module_name = module_info.name - else: - module_name = renderers.NotAvailableValue() - - yield ( - 0, - [ - format_hints.Hex(call_addr), - module_name, - symbol_name or renderers.NotAvailableValue(), - ], - ) - - def run(self): - return renderers.TreeGrid( - [("Address", format_hints.Hex), ("Module", str), ("Symbol", str)], - self._generator(), - ) + _version = (1, 0, 0) diff --git a/volatility3/framework/plugins/linux/malware/keyboard_notifiers.py b/volatility3/framework/plugins/linux/malware/keyboard_notifiers.py new file mode 100644 index 000000000..9e99809b2 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/keyboard_notifiers.py @@ -0,0 +1,105 @@ +# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# + +import logging + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules +from volatility3.framework import interfaces, renderers, exceptions +from volatility3.framework.configuration import requirements +from volatility3.framework.renderers import format_hints +from volatility3.framework.symbols import linux + +vollog = logging.getLogger(__name__) + + +class Keyboard_notifiers(interfaces.plugins.PluginInterface): + """Parses the keyboard notifier call chain""" + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 0) + + @classmethod + def get_requirements(cls): + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="linux_utilities_modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherers", + component=linux_utilities_modules.ModuleGatherers, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) + ), + ] + + def _generator(self): + vmlinux = self.context.modules[self.config["kernel"]] + + try: + knl_addr = vmlinux.object_from_symbol("keyboard_notifier_list") + except exceptions.SymbolError: + knl_addr = None + + if not knl_addr: + raise TypeError( + "This plugin requires the keyboard_notifier_list structure. " + "This structure is not present in the supplied symbol table. " + "This means you are either analyzing an unsupported kernel version or that your symbol table is corrupt." + ) + + if not self.context.layers[vmlinux.layer_name].is_valid(knl_addr.vol.offset): + vollog.error("The head of the keyboard notifier list is paged out.") + return + + known_modules = linux_utilities_modules.Modules.run_modules_scanners( + context=self.context, + kernel_module_name=self.config["kernel"], + caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, + ) + + knl = vmlinux.object( + object_type="atomic_notifier_head", + offset=knl_addr.vol.offset, + absolute=True, + ) + + for call_back in linux.LinuxUtilities.walk_internal_list( + vmlinux, "notifier_block", "next", knl.head + ): + call_addr = call_back.notifier_call + + module_info, symbol_name = ( + linux_utilities_modules.Modules.module_lookup_by_address( + self.context, vmlinux.name, known_modules, call_addr + ) + ) + + if module_info: + module_name = module_info.name + else: + module_name = renderers.NotAvailableValue() + + yield ( + 0, + [ + format_hints.Hex(call_addr), + module_name, + symbol_name or renderers.NotAvailableValue(), + ], + ) + + def run(self): + return renderers.TreeGrid( + [("Address", format_hints.Hex), ("Module", str), ("Symbol", str)], + self._generator(), + ) From a06d59bc52d670ba3ba9ccef11c0fdd9d4e88d0c Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Sat, 7 Jun 2025 22:58:46 +0300 Subject: [PATCH 21/25] Plugins: categorize linux.malfind as a malware plugin --- test/plugins/linux/linux.py | 7 +- .../framework/plugins/linux/malfind.py | 114 ++---------------- .../plugins/linux/malware/malfind.py | 114 ++++++++++++++++++ 3 files changed, 129 insertions(+), 106 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/malfind.py diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index 9a11d9c95..69aeb8a6c 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -251,7 +251,7 @@ class TestLinuxKthreads: class TestLinuxMalfind: def test_linux_generic_malfind(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.malfind.Malfind", image, volatility, python + "linux.malware.malfind.Malfind", image, volatility, python ) # linux-sample-1.bin has no process memory ranges with potential injected code. @@ -479,7 +479,10 @@ class TestLinuxIomem: class TestLinuxKeyboardNotifiers: def test_linux_generic_keyboard_notifiers(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.malware.keyboard_notifiers.Keyboard_notifiers", image, volatility, python + "linux.malware.keyboard_notifiers.Keyboard_notifiers", + image, + volatility, + python, ) # linux-sample-1.bin has no suspicious results for this plugin. diff --git a/volatility3/framework/plugins/linux/malfind.py b/volatility3/framework/plugins/linux/malfind.py index c7e141c02..647e1531a 100644 --- a/volatility3/framework/plugins/linux/malfind.py +++ b/volatility3/framework/plugins/linux/malfind.py @@ -1,114 +1,20 @@ -# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # - -from typing import List, Tuple, Optional import logging -from volatility3.framework import interfaces -from volatility3.framework import renderers, symbols -from volatility3.framework.configuration import requirements -from volatility3.framework.objects import utility -from volatility3.framework.renderers import format_hints -from volatility3.plugins.linux import pslist +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import malfind vollog = logging.getLogger(__name__) -class Malfind(interfaces.plugins.PluginInterface): - """Lists process memory ranges that potentially contain injected code.""" +class Malfind( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=malfind.Malfind, + removal_date="2026-06-07", +): + """Lists process memory ranges that potentially contain injected code (deprecated).""" _required_framework_version = (2, 0, 0) _version = (1, 0, 3) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="pslist", component=pslist.PsList, version=(4, 0, 0) - ), - requirements.ListRequirement( - name="pid", - description="Filter on specific process IDs", - element_type=int, - optional=True, - ), - ] - - def _list_injections( - self, task - ) -> Tuple[interfaces.objects.ObjectInterface, Optional[str], bytes]: - """Generate memory regions for a process that may contain injected - code.""" - - proc_layer_name = task.add_process_layer() - if not proc_layer_name: - return None - - proc_layer = self.context.layers[proc_layer_name] - - for vma in task.mm.get_vma_iter(): - vma_name = vma.get_name(self.context, task) - vollog.debug( - f"Injections : processing PID {task.pid} : VMA {vma_name} : {hex(vma.vm_start)}-{hex(vma.vm_end)}" - ) - if vma.is_suspicious(proc_layer) and vma_name != "[vdso]": - data = proc_layer.read(vma.vm_start, 64, pad=True) - yield vma, vma_name, data - - def _generator(self, tasks): - # determine if we're on a 32 or 64 bit kernel - vmlinux = self.context.modules[self.config["kernel"]] - is_32bit_arch = not symbols.symbol_table_is_64bit( - context=self.context, symbol_table_name=vmlinux.symbol_table_name - ) - - for task in tasks: - process_name = utility.array_to_string(task.comm) - - for vma, vma_name, data in self._list_injections(task): - if is_32bit_arch: - architecture = "intel" - else: - architecture = "intel64" - - disasm = renderers.Disassembly(data, vma.vm_start, architecture) - - yield ( - 0, - ( - task.pid, - process_name, - format_hints.Hex(vma.vm_start), - format_hints.Hex(vma.vm_end), - vma_name or renderers.NotAvailableValue(), - vma.get_protection(), - format_hints.HexBytes(data), - disasm, - ), - ) - - def run(self): - filter_func = pslist.PsList.create_pid_filter(self.config.get("pid", None)) - - return renderers.TreeGrid( - [ - ("PID", int), - ("Process", str), - ("Start", format_hints.Hex), - ("End", format_hints.Hex), - ("Path", str), - ("Protection", str), - ("Hexdump", format_hints.HexBytes), - ("Disasm", renderers.Disassembly), - ], - self._generator( - pslist.PsList.list_tasks( - self.context, self.config["kernel"], filter_func=filter_func - ) - ), - ) diff --git a/volatility3/framework/plugins/linux/malware/malfind.py b/volatility3/framework/plugins/linux/malware/malfind.py new file mode 100644 index 000000000..c7e141c02 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/malfind.py @@ -0,0 +1,114 @@ +# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# + +from typing import List, Tuple, Optional +import logging +from volatility3.framework import interfaces +from volatility3.framework import renderers, symbols +from volatility3.framework.configuration import requirements +from volatility3.framework.objects import utility +from volatility3.framework.renderers import format_hints +from volatility3.plugins.linux import pslist + +vollog = logging.getLogger(__name__) + + +class Malfind(interfaces.plugins.PluginInterface): + """Lists process memory ranges that potentially contain injected code.""" + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 3) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="pslist", component=pslist.PsList, version=(4, 0, 0) + ), + requirements.ListRequirement( + name="pid", + description="Filter on specific process IDs", + element_type=int, + optional=True, + ), + ] + + def _list_injections( + self, task + ) -> Tuple[interfaces.objects.ObjectInterface, Optional[str], bytes]: + """Generate memory regions for a process that may contain injected + code.""" + + proc_layer_name = task.add_process_layer() + if not proc_layer_name: + return None + + proc_layer = self.context.layers[proc_layer_name] + + for vma in task.mm.get_vma_iter(): + vma_name = vma.get_name(self.context, task) + vollog.debug( + f"Injections : processing PID {task.pid} : VMA {vma_name} : {hex(vma.vm_start)}-{hex(vma.vm_end)}" + ) + if vma.is_suspicious(proc_layer) and vma_name != "[vdso]": + data = proc_layer.read(vma.vm_start, 64, pad=True) + yield vma, vma_name, data + + def _generator(self, tasks): + # determine if we're on a 32 or 64 bit kernel + vmlinux = self.context.modules[self.config["kernel"]] + is_32bit_arch = not symbols.symbol_table_is_64bit( + context=self.context, symbol_table_name=vmlinux.symbol_table_name + ) + + for task in tasks: + process_name = utility.array_to_string(task.comm) + + for vma, vma_name, data in self._list_injections(task): + if is_32bit_arch: + architecture = "intel" + else: + architecture = "intel64" + + disasm = renderers.Disassembly(data, vma.vm_start, architecture) + + yield ( + 0, + ( + task.pid, + process_name, + format_hints.Hex(vma.vm_start), + format_hints.Hex(vma.vm_end), + vma_name or renderers.NotAvailableValue(), + vma.get_protection(), + format_hints.HexBytes(data), + disasm, + ), + ) + + def run(self): + filter_func = pslist.PsList.create_pid_filter(self.config.get("pid", None)) + + return renderers.TreeGrid( + [ + ("PID", int), + ("Process", str), + ("Start", format_hints.Hex), + ("End", format_hints.Hex), + ("Path", str), + ("Protection", str), + ("Hexdump", format_hints.HexBytes), + ("Disasm", renderers.Disassembly), + ], + self._generator( + pslist.PsList.list_tasks( + self.context, self.config["kernel"], filter_func=filter_func + ) + ), + ) From 6c35bc3fa0135c7c4124b327d536f7ea4cba11ca Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Tue, 10 Jun 2025 19:12:09 +0300 Subject: [PATCH 22/25] Plugins: categorize linux.modxview as a malware plugin --- .../plugins/linux/malware/modxview.py | 181 ++++++++++++++++++ .../framework/plugins/linux/modxview.py | 181 ++---------------- 2 files changed, 192 insertions(+), 170 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/modxview.py diff --git a/volatility3/framework/plugins/linux/malware/modxview.py b/volatility3/framework/plugins/linux/malware/modxview.py new file mode 100644 index 000000000..c1707d26f --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/modxview.py @@ -0,0 +1,181 @@ +# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +import logging +from typing import List, Dict, Iterator + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules + +from volatility3.framework import interfaces, deprecation, renderers +from volatility3.framework.configuration import requirements +from volatility3.framework.renderers import format_hints +from volatility3.framework.symbols.linux import extensions +from volatility3.framework.constants import architectures +from volatility3.framework.symbols.linux.utilities import tainting + +vollog = logging.getLogger(__name__) + + +class Modxview(interfaces.plugins.PluginInterface): + """Centralize lsmod, check_modules and hidden_modules results to efficiently \ +spot modules presence and taints.""" + + _version = (1, 0, 0) + _required_framework_version = (2, 17, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=architectures.LINUX_ARCHS, + ), + requirements.VersionRequirement( + name="linux_utilities_modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherer_lsmod", + component=linux_utilities_modules.ModuleGathererLsmod, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherer_sysfs", + component=linux_utilities_modules.ModuleGathererSysFs, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherer_scanner", + component=linux_utilities_modules.ModuleGathererScanner, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linux-tainting", component=tainting.Tainting, version=(1, 0, 0) + ), + requirements.BooleanRequirement( + name="plain_taints", + description="Display the plain taints string for each module.", + optional=True, + default=False, + ), + ] + + @classmethod + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.flatten_run_modules_results, + replacement_version=(3, 0, 0), + removal_date="2025-09-25", + ) + def flatten_run_modules_results( + cls, run_results: Dict[str, List[extensions.module]], deduplicate: bool = True + ) -> Iterator[extensions.module]: + """Flatten a dictionary mapping plugin names and modules list, to a single merged list. + This is useful to get a generic lookup list of all the detected modules. + + Args: + run_results: dictionary of plugin names mapping a list of detected modules + deduplicate: remove duplicate modules, based on their offsets + + Returns: + Iterator of modules objects + """ + return linux_utilities_modules.Modules.flatten_run_modules_results( + run_results, deduplicate + ) + + @classmethod + @deprecation.deprecated_method( + replacement=linux_utilities_modules.Modules.run_modules_scanners, + replacement_version=(3, 0, 0), + removal_date="2025-09-25", + ) + def run_modules_scanners( + cls, + context: interfaces.context.ContextInterface, + kernel_name: str, + run_hidden_modules: bool = True, + ) -> Dict[str, List[extensions.module]]: + """Run module scanning plugins and aggregate the results. It is designed + to not operate any inter-plugin results triage.""" + return linux_utilities_modules.Modules.run_modules_scanners( + context, kernel_name, run_hidden_modules + ) + + def _generator(self): + kernel = self.context.modules[self.config["kernel"]] + + wanted_gatherers = [ + linux_utilities_modules.ModuleGathererLsmod, + linux_utilities_modules.ModuleGathererSysFs, + linux_utilities_modules.ModuleGathererScanner, + ] + + run_results = linux_utilities_modules.Modules.run_modules_scanners( + context=self.context, + kernel_module_name=self.config["kernel"], + caller_wanted_gatherers=wanted_gatherers, + flatten=False, + ) + + aggregated_modules = {} + # We want to be explicit on the plugins results we are interested in + for gatherer in wanted_gatherers: + # Iterate over each recovered module + for mod_info in run_results[gatherer.name]: + # Use offsets as unique keys, whether a module + # appears in many plugin runs or not + if aggregated_modules.get(mod_info.offset, None) is not None: + # Append the plugin to the list of originating plugins + aggregated_modules[mod_info.offset].append(gatherer.name) + else: + aggregated_modules[mod_info.offset] = [gatherer.name] + + for module_offset, gatherers in aggregated_modules.items(): + module = kernel.object("module", offset=module_offset, absolute=True) + + # Tainting parsing capabilities applied to the module + if self.config.get("plain_taints"): + taints = tainting.Tainting.get_taints_as_plain_string( + self.context, + self.config["kernel"], + module.taints, + True, + ) + else: + taints = ",".join( + tainting.Tainting.get_taints_parsed( + self.context, + self.config["kernel"], + module.taints, + True, + ) + ) + + yield ( + 0, + ( + module.get_name() or renderers.NotAvailableValue(), + format_hints.Hex(module_offset), + linux_utilities_modules.ModuleGathererLsmod.name in gatherers, + linux_utilities_modules.ModuleGathererSysFs.name in gatherers, + linux_utilities_modules.ModuleGathererScanner.name in gatherers, + taints or renderers.NotAvailableValue(), + ), + ) + + def run(self): + columns = [ + ("Name", str), + ("Address", format_hints.Hex), + ("In procfs", bool), + ("In sysfs", bool), + ("In scan", bool), + ("Taints", str), + ] + + return renderers.TreeGrid( + columns, + self._generator(), + ) diff --git a/volatility3/framework/plugins/linux/modxview.py b/volatility3/framework/plugins/linux/modxview.py index c1707d26f..f710b1291 100644 --- a/volatility3/framework/plugins/linux/modxview.py +++ b/volatility3/framework/plugins/linux/modxview.py @@ -1,181 +1,22 @@ -# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # import logging -from typing import List, Dict, Iterator - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules - -from volatility3.framework import interfaces, deprecation, renderers -from volatility3.framework.configuration import requirements -from volatility3.framework.renderers import format_hints -from volatility3.framework.symbols.linux import extensions -from volatility3.framework.constants import architectures -from volatility3.framework.symbols.linux.utilities import tainting +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import modxview vollog = logging.getLogger(__name__) -class Modxview(interfaces.plugins.PluginInterface): +class Modxview( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=modxview.Modxview, + removal_date="2026-06-07", +): + """Centralize lsmod, check_modules and hidden_modules results to efficiently \ -spot modules presence and taints.""" +spot modules presence and taints (deprecated).""" _version = (1, 0, 0) _required_framework_version = (2, 17, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=architectures.LINUX_ARCHS, - ), - requirements.VersionRequirement( - name="linux_utilities_modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherer_lsmod", - component=linux_utilities_modules.ModuleGathererLsmod, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherer_sysfs", - component=linux_utilities_modules.ModuleGathererSysFs, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherer_scanner", - component=linux_utilities_modules.ModuleGathererScanner, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linux-tainting", component=tainting.Tainting, version=(1, 0, 0) - ), - requirements.BooleanRequirement( - name="plain_taints", - description="Display the plain taints string for each module.", - optional=True, - default=False, - ), - ] - - @classmethod - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.flatten_run_modules_results, - replacement_version=(3, 0, 0), - removal_date="2025-09-25", - ) - def flatten_run_modules_results( - cls, run_results: Dict[str, List[extensions.module]], deduplicate: bool = True - ) -> Iterator[extensions.module]: - """Flatten a dictionary mapping plugin names and modules list, to a single merged list. - This is useful to get a generic lookup list of all the detected modules. - - Args: - run_results: dictionary of plugin names mapping a list of detected modules - deduplicate: remove duplicate modules, based on their offsets - - Returns: - Iterator of modules objects - """ - return linux_utilities_modules.Modules.flatten_run_modules_results( - run_results, deduplicate - ) - - @classmethod - @deprecation.deprecated_method( - replacement=linux_utilities_modules.Modules.run_modules_scanners, - replacement_version=(3, 0, 0), - removal_date="2025-09-25", - ) - def run_modules_scanners( - cls, - context: interfaces.context.ContextInterface, - kernel_name: str, - run_hidden_modules: bool = True, - ) -> Dict[str, List[extensions.module]]: - """Run module scanning plugins and aggregate the results. It is designed - to not operate any inter-plugin results triage.""" - return linux_utilities_modules.Modules.run_modules_scanners( - context, kernel_name, run_hidden_modules - ) - - def _generator(self): - kernel = self.context.modules[self.config["kernel"]] - - wanted_gatherers = [ - linux_utilities_modules.ModuleGathererLsmod, - linux_utilities_modules.ModuleGathererSysFs, - linux_utilities_modules.ModuleGathererScanner, - ] - - run_results = linux_utilities_modules.Modules.run_modules_scanners( - context=self.context, - kernel_module_name=self.config["kernel"], - caller_wanted_gatherers=wanted_gatherers, - flatten=False, - ) - - aggregated_modules = {} - # We want to be explicit on the plugins results we are interested in - for gatherer in wanted_gatherers: - # Iterate over each recovered module - for mod_info in run_results[gatherer.name]: - # Use offsets as unique keys, whether a module - # appears in many plugin runs or not - if aggregated_modules.get(mod_info.offset, None) is not None: - # Append the plugin to the list of originating plugins - aggregated_modules[mod_info.offset].append(gatherer.name) - else: - aggregated_modules[mod_info.offset] = [gatherer.name] - - for module_offset, gatherers in aggregated_modules.items(): - module = kernel.object("module", offset=module_offset, absolute=True) - - # Tainting parsing capabilities applied to the module - if self.config.get("plain_taints"): - taints = tainting.Tainting.get_taints_as_plain_string( - self.context, - self.config["kernel"], - module.taints, - True, - ) - else: - taints = ",".join( - tainting.Tainting.get_taints_parsed( - self.context, - self.config["kernel"], - module.taints, - True, - ) - ) - - yield ( - 0, - ( - module.get_name() or renderers.NotAvailableValue(), - format_hints.Hex(module_offset), - linux_utilities_modules.ModuleGathererLsmod.name in gatherers, - linux_utilities_modules.ModuleGathererSysFs.name in gatherers, - linux_utilities_modules.ModuleGathererScanner.name in gatherers, - taints or renderers.NotAvailableValue(), - ), - ) - - def run(self): - columns = [ - ("Name", str), - ("Address", format_hints.Hex), - ("In procfs", bool), - ("In sysfs", bool), - ("In scan", bool), - ("Taints", str), - ] - - return renderers.TreeGrid( - columns, - self._generator(), - ) From 77801e4cb09ce54ca576bc2ee11ad009d6ce42fa Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Tue, 10 Jun 2025 19:22:12 +0300 Subject: [PATCH 23/25] Plugins: categorize linux.netfilter as a malware plugin --- test/plugins/linux/linux.py | 2 +- .../plugins/linux/malware/netfilter.py | 806 +++++++++++++++++ .../framework/plugins/linux/modxview.py | 1 - .../framework/plugins/linux/netfilter.py | 808 +----------------- 4 files changed, 818 insertions(+), 799 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/netfilter.py diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index e39c1d15d..c7f1df9c6 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -501,7 +501,7 @@ class TestLinuxKmesg: class TestLinuxNetfilter: def test_linux_generic_netfilter(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.netfilter.Netfilter", image, volatility, python + "linux.malware.netfilter.Netfilter", image, volatility, python ) # linux-sample-1.bin has no suspicious results for this plugin. diff --git a/volatility3/framework/plugins/linux/malware/netfilter.py b/volatility3/framework/plugins/linux/malware/netfilter.py new file mode 100644 index 000000000..d724d4296 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/netfilter.py @@ -0,0 +1,806 @@ +# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# +from dataclasses import dataclass, field +from abc import ABC, abstractmethod +import logging + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules +from typing import Iterator, List, Tuple, Optional +from volatility3 import framework +from volatility3.framework import ( + constants, + interfaces, + renderers, + exceptions, + deprecation, +) +from volatility3.framework.renderers import format_hints +from volatility3.framework.configuration import requirements +from volatility3.framework.symbols.linux import network + +vollog = logging.getLogger(__name__) + + +@dataclass +class Proto: + name: str + hooks: Tuple[str] = field(default_factory=tuple) + + +PROTO_NOT_IMPLEMENTED = Proto(name="UNSPEC") + +NF_INET_HOOKS = ("PRE_ROUTING", "LOCAL_IN", "FORWARD", "LOCAL_OUT", "POST_ROUTING") +NF_DEC_HOOKS = ( + "PRE_ROUTING", + "LOCAL_IN", + "FORWARD", + "LOCAL_OUT", + "POST_ROUTING", + "HELLO", + "ROUTE", +) +NF_ARP_HOOKS = ("IN", "OUT", "FORWARD") +NF_NETDEV_HOOKS = ("INGRESS", "EGRESS") +LARGEST_HOOK_NUMBER = max( + len(NF_INET_HOOKS), len(NF_DEC_HOOKS), len(NF_ARP_HOOKS), len(NF_NETDEV_HOOKS) +) + + +class AbstractNetfilter(ABC): + """Netfilter Abstract Base Classes handling details across various + Netfilter implementations, including constants, helpers, and common + routines. + """ + + PROTO_HOOKS = ( + PROTO_NOT_IMPLEMENTED, # NFPROTO_UNSPEC + Proto(name="INET", hooks=NF_INET_HOOKS), # From kernels 3.14 + Proto(name="IPV4", hooks=NF_INET_HOOKS), + Proto(name="ARP", hooks=NF_ARP_HOOKS), + PROTO_NOT_IMPLEMENTED, + Proto(name="NETDEV", hooks=NF_NETDEV_HOOKS), + PROTO_NOT_IMPLEMENTED, + Proto(name="BRIDGE", hooks=NF_INET_HOOKS), + PROTO_NOT_IMPLEMENTED, + PROTO_NOT_IMPLEMENTED, + Proto(name="IPV6", hooks=NF_INET_HOOKS), + PROTO_NOT_IMPLEMENTED, + Proto(name="DECNET", hooks=NF_DEC_HOOKS), # Removed in kernel 6.1 + ) + NF_MAX_HOOKS = LARGEST_HOOK_NUMBER + 1 + + def __init__( + self, context: interfaces.context.ContextInterface, kernel_module_name: str + ): + self._context = context + self.vmlinux = context.modules[kernel_module_name] + self.layer_name = self.vmlinux.layer_name + + # Set data sizes + self.ptr_size = self.vmlinux.get_type("pointer").size + self.list_head_size = self.vmlinux.get_type("list_head").size + + linuxutils_modulegatherers_required_version = ( + Netfilter._required_linuxutils_gatherers_version + ) + linuxutils_modulegatherers_current_version = ( + linux_utilities_modules.ModuleGatherers.version + ) + if not requirements.VersionRequirement.matches_required( + linuxutils_modulegatherers_required_version, + linuxutils_modulegatherers_current_version, + ): + raise exceptions.PluginRequirementException( + f"linux_utilities_modules.ModuleGatherer version not suitable: required {linuxutils_modulegatherers_required_version} found {linuxutils_modulegatherers_current_version}" + ) + + linux_net_required_version = Netfilter._required_linuxnet_version + linux_net_current_version = network.NetSymbols.version + if not requirements.VersionRequirement.matches_required( + linux_net_required_version, linux_net_current_version + ): + raise exceptions.PluginRequirementException( + f"symbols.linux.net.NetSymbols version not suitable: required {linux_net_required_version} found {linux_net_current_version}" + ) + + linux_utilities_modules_required_version = ( + Netfilter._required_linux_utilities_modules_version + ) + linux_utilities_modules_current_version = ( + linux_utilities_modules.Modules.version + ) + if not requirements.VersionRequirement.matches_required( + linux_utilities_modules_required_version, + linux_utilities_modules_current_version, + ): + raise exceptions.PluginRequirementException( + f"linux_utilities_modules.Modules version not suitable: required {linux_utilities_modules_required_version} found {linux_utilities_modules_current_version}" + ) + + symbol_table = context.symbol_space[self.vmlinux.symbol_table_name] + network.NetSymbols.apply(symbol_table) + + self.handlers = linux_utilities_modules.Modules.run_modules_scanners( + context=context, + kernel_module_name=kernel_module_name, + caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, + ) + + @classmethod + def run_all( + cls, context: interfaces.context.ContextInterface, kernel_module_name: str + ) -> Iterator[Tuple[int, str, str, int, int, str, bool]]: + """It calls each subclass symtab_checks() to test the required + conditions to that specific kernel implementation. + + Args: + context: The volatility3 context on which to operate + kernel_module_name: The name of the table containing the kernel symbols + + Yields: + The kmsg records. Same as _run() + """ + vmlinux = context.modules[kernel_module_name] + + implementation_inst = None # type: ignore + for subclass in framework.class_subclasses(cls): + if not subclass.symtab_checks(vmlinux=vmlinux): + vollog.log( + constants.LOGLEVEL_VVVV, + "Netfilter implementation '%s' doesn't match this memory dump", + subclass.__name__, + ) + continue + + vollog.log( + constants.LOGLEVEL_VVVV, + "Netfilter implementation '%s' matches!", + subclass.__name__, + ) + implementation_inst = subclass( + context=context, kernel_module_name=kernel_module_name + ) + # More than one class could be executed for an specific kernel version + # For instance: Netfilter Ingress hooks + yield from implementation_inst._run() + + if implementation_inst is None: + vollog.error("Unsupported Netfilter kernel implementation") + + def _run(self) -> Iterator[Tuple[int, str, str, int, int, str, bool]]: + """Iterates over namespaces and protocols, executing various callbacks that + allow customization of the code to the specific data structure used in a + particular kernel implementation + + get_hooks_container(net, proto_name, hook_name) + It returns the data structure used in a specific kernel implementation + to store the hooks for a respective namespace and protocol, basically: + For Ingress hooks: + network_namespace[] -> net_device[] -> nf_hooks_ingress[] + For egress hooks: + network_namespace[] -> net_device[] -> nf_hooks_egress[] + For all the other Netfilter hooks: + <= 4.2.8 + nf_hooks[] + >= 4.3 + network_namespace[] -> nf.hooks[] + + get_hook_ops(hook_container, proto_idx, hook_idx) + Give the 'hook_container' got in get_hooks_container(), it + returns an iterable of 'nf_hook_ops' elements for a respective protocol + and hook type. + + Returns: + netns [int]: Network namespace id + proto_name [str]: Protocol name + hook_name [str]: Hook name + priority [int]: Priority + hook_ops_hook [int]: Hook address + module_name [str]: Linux kernel module name + hooked [bool]: "True" if the network stack has been hijacked + """ + for netns, net in self.get_net_namespaces(): + for proto_idx, proto_name, hook_idx, hook_name in self._proto_hook_loop(): + hooks_container = self.get_hooks_container(net, proto_name, hook_name) + + for hook_container in hooks_container: + for hook_ops in self.get_hook_ops( + hook_container, proto_idx, hook_idx + ): + if not hook_ops: + continue + + priority = int(hook_ops.priority) + hook_ops_hook = hook_ops.hook + module_info, symbol_name = ( + linux_utilities_modules.Modules.module_lookup_by_address( + self._context, + self.vmlinux.name, + self.handlers, + hook_ops_hook, + ) + ) + hooked = module_info is None + + yield netns, proto_name, hook_name, priority, hook_ops_hook, module_info, symbol_name, hooked + + @classmethod + @abstractmethod + def symtab_checks(cls, vmlinux: interfaces.context.ModuleInterface) -> bool: + """This method on each sublasss will be called to evaluate if the kernel + being analyzed fulfill the type & symbols requirements for the implementation. + The first class returning True will be instantiated and called via the + run() method. + + Returns: + bool: True if the kernel being analyzed fulfill the class requirements. + """ + + def _proto_hook_loop(self) -> Iterator[Tuple[int, str, int, str]]: + """Flattens the protocol families and hooks""" + for proto_idx, proto in enumerate(AbstractNetfilter.PROTO_HOOKS): + if proto == PROTO_NOT_IMPLEMENTED: + continue + if proto.name not in self.subscribed_protocols(): + # This protocol is not managed in this object + continue + for hook_idx, hook_name in enumerate(proto.hooks): + yield proto_idx, proto.name, hook_idx, hook_name + + def build_nf_hook_ops_array( + self, nf_hook_entries + ) -> Optional[interfaces.objects.ObjectInterface]: + """Function helper to build the nf_hook_ops array when it is not part of the + struct 'nf_hook_entries' definition. + + nf_hook_ops was stored adjacent in memory to the nf_hook_entry array, in the + new struct 'nf_hook_entries'. However, this 'nf_hooks_ops' array 'orig_ops' is + not part of the 'nf_hook_entries' struct. So, we need to calculate the offset. + + struct nf_hook_entries { + u16 num_hook_entries; /* plus padding */ + struct nf_hook_entry hooks[]; + //const struct nf_hook_ops *orig_ops[]; + } + """ + nf_hook_entry_size = self.vmlinux.get_type("nf_hook_entry").size + + try: + num_hook_entries = nf_hook_entries.num_hook_entries + except exceptions.InvalidAddressException: + return None + + orig_ops_addr = ( + nf_hook_entries.hooks.vol.offset + nf_hook_entry_size * num_hook_entries + ) + + if not self.vmlinux._context.layers[self.vmlinux.layer_name].is_valid( + orig_ops_addr + ): + return None + + orig_ops = self._context.object( + object_type=self.get_symbol_fullname("array"), + offset=orig_ops_addr, + subtype=self.vmlinux.get_type("pointer"), + layer_name=self.layer_name, + count=num_hook_entries, + ) + + return orig_ops + + def subscribed_protocols(self) -> Tuple[str]: + """Allows to select which PROTO_HOOKS protocols will be processed by the + Netfiler subclass. + """ + + # Most implementation handlers respond to these protocols, except for + # the ingress hook, which specifically handles the 'NETDEV' protocol. + # However, there is no corresponding Netfilter hook implementation for + # the INET protocol in the kernel. AFAIU, this is used as + # 'NFPROTO_INET = NFPROTO_IPV4 || NFPROTO_IPV6' + # in other parts of the kernel source code. + return ("IPV4", "ARP", "BRIDGE", "IPV6", "DECNET") + + @deprecation.method_being_removed( + removal_date="2025-09-25", + message="Callers to this method should adapt `linux_utilities_modules.Modules.run_module_scanners`", + ) + def get_module_name_for_address(self, addr) -> str: + """Helper to obtain the module and symbol name in the format needed for the + output of this plugin. + """ + module_name, symbol_name = ( + linux_utilities_modules.Modules.lookup_module_address( + self._context, self.vmlinux.name, self.handlers, addr + ) + ) + + if module_name == "UNKNOWN": + module_name = None + + if symbol_name != "N/A": + module_name = f"[{symbol_name}]" + + return module_name + + def get_net_namespaces(self): + """Common function to retrieve the different namespaces. + From 4.3 on, all the implementations use network namespaces. + """ + nethead = self.vmlinux.object_from_symbol("net_namespace_list") + symbol_net_name = self.get_symbol_fullname("net") + for net in nethead.to_list(symbol_net_name, "list"): + net_ns_id = net.ns.inum + yield net_ns_id, net + + def get_hooks_container(self, net, proto_name, hook_name): + """Returns the data structure used in a specific kernel implementation to store + the hooks for a respective namespace and protocol. + + Except for kernels < 4.3, all the implementations use network namespaces. + Also the data structure which contains the hooks, even though it changes its + implementation and/or data type, it is always in this location. + """ + yield net.nf.hooks + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + """Given the hook_container obtained from get_hooks_container(), it + returns an iterable of 'nf_hook_ops' elements for a corresponding protocol + and hook type. + + This is the most variable/unstable part of all Netfilter hook designs, it + changes almost in every single implementation. + """ + raise NotImplementedError("You must implement this method") + + def get_symbol_fullname(self, symbol_basename: str) -> str: + """Given a short symbol or type name, it returns its full name""" + return self.vmlinux.symbol_table_name + constants.BANG + symbol_basename + + @staticmethod + def get_member_type( + vol_type: interfaces.objects.Template, member_name: str + ) -> List[str]: + """Returns a list of types/subtypes belonging to the given type member. + + Args: + vol_type (interfaces.objects.Template): A vol3 type object + member_name (str): The member name + + Returns: + list: A list of types/subtypes + """ + _size, vol_obj = vol_type.vol.members[member_name] + type_name = vol_obj.type_name + type_basename = type_name.split(constants.BANG)[1] + member_type = [type_basename] + cur_type = vol_obj + while hasattr(cur_type, "subtype"): + subtype_name = cur_type.subtype.type_name + subtype_basename = subtype_name.split(constants.BANG)[1] + member_type.append(subtype_basename) + cur_type = cur_type.subtype + + return member_type + + +class NetfilterImp_to_4_3(AbstractNetfilter): + """At this point, Netfilter hooks were implemented as a linked list of struct + 'nf_hook_ops' type. One linked list per protocol per hook type. + It was like that until 4.2.8. + + struct list_head nf_hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + return vmlinux.has_symbol("nf_hooks") + + def get_net_namespaces(self): + # In kernels <= 4.2.8 netfilter hooks are not implemented per namespaces + netns, net = renderers.NotAvailableValue(), renderers.NotAvailableValue() + yield netns, net + + def get_hooks_container(self, net, proto_name, hook_name): + nf_hooks = self.vmlinux.object_from_symbol("nf_hooks") + if not nf_hooks: + return + + yield nf_hooks + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + list_head = hook_container[proto_idx][hook_idx] + nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") + return list_head.to_list(nf_hooks_ops_name, "list") + + +class NetfilterImp_4_3_to_4_9(AbstractNetfilter): + """Netfilter hooks were added to network namespaces in 4.3. + It is still implemented as a linked list of 'struct nf_hook_ops' type but inside a + network namespace. One linked list per protocol per hook type. + + struct net { ... struct netns_nf nf; ... } + struct netns_nf { ... + struct list_head hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("netns_nf") + and vmlinux.get_type("netns_nf").has_member("hooks") + and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") + == ["array", "array", "list_head"] + ) + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + list_head = hook_container[proto_idx][hook_idx] + nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") + return list_head.to_list(nf_hooks_ops_name, "list") + + +class NetfilterImp_4_9_to_4_14(AbstractNetfilter): + """In this range of kernel versions, the doubly-linked lists of netfilter hooks were + replaced by an array of arrays of 'nf_hook_entry' pointers in a singly-linked lists. + struct net { ... struct netns_nf nf; ... } + struct netns_nf { .. + struct nf_hook_entry __rcu *hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } + + Also in v4.10 the struct nf_hook_entry changed, a hook function pointer was added to + it. However, for simplicity of this design, we will still take the hook address from + the 'nf_hook_ops'. As per v5.0-rc2, the hook address is duplicated in both sides. + - v4.9: + struct nf_hook_entry { + struct nf_hook_entry *next; + struct nf_hook_ops ops; + const struct nf_hook_ops *orig_ops; }; + - v4.10: + struct nf_hook_entry { + struct nf_hook_entry *next; + nf_hookfn *hook; + void *priv; + const struct nf_hook_ops *orig_ops; }; + (*) Even though the hook address is in the struct 'nf_hook_entry', we use the + original 'nf_hook_ops' hook address value, the one which was filled by the user, to + make it uniform to all the implementations. + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + hooks_type = ["array", "array", "pointer", "nf_hook_entry"] + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("netns_nf") + and vmlinux.get_type("netns_nf").has_member("hooks") + and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") == hooks_type + ) + + def _get_hook_ops(self, hook_container, proto_idx, hook_idx): + list_head = hook_container[proto_idx][hook_idx] + nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") + return list_head.to_list(nf_hooks_ops_name, "list") + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + nf_hook_entry_list = hook_container[proto_idx][hook_idx] + while nf_hook_entry_list: + yield nf_hook_entry_list.orig_ops + nf_hook_entry_list = nf_hook_entry_list.next + + +class NetfilterImp_4_14_to_4_16(AbstractNetfilter): + """'nf_hook_ops' was removed from struct 'nf_hook_entry'. Instead, it was stored + adjacent in memory to the 'nf_hook_entry' array, in the new struct 'nf_hook_entries' + However, 'orig_ops' is not part of the 'nf_hook_entries' struct definition. So, we + have to craft it by hand. + + struct net { ... struct netns_nf nf; ... } + struct netns_nf { + struct nf_hook_entries *hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } + struct nf_hook_entries { + u16 num_hook_entries; /* plus padding */ + struct nf_hook_entry hooks[]; + //const struct nf_hook_ops *orig_ops[]; } + struct nf_hook_entry { + nf_hookfn *hook; + void *priv; } + + (*) Even though the hook address is in the struct 'nf_hook_entry', we use the + original 'nf_hook_ops' hook address value, the one which was filled by the user, to + make it uniform to all the implementations. + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + hooks_type = ["array", "array", "pointer", "nf_hook_entries"] + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("netns_nf") + and vmlinux.get_type("netns_nf").has_member("hooks") + and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") == hooks_type + ) + + def get_nf_hook_entries(self, nf_hooks_addr, proto_idx, hook_idx): + """This allows to support different hook array implementations from this version + on. For instance, in kernels >= 4.16 this multi-dimensional array is split in + one-dimensional array of pointers to 'nf_hooks_entries' per each protocol.""" + return nf_hooks_addr[proto_idx][hook_idx] + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + nf_hook_entries = self.get_nf_hook_entries(hook_container, proto_idx, hook_idx) + if not nf_hook_entries: + return + + nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") + nf_hook_ops_ptr_arr = self.build_nf_hook_ops_array(nf_hook_entries) + if not nf_hook_ops_ptr_arr: + return + + for nf_hook_ops_ptr in nf_hook_ops_ptr_arr: + nf_hook_ops = nf_hook_ops_ptr.dereference().cast(nf_hook_ops_name) + yield nf_hook_ops + + +class NetfilterImp_4_16_to_latest(NetfilterImp_4_14_to_4_16): + """The multidimensional array of nf_hook_entries was split in a one-dimensional + array per each protocol. + + struct net { + struct netns_nf nf; ... } + struct netns_nf { + struct nf_hook_entries * hooks_ipv4[NF_INET_NUMHOOKS]; + struct nf_hook_entries * hooks_ipv6[NF_INET_NUMHOOKS]; + struct nf_hook_entries * hooks_arp[NF_ARP_NUMHOOKS]; + struct nf_hook_entries * hooks_bridge[NF_INET_NUMHOOKS]; + struct nf_hook_entries * hooks_decnet[NF_DN_NUMHOOKS]; ... } + struct nf_hook_entries { + u16 num_hook_entries; /* plus padding */ + struct nf_hook_entry hooks[]; + //const struct nf_hook_ops *orig_ops[]; } + struct nf_hook_entry { + nf_hookfn *hook; + void *priv; } + + (*) Even though the hook address is in the struct nf_hook_entry, we use the original + nf_hook_ops hook address value, the one which was filled by the user, to make it + uniform to all the implementations. + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("netns_nf") + and vmlinux.get_type("netns_nf").has_member("hooks_ipv4") + ) + + def get_hooks_container(self, net, proto_name, hook_name): + try: + if proto_name == "IPV4": + net_nf_hooks = net.nf.hooks_ipv4 + elif proto_name == "ARP": + net_nf_hooks = net.nf.hooks_arp + elif proto_name == "BRIDGE": + net_nf_hooks = net.nf.hooks_bridge + elif proto_name == "IPV6": + net_nf_hooks = net.nf.hooks_ipv6 + elif proto_name == "DECNET": + net_nf_hooks = net.nf.hooks_decnet + else: + return + + yield net_nf_hooks + + except AttributeError: + # Protocol family disabled at kernel compilation + # CONFIG_NETFILTER_FAMILY_ARP=n || + # CONFIG_NETFILTER_FAMILY_BRIDGE=n || + # CONFIG_DECNET=n + pass + + def _get_nf_hook_entries_ptr(self, nf_hooks_addr, proto_idx, hook_idx): + nf_hook_entries_ptr = nf_hooks_addr[hook_idx] + return nf_hook_entries_ptr + + def get_nf_hook_entries(self, nf_hooks_addr, proto_idx, hook_idx): + return nf_hooks_addr[hook_idx] + + +class AbstractNetfilterNetDev(AbstractNetfilter): + """Base class to handle the Netfilter NetDev hooks. + It won't be executed. It has some common functions to all Netfilter NetDev hook + implementations. + + Netfilter NetDev hooks are set per network device which belongs to a network + namespace. + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + return False + + def subscribed_protocols(self): + return ("NETDEV",) + + def get_hooks_container(self, net, proto_name, hook_name): + net_device_type = self.vmlinux.get_type("net_device") + net_device_name = self.get_symbol_fullname("net_device") + for net_device in net.dev_base_head.to_list(net_device_name, "dev_list"): + if hook_name == "INGRESS": + if net_device_type.has_member("nf_hooks_ingress"): + # CONFIG_NETFILTER_INGRESS=y + yield net_device.nf_hooks_ingress + + elif hook_name == "EGRESS": + if net_device_type.has_member("nf_hooks_egress"): + # CONFIG_NETFILTER_EGRESS=y + yield net_device.nf_hooks_egress + + +class NetfilterNetDevImp_4_2_to_4_9(AbstractNetfilterNetDev): + """This is the first version of Netfilter Ingress hooks which was implemented using + a doubly-linked list of 'nf_hook_ops'. + struct list_head nf_hooks_ingress; + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + hooks_type = ["list_head"] + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("net_device") + and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") + and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") + == hooks_type + ) + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + nf_hooks_ingress = hook_container + nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") + return nf_hooks_ingress.to_list(nf_hook_ops_name, "list") + + +class NetfilterNetDevImp_4_9_to_4_14(AbstractNetfilterNetDev): + """In 4.9 it was changed to a simple singly-linked list. + struct nf_hook_entry * nf_hooks_ingress; + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + hooks_type = ["pointer", "nf_hook_entry"] + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("net_device") + and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") + and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") + == hooks_type + ) + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + nf_hooks_ingress_ptr = hook_container + if not nf_hooks_ingress_ptr: + return + + while nf_hooks_ingress_ptr: + nf_hook_entry = nf_hooks_ingress_ptr.dereference() + orig_ops = nf_hook_entry.orig_ops.dereference() + yield orig_ops + nf_hooks_ingress_ptr = nf_hooks_ingress_ptr.next + + +class NetfilterNetDevImp_4_14_to_latest(AbstractNetfilterNetDev): + """In 4.14 the hook list was converted to an array of pointers inside the struct + 'nf_hook_entries': + struct nf_hook_entries * nf_hooks_ingress; + struct nf_hook_entries { + u16 num_hook_entries; + struct nf_hook_entry hooks[]; + //const struct nf_hook_ops *orig_ops[]; } + """ + + @classmethod + def symtab_checks(cls, vmlinux) -> bool: + hooks_type = ["pointer", "nf_hook_entries"] + return ( + vmlinux.has_symbol("net_namespace_list") + and vmlinux.has_type("net_device") + and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") + and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") + == hooks_type + ) + + def get_hook_ops(self, hook_container, proto_idx, hook_idx): + nf_hook_entries = hook_container + if not nf_hook_entries: + return + + nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") + nf_hook_ops_ptr_arr = self.build_nf_hook_ops_array(nf_hook_entries) + if not nf_hook_ops_ptr_arr: + return + + for nf_hook_ops_ptr in nf_hook_ops_ptr_arr: + nf_hook_ops = nf_hook_ops_ptr.dereference().cast(nf_hook_ops_name) + yield nf_hook_ops + + +class Netfilter(interfaces.plugins.PluginInterface): + """Lists Netfilter hooks.""" + + _required_framework_version = (2, 22, 0) + + _version = (2, 0, 0) + + _required_linux_utilities_modules_version = (3, 0, 0) + _required_linuxutils_gatherers_version = (1, 0, 0) + _required_linuxnet_version = (1, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherers", + component=linux_utilities_modules.ModuleGatherers, + version=cls._required_linuxutils_gatherers_version, + ), + requirements.VersionRequirement( + name="linuxnet", + component=network.NetSymbols, + version=cls._required_linuxnet_version, + ), + ] + + def _format_fields(self, fields): + ( + netns, + proto_name, + hook_name, + priority, + hook_func, + module_info, + symbol_name, + hooked, + ) = fields + + if module_info: + module_name = module_info.name + else: + module_name = renderers.NotAvailableValue() + + return ( + netns, + proto_name, + hook_name, + priority, + format_hints.Hex(hook_func), + module_name, + symbol_name or renderers.NotAvailableValue(), + str(hooked), + ) + + def _generator(self): + kernel_module_name = self.config["kernel"] + for fields in AbstractNetfilter.run_all( + context=self.context, kernel_module_name=kernel_module_name + ): + yield (0, self._format_fields(fields)) + + def run(self): + headers = [ + ("Net NS", int), + ("Proto", str), + ("Hook", str), + ("Priority", int), + ("Handler", format_hints.Hex), + ("Module", str), + ("Symbol", str), + ("Is Hooked", str), + ] + return renderers.TreeGrid(headers, self._generator()) diff --git a/volatility3/framework/plugins/linux/modxview.py b/volatility3/framework/plugins/linux/modxview.py index f710b1291..d91f37587 100644 --- a/volatility3/framework/plugins/linux/modxview.py +++ b/volatility3/framework/plugins/linux/modxview.py @@ -14,7 +14,6 @@ class Modxview( replacement_class=modxview.Modxview, removal_date="2026-06-07", ): - """Centralize lsmod, check_modules and hidden_modules results to efficiently \ spot modules presence and taints (deprecated).""" diff --git a/volatility3/framework/plugins/linux/netfilter.py b/volatility3/framework/plugins/linux/netfilter.py index d724d4296..741241039 100644 --- a/volatility3/framework/plugins/linux/netfilter.py +++ b/volatility3/framework/plugins/linux/netfilter.py @@ -1,806 +1,20 @@ -# This file is Copyright 2024 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # -from dataclasses import dataclass, field -from abc import ABC, abstractmethod import logging - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules -from typing import Iterator, List, Tuple, Optional -from volatility3 import framework -from volatility3.framework import ( - constants, - interfaces, - renderers, - exceptions, - deprecation, -) -from volatility3.framework.renderers import format_hints -from volatility3.framework.configuration import requirements -from volatility3.framework.symbols.linux import network +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import netfilter vollog = logging.getLogger(__name__) -@dataclass -class Proto: - name: str - hooks: Tuple[str] = field(default_factory=tuple) - - -PROTO_NOT_IMPLEMENTED = Proto(name="UNSPEC") - -NF_INET_HOOKS = ("PRE_ROUTING", "LOCAL_IN", "FORWARD", "LOCAL_OUT", "POST_ROUTING") -NF_DEC_HOOKS = ( - "PRE_ROUTING", - "LOCAL_IN", - "FORWARD", - "LOCAL_OUT", - "POST_ROUTING", - "HELLO", - "ROUTE", -) -NF_ARP_HOOKS = ("IN", "OUT", "FORWARD") -NF_NETDEV_HOOKS = ("INGRESS", "EGRESS") -LARGEST_HOOK_NUMBER = max( - len(NF_INET_HOOKS), len(NF_DEC_HOOKS), len(NF_ARP_HOOKS), len(NF_NETDEV_HOOKS) -) - - -class AbstractNetfilter(ABC): - """Netfilter Abstract Base Classes handling details across various - Netfilter implementations, including constants, helpers, and common - routines. - """ - - PROTO_HOOKS = ( - PROTO_NOT_IMPLEMENTED, # NFPROTO_UNSPEC - Proto(name="INET", hooks=NF_INET_HOOKS), # From kernels 3.14 - Proto(name="IPV4", hooks=NF_INET_HOOKS), - Proto(name="ARP", hooks=NF_ARP_HOOKS), - PROTO_NOT_IMPLEMENTED, - Proto(name="NETDEV", hooks=NF_NETDEV_HOOKS), - PROTO_NOT_IMPLEMENTED, - Proto(name="BRIDGE", hooks=NF_INET_HOOKS), - PROTO_NOT_IMPLEMENTED, - PROTO_NOT_IMPLEMENTED, - Proto(name="IPV6", hooks=NF_INET_HOOKS), - PROTO_NOT_IMPLEMENTED, - Proto(name="DECNET", hooks=NF_DEC_HOOKS), # Removed in kernel 6.1 - ) - NF_MAX_HOOKS = LARGEST_HOOK_NUMBER + 1 - - def __init__( - self, context: interfaces.context.ContextInterface, kernel_module_name: str - ): - self._context = context - self.vmlinux = context.modules[kernel_module_name] - self.layer_name = self.vmlinux.layer_name - - # Set data sizes - self.ptr_size = self.vmlinux.get_type("pointer").size - self.list_head_size = self.vmlinux.get_type("list_head").size - - linuxutils_modulegatherers_required_version = ( - Netfilter._required_linuxutils_gatherers_version - ) - linuxutils_modulegatherers_current_version = ( - linux_utilities_modules.ModuleGatherers.version - ) - if not requirements.VersionRequirement.matches_required( - linuxutils_modulegatherers_required_version, - linuxutils_modulegatherers_current_version, - ): - raise exceptions.PluginRequirementException( - f"linux_utilities_modules.ModuleGatherer version not suitable: required {linuxutils_modulegatherers_required_version} found {linuxutils_modulegatherers_current_version}" - ) - - linux_net_required_version = Netfilter._required_linuxnet_version - linux_net_current_version = network.NetSymbols.version - if not requirements.VersionRequirement.matches_required( - linux_net_required_version, linux_net_current_version - ): - raise exceptions.PluginRequirementException( - f"symbols.linux.net.NetSymbols version not suitable: required {linux_net_required_version} found {linux_net_current_version}" - ) - - linux_utilities_modules_required_version = ( - Netfilter._required_linux_utilities_modules_version - ) - linux_utilities_modules_current_version = ( - linux_utilities_modules.Modules.version - ) - if not requirements.VersionRequirement.matches_required( - linux_utilities_modules_required_version, - linux_utilities_modules_current_version, - ): - raise exceptions.PluginRequirementException( - f"linux_utilities_modules.Modules version not suitable: required {linux_utilities_modules_required_version} found {linux_utilities_modules_current_version}" - ) - - symbol_table = context.symbol_space[self.vmlinux.symbol_table_name] - network.NetSymbols.apply(symbol_table) - - self.handlers = linux_utilities_modules.Modules.run_modules_scanners( - context=context, - kernel_module_name=kernel_module_name, - caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, - ) - - @classmethod - def run_all( - cls, context: interfaces.context.ContextInterface, kernel_module_name: str - ) -> Iterator[Tuple[int, str, str, int, int, str, bool]]: - """It calls each subclass symtab_checks() to test the required - conditions to that specific kernel implementation. - - Args: - context: The volatility3 context on which to operate - kernel_module_name: The name of the table containing the kernel symbols - - Yields: - The kmsg records. Same as _run() - """ - vmlinux = context.modules[kernel_module_name] - - implementation_inst = None # type: ignore - for subclass in framework.class_subclasses(cls): - if not subclass.symtab_checks(vmlinux=vmlinux): - vollog.log( - constants.LOGLEVEL_VVVV, - "Netfilter implementation '%s' doesn't match this memory dump", - subclass.__name__, - ) - continue - - vollog.log( - constants.LOGLEVEL_VVVV, - "Netfilter implementation '%s' matches!", - subclass.__name__, - ) - implementation_inst = subclass( - context=context, kernel_module_name=kernel_module_name - ) - # More than one class could be executed for an specific kernel version - # For instance: Netfilter Ingress hooks - yield from implementation_inst._run() - - if implementation_inst is None: - vollog.error("Unsupported Netfilter kernel implementation") - - def _run(self) -> Iterator[Tuple[int, str, str, int, int, str, bool]]: - """Iterates over namespaces and protocols, executing various callbacks that - allow customization of the code to the specific data structure used in a - particular kernel implementation - - get_hooks_container(net, proto_name, hook_name) - It returns the data structure used in a specific kernel implementation - to store the hooks for a respective namespace and protocol, basically: - For Ingress hooks: - network_namespace[] -> net_device[] -> nf_hooks_ingress[] - For egress hooks: - network_namespace[] -> net_device[] -> nf_hooks_egress[] - For all the other Netfilter hooks: - <= 4.2.8 - nf_hooks[] - >= 4.3 - network_namespace[] -> nf.hooks[] - - get_hook_ops(hook_container, proto_idx, hook_idx) - Give the 'hook_container' got in get_hooks_container(), it - returns an iterable of 'nf_hook_ops' elements for a respective protocol - and hook type. - - Returns: - netns [int]: Network namespace id - proto_name [str]: Protocol name - hook_name [str]: Hook name - priority [int]: Priority - hook_ops_hook [int]: Hook address - module_name [str]: Linux kernel module name - hooked [bool]: "True" if the network stack has been hijacked - """ - for netns, net in self.get_net_namespaces(): - for proto_idx, proto_name, hook_idx, hook_name in self._proto_hook_loop(): - hooks_container = self.get_hooks_container(net, proto_name, hook_name) - - for hook_container in hooks_container: - for hook_ops in self.get_hook_ops( - hook_container, proto_idx, hook_idx - ): - if not hook_ops: - continue - - priority = int(hook_ops.priority) - hook_ops_hook = hook_ops.hook - module_info, symbol_name = ( - linux_utilities_modules.Modules.module_lookup_by_address( - self._context, - self.vmlinux.name, - self.handlers, - hook_ops_hook, - ) - ) - hooked = module_info is None - - yield netns, proto_name, hook_name, priority, hook_ops_hook, module_info, symbol_name, hooked - - @classmethod - @abstractmethod - def symtab_checks(cls, vmlinux: interfaces.context.ModuleInterface) -> bool: - """This method on each sublasss will be called to evaluate if the kernel - being analyzed fulfill the type & symbols requirements for the implementation. - The first class returning True will be instantiated and called via the - run() method. - - Returns: - bool: True if the kernel being analyzed fulfill the class requirements. - """ - - def _proto_hook_loop(self) -> Iterator[Tuple[int, str, int, str]]: - """Flattens the protocol families and hooks""" - for proto_idx, proto in enumerate(AbstractNetfilter.PROTO_HOOKS): - if proto == PROTO_NOT_IMPLEMENTED: - continue - if proto.name not in self.subscribed_protocols(): - # This protocol is not managed in this object - continue - for hook_idx, hook_name in enumerate(proto.hooks): - yield proto_idx, proto.name, hook_idx, hook_name - - def build_nf_hook_ops_array( - self, nf_hook_entries - ) -> Optional[interfaces.objects.ObjectInterface]: - """Function helper to build the nf_hook_ops array when it is not part of the - struct 'nf_hook_entries' definition. - - nf_hook_ops was stored adjacent in memory to the nf_hook_entry array, in the - new struct 'nf_hook_entries'. However, this 'nf_hooks_ops' array 'orig_ops' is - not part of the 'nf_hook_entries' struct. So, we need to calculate the offset. - - struct nf_hook_entries { - u16 num_hook_entries; /* plus padding */ - struct nf_hook_entry hooks[]; - //const struct nf_hook_ops *orig_ops[]; - } - """ - nf_hook_entry_size = self.vmlinux.get_type("nf_hook_entry").size - - try: - num_hook_entries = nf_hook_entries.num_hook_entries - except exceptions.InvalidAddressException: - return None - - orig_ops_addr = ( - nf_hook_entries.hooks.vol.offset + nf_hook_entry_size * num_hook_entries - ) - - if not self.vmlinux._context.layers[self.vmlinux.layer_name].is_valid( - orig_ops_addr - ): - return None - - orig_ops = self._context.object( - object_type=self.get_symbol_fullname("array"), - offset=orig_ops_addr, - subtype=self.vmlinux.get_type("pointer"), - layer_name=self.layer_name, - count=num_hook_entries, - ) - - return orig_ops - - def subscribed_protocols(self) -> Tuple[str]: - """Allows to select which PROTO_HOOKS protocols will be processed by the - Netfiler subclass. - """ - - # Most implementation handlers respond to these protocols, except for - # the ingress hook, which specifically handles the 'NETDEV' protocol. - # However, there is no corresponding Netfilter hook implementation for - # the INET protocol in the kernel. AFAIU, this is used as - # 'NFPROTO_INET = NFPROTO_IPV4 || NFPROTO_IPV6' - # in other parts of the kernel source code. - return ("IPV4", "ARP", "BRIDGE", "IPV6", "DECNET") - - @deprecation.method_being_removed( - removal_date="2025-09-25", - message="Callers to this method should adapt `linux_utilities_modules.Modules.run_module_scanners`", - ) - def get_module_name_for_address(self, addr) -> str: - """Helper to obtain the module and symbol name in the format needed for the - output of this plugin. - """ - module_name, symbol_name = ( - linux_utilities_modules.Modules.lookup_module_address( - self._context, self.vmlinux.name, self.handlers, addr - ) - ) - - if module_name == "UNKNOWN": - module_name = None - - if symbol_name != "N/A": - module_name = f"[{symbol_name}]" - - return module_name - - def get_net_namespaces(self): - """Common function to retrieve the different namespaces. - From 4.3 on, all the implementations use network namespaces. - """ - nethead = self.vmlinux.object_from_symbol("net_namespace_list") - symbol_net_name = self.get_symbol_fullname("net") - for net in nethead.to_list(symbol_net_name, "list"): - net_ns_id = net.ns.inum - yield net_ns_id, net - - def get_hooks_container(self, net, proto_name, hook_name): - """Returns the data structure used in a specific kernel implementation to store - the hooks for a respective namespace and protocol. - - Except for kernels < 4.3, all the implementations use network namespaces. - Also the data structure which contains the hooks, even though it changes its - implementation and/or data type, it is always in this location. - """ - yield net.nf.hooks - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - """Given the hook_container obtained from get_hooks_container(), it - returns an iterable of 'nf_hook_ops' elements for a corresponding protocol - and hook type. - - This is the most variable/unstable part of all Netfilter hook designs, it - changes almost in every single implementation. - """ - raise NotImplementedError("You must implement this method") - - def get_symbol_fullname(self, symbol_basename: str) -> str: - """Given a short symbol or type name, it returns its full name""" - return self.vmlinux.symbol_table_name + constants.BANG + symbol_basename - - @staticmethod - def get_member_type( - vol_type: interfaces.objects.Template, member_name: str - ) -> List[str]: - """Returns a list of types/subtypes belonging to the given type member. - - Args: - vol_type (interfaces.objects.Template): A vol3 type object - member_name (str): The member name - - Returns: - list: A list of types/subtypes - """ - _size, vol_obj = vol_type.vol.members[member_name] - type_name = vol_obj.type_name - type_basename = type_name.split(constants.BANG)[1] - member_type = [type_basename] - cur_type = vol_obj - while hasattr(cur_type, "subtype"): - subtype_name = cur_type.subtype.type_name - subtype_basename = subtype_name.split(constants.BANG)[1] - member_type.append(subtype_basename) - cur_type = cur_type.subtype - - return member_type - - -class NetfilterImp_to_4_3(AbstractNetfilter): - """At this point, Netfilter hooks were implemented as a linked list of struct - 'nf_hook_ops' type. One linked list per protocol per hook type. - It was like that until 4.2.8. - - struct list_head nf_hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - return vmlinux.has_symbol("nf_hooks") - - def get_net_namespaces(self): - # In kernels <= 4.2.8 netfilter hooks are not implemented per namespaces - netns, net = renderers.NotAvailableValue(), renderers.NotAvailableValue() - yield netns, net - - def get_hooks_container(self, net, proto_name, hook_name): - nf_hooks = self.vmlinux.object_from_symbol("nf_hooks") - if not nf_hooks: - return - - yield nf_hooks - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - list_head = hook_container[proto_idx][hook_idx] - nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") - return list_head.to_list(nf_hooks_ops_name, "list") - - -class NetfilterImp_4_3_to_4_9(AbstractNetfilter): - """Netfilter hooks were added to network namespaces in 4.3. - It is still implemented as a linked list of 'struct nf_hook_ops' type but inside a - network namespace. One linked list per protocol per hook type. - - struct net { ... struct netns_nf nf; ... } - struct netns_nf { ... - struct list_head hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("netns_nf") - and vmlinux.get_type("netns_nf").has_member("hooks") - and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") - == ["array", "array", "list_head"] - ) - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - list_head = hook_container[proto_idx][hook_idx] - nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") - return list_head.to_list(nf_hooks_ops_name, "list") - - -class NetfilterImp_4_9_to_4_14(AbstractNetfilter): - """In this range of kernel versions, the doubly-linked lists of netfilter hooks were - replaced by an array of arrays of 'nf_hook_entry' pointers in a singly-linked lists. - struct net { ... struct netns_nf nf; ... } - struct netns_nf { .. - struct nf_hook_entry __rcu *hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } - - Also in v4.10 the struct nf_hook_entry changed, a hook function pointer was added to - it. However, for simplicity of this design, we will still take the hook address from - the 'nf_hook_ops'. As per v5.0-rc2, the hook address is duplicated in both sides. - - v4.9: - struct nf_hook_entry { - struct nf_hook_entry *next; - struct nf_hook_ops ops; - const struct nf_hook_ops *orig_ops; }; - - v4.10: - struct nf_hook_entry { - struct nf_hook_entry *next; - nf_hookfn *hook; - void *priv; - const struct nf_hook_ops *orig_ops; }; - (*) Even though the hook address is in the struct 'nf_hook_entry', we use the - original 'nf_hook_ops' hook address value, the one which was filled by the user, to - make it uniform to all the implementations. - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - hooks_type = ["array", "array", "pointer", "nf_hook_entry"] - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("netns_nf") - and vmlinux.get_type("netns_nf").has_member("hooks") - and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") == hooks_type - ) - - def _get_hook_ops(self, hook_container, proto_idx, hook_idx): - list_head = hook_container[proto_idx][hook_idx] - nf_hooks_ops_name = self.get_symbol_fullname("nf_hook_ops") - return list_head.to_list(nf_hooks_ops_name, "list") - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - nf_hook_entry_list = hook_container[proto_idx][hook_idx] - while nf_hook_entry_list: - yield nf_hook_entry_list.orig_ops - nf_hook_entry_list = nf_hook_entry_list.next - - -class NetfilterImp_4_14_to_4_16(AbstractNetfilter): - """'nf_hook_ops' was removed from struct 'nf_hook_entry'. Instead, it was stored - adjacent in memory to the 'nf_hook_entry' array, in the new struct 'nf_hook_entries' - However, 'orig_ops' is not part of the 'nf_hook_entries' struct definition. So, we - have to craft it by hand. - - struct net { ... struct netns_nf nf; ... } - struct netns_nf { - struct nf_hook_entries *hooks[NFPROTO_NUMPROTO][NF_MAX_HOOKS]; ... } - struct nf_hook_entries { - u16 num_hook_entries; /* plus padding */ - struct nf_hook_entry hooks[]; - //const struct nf_hook_ops *orig_ops[]; } - struct nf_hook_entry { - nf_hookfn *hook; - void *priv; } - - (*) Even though the hook address is in the struct 'nf_hook_entry', we use the - original 'nf_hook_ops' hook address value, the one which was filled by the user, to - make it uniform to all the implementations. - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - hooks_type = ["array", "array", "pointer", "nf_hook_entries"] - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("netns_nf") - and vmlinux.get_type("netns_nf").has_member("hooks") - and cls.get_member_type(vmlinux.get_type("netns_nf"), "hooks") == hooks_type - ) - - def get_nf_hook_entries(self, nf_hooks_addr, proto_idx, hook_idx): - """This allows to support different hook array implementations from this version - on. For instance, in kernels >= 4.16 this multi-dimensional array is split in - one-dimensional array of pointers to 'nf_hooks_entries' per each protocol.""" - return nf_hooks_addr[proto_idx][hook_idx] - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - nf_hook_entries = self.get_nf_hook_entries(hook_container, proto_idx, hook_idx) - if not nf_hook_entries: - return - - nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") - nf_hook_ops_ptr_arr = self.build_nf_hook_ops_array(nf_hook_entries) - if not nf_hook_ops_ptr_arr: - return - - for nf_hook_ops_ptr in nf_hook_ops_ptr_arr: - nf_hook_ops = nf_hook_ops_ptr.dereference().cast(nf_hook_ops_name) - yield nf_hook_ops - - -class NetfilterImp_4_16_to_latest(NetfilterImp_4_14_to_4_16): - """The multidimensional array of nf_hook_entries was split in a one-dimensional - array per each protocol. - - struct net { - struct netns_nf nf; ... } - struct netns_nf { - struct nf_hook_entries * hooks_ipv4[NF_INET_NUMHOOKS]; - struct nf_hook_entries * hooks_ipv6[NF_INET_NUMHOOKS]; - struct nf_hook_entries * hooks_arp[NF_ARP_NUMHOOKS]; - struct nf_hook_entries * hooks_bridge[NF_INET_NUMHOOKS]; - struct nf_hook_entries * hooks_decnet[NF_DN_NUMHOOKS]; ... } - struct nf_hook_entries { - u16 num_hook_entries; /* plus padding */ - struct nf_hook_entry hooks[]; - //const struct nf_hook_ops *orig_ops[]; } - struct nf_hook_entry { - nf_hookfn *hook; - void *priv; } - - (*) Even though the hook address is in the struct nf_hook_entry, we use the original - nf_hook_ops hook address value, the one which was filled by the user, to make it - uniform to all the implementations. - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("netns_nf") - and vmlinux.get_type("netns_nf").has_member("hooks_ipv4") - ) - - def get_hooks_container(self, net, proto_name, hook_name): - try: - if proto_name == "IPV4": - net_nf_hooks = net.nf.hooks_ipv4 - elif proto_name == "ARP": - net_nf_hooks = net.nf.hooks_arp - elif proto_name == "BRIDGE": - net_nf_hooks = net.nf.hooks_bridge - elif proto_name == "IPV6": - net_nf_hooks = net.nf.hooks_ipv6 - elif proto_name == "DECNET": - net_nf_hooks = net.nf.hooks_decnet - else: - return - - yield net_nf_hooks - - except AttributeError: - # Protocol family disabled at kernel compilation - # CONFIG_NETFILTER_FAMILY_ARP=n || - # CONFIG_NETFILTER_FAMILY_BRIDGE=n || - # CONFIG_DECNET=n - pass - - def _get_nf_hook_entries_ptr(self, nf_hooks_addr, proto_idx, hook_idx): - nf_hook_entries_ptr = nf_hooks_addr[hook_idx] - return nf_hook_entries_ptr - - def get_nf_hook_entries(self, nf_hooks_addr, proto_idx, hook_idx): - return nf_hooks_addr[hook_idx] - - -class AbstractNetfilterNetDev(AbstractNetfilter): - """Base class to handle the Netfilter NetDev hooks. - It won't be executed. It has some common functions to all Netfilter NetDev hook - implementations. - - Netfilter NetDev hooks are set per network device which belongs to a network - namespace. - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - return False - - def subscribed_protocols(self): - return ("NETDEV",) - - def get_hooks_container(self, net, proto_name, hook_name): - net_device_type = self.vmlinux.get_type("net_device") - net_device_name = self.get_symbol_fullname("net_device") - for net_device in net.dev_base_head.to_list(net_device_name, "dev_list"): - if hook_name == "INGRESS": - if net_device_type.has_member("nf_hooks_ingress"): - # CONFIG_NETFILTER_INGRESS=y - yield net_device.nf_hooks_ingress - - elif hook_name == "EGRESS": - if net_device_type.has_member("nf_hooks_egress"): - # CONFIG_NETFILTER_EGRESS=y - yield net_device.nf_hooks_egress - - -class NetfilterNetDevImp_4_2_to_4_9(AbstractNetfilterNetDev): - """This is the first version of Netfilter Ingress hooks which was implemented using - a doubly-linked list of 'nf_hook_ops'. - struct list_head nf_hooks_ingress; - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - hooks_type = ["list_head"] - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("net_device") - and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") - and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") - == hooks_type - ) - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - nf_hooks_ingress = hook_container - nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") - return nf_hooks_ingress.to_list(nf_hook_ops_name, "list") - - -class NetfilterNetDevImp_4_9_to_4_14(AbstractNetfilterNetDev): - """In 4.9 it was changed to a simple singly-linked list. - struct nf_hook_entry * nf_hooks_ingress; - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - hooks_type = ["pointer", "nf_hook_entry"] - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("net_device") - and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") - and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") - == hooks_type - ) - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - nf_hooks_ingress_ptr = hook_container - if not nf_hooks_ingress_ptr: - return - - while nf_hooks_ingress_ptr: - nf_hook_entry = nf_hooks_ingress_ptr.dereference() - orig_ops = nf_hook_entry.orig_ops.dereference() - yield orig_ops - nf_hooks_ingress_ptr = nf_hooks_ingress_ptr.next - - -class NetfilterNetDevImp_4_14_to_latest(AbstractNetfilterNetDev): - """In 4.14 the hook list was converted to an array of pointers inside the struct - 'nf_hook_entries': - struct nf_hook_entries * nf_hooks_ingress; - struct nf_hook_entries { - u16 num_hook_entries; - struct nf_hook_entry hooks[]; - //const struct nf_hook_ops *orig_ops[]; } - """ - - @classmethod - def symtab_checks(cls, vmlinux) -> bool: - hooks_type = ["pointer", "nf_hook_entries"] - return ( - vmlinux.has_symbol("net_namespace_list") - and vmlinux.has_type("net_device") - and vmlinux.get_type("net_device").has_member("nf_hooks_ingress") - and cls.get_member_type(vmlinux.get_type("net_device"), "nf_hooks_ingress") - == hooks_type - ) - - def get_hook_ops(self, hook_container, proto_idx, hook_idx): - nf_hook_entries = hook_container - if not nf_hook_entries: - return - - nf_hook_ops_name = self.get_symbol_fullname("nf_hook_ops") - nf_hook_ops_ptr_arr = self.build_nf_hook_ops_array(nf_hook_entries) - if not nf_hook_ops_ptr_arr: - return - - for nf_hook_ops_ptr in nf_hook_ops_ptr_arr: - nf_hook_ops = nf_hook_ops_ptr.dereference().cast(nf_hook_ops_name) - yield nf_hook_ops - - -class Netfilter(interfaces.plugins.PluginInterface): - """Lists Netfilter hooks.""" - - _required_framework_version = (2, 22, 0) +class Netfilter( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=netfilter.Netfilter, + removal_date="2026-06-07", +): + """Lists Netfilter hooks (deprecated).""" _version = (2, 0, 0) - - _required_linux_utilities_modules_version = (3, 0, 0) - _required_linuxutils_gatherers_version = (1, 0, 0) - _required_linuxnet_version = (1, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherers", - component=linux_utilities_modules.ModuleGatherers, - version=cls._required_linuxutils_gatherers_version, - ), - requirements.VersionRequirement( - name="linuxnet", - component=network.NetSymbols, - version=cls._required_linuxnet_version, - ), - ] - - def _format_fields(self, fields): - ( - netns, - proto_name, - hook_name, - priority, - hook_func, - module_info, - symbol_name, - hooked, - ) = fields - - if module_info: - module_name = module_info.name - else: - module_name = renderers.NotAvailableValue() - - return ( - netns, - proto_name, - hook_name, - priority, - format_hints.Hex(hook_func), - module_name, - symbol_name or renderers.NotAvailableValue(), - str(hooked), - ) - - def _generator(self): - kernel_module_name = self.config["kernel"] - for fields in AbstractNetfilter.run_all( - context=self.context, kernel_module_name=kernel_module_name - ): - yield (0, self._format_fields(fields)) - - def run(self): - headers = [ - ("Net NS", int), - ("Proto", str), - ("Hook", str), - ("Priority", int), - ("Handler", format_hints.Hex), - ("Module", str), - ("Symbol", str), - ("Is Hooked", str), - ] - return renderers.TreeGrid(headers, self._generator()) + _required_framework_version = (2, 22, 0) From e3877f68ec463a8f39b946014214e5cbaf8a52b5 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Tue, 10 Jun 2025 19:37:57 +0300 Subject: [PATCH 24/25] Plugins: categorize linux.tty_check as a malware plugin --- test/plugins/linux/linux.py | 2 +- .../plugins/linux/malware/tty_check.py | 119 +++++++++++++++++ .../framework/plugins/linux/tty_check.py | 120 ++---------------- 3 files changed, 131 insertions(+), 110 deletions(-) create mode 100644 volatility3/framework/plugins/linux/malware/tty_check.py diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index c7f1df9c6..99fb4136a 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -89,7 +89,7 @@ class TestLinuxProcMaps: class TestLinuxTtyCheck: def test_linux_generic_tty_check(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.tty_check.tty_check", image, volatility, python + "linux.malware.tty_check.tty_check", image, volatility, python ) assert rc == 0 diff --git a/volatility3/framework/plugins/linux/malware/tty_check.py b/volatility3/framework/plugins/linux/malware/tty_check.py new file mode 100644 index 000000000..1547c5cc6 --- /dev/null +++ b/volatility3/framework/plugins/linux/malware/tty_check.py @@ -0,0 +1,119 @@ +# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 +# + +import logging +from typing import List + +import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules +from volatility3.framework import interfaces, renderers, exceptions, constants +from volatility3.framework.configuration import requirements +from volatility3.framework.interfaces import plugins +from volatility3.framework.objects import utility +from volatility3.framework.renderers import format_hints +from volatility3.framework.symbols import linux + +vollog = logging.getLogger(__name__) + + +class Tty_Check(plugins.PluginInterface): + """Checks tty devices for hooks""" + + _required_framework_version = (2, 0, 0) + _version = (1, 0, 0) + + @classmethod + def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: + return [ + requirements.ModuleRequirement( + name="kernel", + description="Linux kernel", + architectures=["Intel32", "Intel64"], + ), + requirements.VersionRequirement( + name="linux_utilities_modules", + component=linux_utilities_modules.Modules, + version=(3, 0, 0), + ), + requirements.VersionRequirement( + name="linux_utilities_module_gatherers", + component=linux_utilities_modules.ModuleGatherers, + version=(1, 0, 0), + ), + requirements.VersionRequirement( + name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) + ), + ] + + def _generator(self): + vmlinux = self.context.modules[self.config["kernel"]] + + try: + tty_drivers = vmlinux.object_from_symbol("tty_drivers").cast("list_head") + except exceptions.SymbolError: + tty_drivers = None + + if not tty_drivers: + raise TypeError( + "This plugin requires the tty_drivers structure." + "This structure is not present in the supplied symbol table." + "This means you are either analyzing an unsupported kernel version or that your symbol table is corrupt." + ) + + known_modules = linux_utilities_modules.Modules.run_modules_scanners( + context=self.context, + kernel_module_name=self.config["kernel"], + caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, + ) + + for tty in tty_drivers.to_list( + vmlinux.symbol_table_name + constants.BANG + "tty_driver", "tty_drivers" + ): + try: + ttys = utility.array_of_pointers( + tty.ttys.dereference(), + count=tty.num, + subtype=vmlinux.symbol_table_name + constants.BANG + "tty_struct", + context=self.context, + ) + except exceptions.PagedInvalidAddressException: + continue + + for tty_dev in ttys: + if tty_dev == 0: + continue + + try: + name = utility.array_to_string(tty_dev.name) + recv_buf = tty_dev.ldisc.ops.receive_buf + except exceptions.InvalidAddressException: + continue + + module_info, symbol_name = ( + linux_utilities_modules.Modules.module_lookup_by_address( + self.context, vmlinux.name, known_modules, recv_buf + ) + ) + + if module_info: + module_name = module_info.name + else: + module_name = renderers.NotAvailableValue() + + yield 0, ( + name, + format_hints.Hex(recv_buf), + module_name, + symbol_name or renderers.NotAvailableValue(), + ) + + def run(self): + return renderers.TreeGrid( + [ + ("Name", str), + ("Address", format_hints.Hex), + ("Module", str), + ("Symbol", str), + ], + self._generator(), + ) diff --git a/volatility3/framework/plugins/linux/tty_check.py b/volatility3/framework/plugins/linux/tty_check.py index 7d30b84ee..36bfb1b5a 100644 --- a/volatility3/framework/plugins/linux/tty_check.py +++ b/volatility3/framework/plugins/linux/tty_check.py @@ -1,118 +1,20 @@ -# This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0 +# This file is Copyright 2025 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # - import logging -from typing import List - -import volatility3.framework.symbols.linux.utilities.modules as linux_utilities_modules -from volatility3.framework import interfaces, renderers, exceptions, constants -from volatility3.framework.configuration import requirements -from volatility3.framework.interfaces import plugins -from volatility3.framework.objects import utility -from volatility3.framework.renderers import format_hints -from volatility3.framework.symbols import linux +from volatility3.framework import interfaces, deprecation +from volatility3.plugins.linux.malware import tty_check as ttycheck vollog = logging.getLogger(__name__) -class tty_check(plugins.PluginInterface): - """Checks tty devices for hooks""" +class tty_check( + interfaces.plugins.PluginInterface, + deprecation.PluginRenameClass, + replacement_class=ttycheck.Tty_Check, + removal_date="2026-06-07", +): + """Checks tty devices for hooks (deprecated).""" _required_framework_version = (2, 0, 0) - - @classmethod - def get_requirements(cls) -> List[interfaces.configuration.RequirementInterface]: - return [ - requirements.ModuleRequirement( - name="kernel", - description="Linux kernel", - architectures=["Intel32", "Intel64"], - ), - requirements.VersionRequirement( - name="linux_utilities_modules", - component=linux_utilities_modules.Modules, - version=(3, 0, 0), - ), - requirements.VersionRequirement( - name="linux_utilities_module_gatherers", - component=linux_utilities_modules.ModuleGatherers, - version=(1, 0, 0), - ), - requirements.VersionRequirement( - name="linuxutils", component=linux.LinuxUtilities, version=(2, 0, 0) - ), - ] - - def _generator(self): - vmlinux = self.context.modules[self.config["kernel"]] - - try: - tty_drivers = vmlinux.object_from_symbol("tty_drivers").cast("list_head") - except exceptions.SymbolError: - tty_drivers = None - - if not tty_drivers: - raise TypeError( - "This plugin requires the tty_drivers structure." - "This structure is not present in the supplied symbol table." - "This means you are either analyzing an unsupported kernel version or that your symbol table is corrupt." - ) - - known_modules = linux_utilities_modules.Modules.run_modules_scanners( - context=self.context, - kernel_module_name=self.config["kernel"], - caller_wanted_gatherers=linux_utilities_modules.ModuleGatherers.all_gatherers_identifier, - ) - - for tty in tty_drivers.to_list( - vmlinux.symbol_table_name + constants.BANG + "tty_driver", "tty_drivers" - ): - try: - ttys = utility.array_of_pointers( - tty.ttys.dereference(), - count=tty.num, - subtype=vmlinux.symbol_table_name + constants.BANG + "tty_struct", - context=self.context, - ) - except exceptions.PagedInvalidAddressException: - continue - - for tty_dev in ttys: - if tty_dev == 0: - continue - - try: - name = utility.array_to_string(tty_dev.name) - recv_buf = tty_dev.ldisc.ops.receive_buf - except exceptions.InvalidAddressException: - continue - - module_info, symbol_name = ( - linux_utilities_modules.Modules.module_lookup_by_address( - self.context, vmlinux.name, known_modules, recv_buf - ) - ) - - if module_info: - module_name = module_info.name - else: - module_name = renderers.NotAvailableValue() - - yield 0, ( - name, - format_hints.Hex(recv_buf), - module_name, - symbol_name or renderers.NotAvailableValue(), - ) - - def run(self): - return renderers.TreeGrid( - [ - ("Name", str), - ("Address", format_hints.Hex), - ("Module", str), - ("Symbol", str), - ], - self._generator(), - ) + _version = (1, 0, 0) From 8040c049e0c338e66a4f70671b6976421d2ae361 Mon Sep 17 00:00:00 2001 From: SolitudePy <47316655+SolitudePy@users.noreply.github.com> Date: Tue, 10 Jun 2025 20:30:05 +0300 Subject: [PATCH 25/25] Tests: change class name for tty_check --- test/plugins/linux/linux.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/plugins/linux/linux.py b/test/plugins/linux/linux.py index 99fb4136a..d6fbf5fa8 100644 --- a/test/plugins/linux/linux.py +++ b/test/plugins/linux/linux.py @@ -89,7 +89,7 @@ class TestLinuxProcMaps: class TestLinuxTtyCheck: def test_linux_generic_tty_check(self, image, volatility, python): rc, out, _err = test_volatility.runvol_plugin( - "linux.malware.tty_check.tty_check", image, volatility, python + "linux.malware.tty_check.Tty_Check", image, volatility, python ) assert rc == 0