-
Notifications
You must be signed in to change notification settings - Fork 91
Add INI file parser plugin #1639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DanielErb
wants to merge
9
commits into
fox-it:main
Choose a base branch
from
DanielErb:feature/ini
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+220
−0
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3e1a67e
add ini plugin
DanielErb 4aa5b91
add ini plugin with exceptions and tests
DanielErb fff5a26
add ini plugin with exceptions and tests
DanielErb 463336f
minor fixes
DanielErb e094f1c
CR fixes
DanielErb f00f9d3
added minor fixes to tests and plugin
DanielErb 3559a38
add ini plugin with exceptions and tests
DanielErb 99093d6
add ini plugin with exceptions and tests
DanielErb fc803ef
Update dissect/target/plugins/filesystem/ini.py
DanielErb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from dissect.target.exceptions import ConfigurationParsingError, FileNotFoundError, UnsupportedPluginError | ||
| from dissect.target.helpers import configutil | ||
| from dissect.target.helpers.record import TargetRecordDescriptor | ||
| from dissect.target.plugin import Plugin, arg, export | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Iterator | ||
|
|
||
| from dissect.target.helpers.fsutil import TargetPath | ||
|
|
||
| IniRecord = TargetRecordDescriptor( | ||
| "filesystem/iniFileRecord", | ||
| [ | ||
| ("datetime", "atime"), | ||
| ("datetime", "mtime"), | ||
| ("datetime", "ctime"), | ||
| ("string", "section"), | ||
| ("string", "key"), | ||
| ("string", "value"), | ||
| ("path", "path"), | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| class IniPlugin(Plugin): | ||
| """INI file plugin. | ||
|
|
||
| This plugin scans target filesystems for INI configuration files and parses them into | ||
| structured records. It handles both UTF-8 and UTF-16 encoded INI files | ||
| """ | ||
|
|
||
| def check_compatible(self) -> None: | ||
| if not len(self.target.fs.mounts): | ||
| raise UnsupportedPluginError("No filesystems found on target") | ||
|
|
||
| def on_error(self, error: Exception) -> None: | ||
| """Error handler for filesystem traversal. Logs warnings for permission errors and other exceptions, | ||
| but continues traversal. | ||
|
|
||
| Args: | ||
| error: ``Exception`` the exception thrown during filesystem traversal. | ||
| """ | ||
| if isinstance(error, PermissionError): | ||
| self.target.log.warning("Permission denied while scanning for ini files: %s", error) | ||
| self.target.log.debug("", exc_info=error) | ||
| return | ||
|
|
||
| self.target.log.warning("Exception while scanning for ini files: %s", error) | ||
| self.target.log.debug("", exc_info=error) | ||
|
|
||
| def _iter_ini_files(self, path: str) -> Iterator[TargetPath]: | ||
| """Find all INI files under the given path. | ||
|
|
||
| Handles both explicit file paths and directory traversal. Continues traversal even if | ||
| permission errors are encountered on individual directories. | ||
|
|
||
| Args: | ||
| path: ``string`` of Target filesystem path to scan. Can be a file or directory. | ||
|
|
||
| Returns: | ||
| Iterator yields ``TargetPath`` | ||
| """ | ||
| target_path = self.target.fs.path(path) | ||
| if not target_path.exists(): | ||
| self.target.log.error("Provided path %s does not exist on target", target_path) | ||
| return | ||
|
|
||
| if target_path.is_file(): | ||
| if target_path.suffix.lower() == ".ini": | ||
| yield target_path | ||
| return | ||
|
|
||
| for root, _dirs, files in self.target.fs.walk(path, onerror=self.on_error): | ||
| root_path = self.target.fs.path(root) | ||
| for file_name in files: | ||
| if file_name.lower().endswith(".ini"): | ||
| yield root_path.joinpath(file_name) | ||
|
|
||
| @export(record=IniRecord) | ||
| @arg("-p", "--path", default="/", help="path to an .ini file or directory in target") | ||
| def ini(self, path: str = "/") -> Iterator[IniRecord]: | ||
| """Scan for and parse INI files, yielding structured records. | ||
|
|
||
| This method recursively discovers INI configuration files under the specified path, | ||
| parses them, and yields an IniRecord for each | ||
| key-value pair found. | ||
|
|
||
| Args: | ||
| path: ``string`` of Target filesystem path to scan (default "/"). Can be a file or directory. | ||
|
|
||
| Returns: | ||
| Iterator yields ``IniRecord``: One record per key-value pair in discovered INI files. | ||
| """ | ||
| for ini_file_path in self._iter_ini_files(path): | ||
| try: | ||
| config = _parse_ini(ini_file_path) | ||
| stat = ini_file_path.stat() | ||
| except FileNotFoundError as e: | ||
| # File may disappear between compatibility check and parse. | ||
| self.target.log.warning("File not found: %s", ini_file_path) | ||
| self.target.log.debug("", exc_info=e) | ||
| continue | ||
| except Exception as e: | ||
| self.target.log.warning("Exception generating ini record for %s: %s", ini_file_path, e) | ||
| self.target.log.debug("", exc_info=e) | ||
| continue | ||
|
|
||
| for section_name, section in config.items(): | ||
| for key, value in section.items(): | ||
| yield IniRecord( | ||
| atime=stat.st_atime, | ||
| mtime=stat.st_mtime, | ||
| ctime=stat.st_ctime, | ||
| section=section_name, | ||
| key=key, | ||
| value=str(value), | ||
| path=ini_file_path, | ||
| _target=self.target, | ||
| ) | ||
|
|
||
|
|
||
| def _parse_ini(ini_file_path: TargetPath) -> configutil.ConfigurationParser: | ||
| """Parse an INI file, with automatic fallback for UTF-16 encoded files. | ||
|
|
||
| First attempts to parse the file with the default UTF-8 encoding. If a ConfigurationParsingError, | ||
| retries using UTF-16 decoding | ||
|
|
||
| Args: | ||
| ini_file_path: ``TargetPath`` to the INI file to parse. | ||
|
|
||
| Returns: | ||
| ConfigurationParser: ``ConfigurationParser`` Parsed INI configuration object. | ||
| """ | ||
| try: | ||
| return configutil.parse(ini_file_path, hint="ini") | ||
| except (UnicodeDecodeError, ConfigurationParsingError): | ||
| # Many Windows INI files are UTF-16 | ||
| with ini_file_path.open("rb") as f: | ||
| raw_data = f.read() | ||
| text_data = raw_data.decode("utf-16") | ||
|
|
||
| parser = configutil.Ini() | ||
| parser.read_file(io.StringIO(text_data)) | ||
| return parser | ||
Git LFS file not shown
Git LFS file not shown
Git LFS file not shown
Git LFS file not shown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| import pytest | ||
|
|
||
| from dissect.target.plugins.filesystem.ini import IniPlugin | ||
| from tests._utils import absolute_path | ||
|
|
||
| if TYPE_CHECKING: | ||
| from dissect.target.filesystem import VirtualFilesystem | ||
| from dissect.target.target import Target | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def target_ini(target_unix: Target, fs_unix: VirtualFilesystem) -> Target: | ||
| fs_unix.map_dir("/etc/config", absolute_path("_data/plugins/filesystem/ini")) | ||
|
|
||
| target_unix.add_plugin(IniPlugin) | ||
| return target_unix | ||
|
|
||
|
|
||
| def test_ini_parses_records(target_ini: Target) -> None: | ||
| """Test INI file discovery and parsing from a directory.""" | ||
| records = list(target_ini.ini("/etc/config")) | ||
|
|
||
| assert len(records) == 6 | ||
|
|
||
| by_key = {(record.section, record.key): record for record in records} | ||
|
|
||
| assert by_key[("Run", "Program")].value == "calc.exe" | ||
| assert by_key[("Run", "NoValue")].value == "None" | ||
| assert by_key[("Display", "Theme")].value == "Dark" | ||
| assert by_key[("Shutdown", "Script")].value == "cleanup.cmd" | ||
|
|
||
| paths = {str(record.path).lower() for record in records} | ||
| assert "/etc/config/startup.ini" in paths | ||
| assert "/etc/config/shutdown.ini" in paths | ||
| assert "/etc/config/not_ini.txt" not in paths | ||
|
|
||
|
|
||
| def test_ini_parses_explicit_file(target_ini: Target) -> None: | ||
| """Test parsing a single explicitly specified INI file.""" | ||
| records = list(target_ini.ini("/etc/config/startup.ini")) | ||
|
|
||
| assert len(records) == 3 | ||
| assert {record.section for record in records} == {"Run", "Display"} | ||
| assert all(str(record.path).lower().endswith("startup.ini") for record in records) | ||
|
|
||
|
|
||
| def test_ini_parses_utf16_encoded_file(target_ini: Target) -> None: | ||
| """Test parsing UTF-16 encoded INI files.""" | ||
| records = list(target_ini.ini("/etc/config/utf16.ini")) | ||
|
|
||
| assert len(records) == 2 | ||
| by_key = {(record.section, record.key): record for record in records} | ||
| assert by_key[("Setting", "Timeout")].value == "30" | ||
| assert by_key[("Setting", "Delay")].value == "60" | ||
| assert all(str(record.path).lower().endswith("utf16.ini") for record in records) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The record name
filesystem/iniFileRecordis inconsistent with the existing record naming convention in this repo (typically lowercase path segments, e.g.filesystem/entry,filesystem/yara/match). Consider renaming this to a lowercase, slash-delimited name to keep record type names consistent for downstream consumers.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dont agree as this name is too generic