rat-king-parser 4.2.4__tar.gz → 4.2.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {rat_king_parser-4.2.4/src/rat_king_parser.egg-info → rat_king_parser-4.2.5}/PKG-INFO +14 -9
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/README.md +9 -6
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/pyproject.toml +4 -3
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/_version.py +1 -1
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/__init__.py +1 -1
- rat_king_parser-4.2.5/src/rat_king_parser/config_parser/rat_config_parser.py +441 -0
- rat_king_parser-4.2.5/src/rat_king_parser/config_parser/utils/config_item.py +465 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/config_normalization.py +14 -4
- rat_king_parser-4.2.5/src/rat_king_parser/config_parser/utils/data_utils.py +173 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/__init__.py +10 -9
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor.py +23 -2
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv.py +204 -87
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv_pbkdf.py +101 -44
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_decrypt_xor.py +52 -22
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_ecb.py +70 -31
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_plaintext.py +4 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_random_hardcoded.py +9 -5
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_rijndael.py +68 -39
- rat_king_parser-4.2.5/src/rat_king_parser/config_parser/utils/dotnetpe_payload.py +487 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/extern/maco/rkp_maco.py +141 -42
- rat_king_parser-4.2.5/src/rat_king_parser/rkp.py +222 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/yara_utils/__init__.py +1 -1
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/yara_utils/recompile.py +6 -4
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/yara_utils/rules.yar +1 -1
- rat_king_parser-4.2.5/src/rat_king_parser/yara_utils/rules.yarc +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5/src/rat_king_parser.egg-info}/PKG-INFO +14 -9
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser.egg-info/SOURCES.txt +1 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser.egg-info/requires.txt +3 -2
- rat_king_parser-4.2.5/tests/test_framework.py +1211 -0
- rat_king_parser-4.2.4/src/rat_king_parser/config_parser/rat_config_parser.py +0 -328
- rat_king_parser-4.2.4/src/rat_king_parser/config_parser/utils/config_item.py +0 -155
- rat_king_parser-4.2.4/src/rat_king_parser/config_parser/utils/data_utils.py +0 -64
- rat_king_parser-4.2.4/src/rat_king_parser/config_parser/utils/dotnetpe_payload.py +0 -318
- rat_king_parser-4.2.4/src/rat_king_parser/rkp.py +0 -142
- rat_king_parser-4.2.4/src/rat_king_parser/yara_utils/rules.yarc +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/LICENSE +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/setup.cfg +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/__init__.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/config_parser_exception.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/__init__.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/config_parser/utils/dotnet_constants.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/extern/__init__.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser/extern/maco/__init__.py +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser.egg-info/dependency_links.txt +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser.egg-info/entry_points.txt +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/src/rat_king_parser.egg-info/top_level.txt +0 -0
- {rat_king_parser-4.2.4 → rat_king_parser-4.2.5}/tests/test_known_samples.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rat-king-parser
|
|
3
|
-
Version: 4.2.
|
|
3
|
+
Version: 4.2.5
|
|
4
4
|
Summary: A robust, multiprocessing-capable, multi-family RAT config parser/config extractor for AsyncRAT, DcRAT, VenomRAT, QuasarRAT, XWorm, Xeno RAT, and cloned/derivative RAT families.
|
|
5
5
|
Author-email: jeFF0Falltrades <8444166+jeFF0Falltrades@users.noreply.github.com>
|
|
6
6
|
Maintainer-email: jeFF0Falltrades <8444166+jeFF0Falltrades@users.noreply.github.com>
|
|
@@ -23,17 +23,19 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
23
23
|
Classifier: Programming Language :: Python :: 3.11
|
|
24
24
|
Classifier: Programming Language :: Python :: 3.12
|
|
25
25
|
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
27
|
Requires-Python: >=3.10
|
|
27
28
|
Description-Content-Type: text/markdown
|
|
28
29
|
License-File: LICENSE
|
|
29
30
|
Requires-Dist: dnfile
|
|
31
|
+
Requires-Dist: pefile
|
|
30
32
|
Requires-Dist: pycryptodomex
|
|
31
|
-
Requires-Dist: yara-
|
|
33
|
+
Requires-Dist: yara-x
|
|
32
34
|
Provides-Extra: dev
|
|
33
35
|
Requires-Dist: pre-commit; extra == "dev"
|
|
34
36
|
Requires-Dist: pytest; extra == "dev"
|
|
35
37
|
Provides-Extra: maco
|
|
36
|
-
Requires-Dist: maco; extra == "maco"
|
|
38
|
+
Requires-Dist: maco>=1.2.22; extra == "maco"
|
|
37
39
|
Requires-Dist: validators; extra == "maco"
|
|
38
40
|
Dynamic: license-file
|
|
39
41
|
|
|
@@ -73,7 +75,7 @@ As of `v3.1.2`, the RAT King Parser is now available on PyPI and can be installe
|
|
|
73
75
|
pip install rat-king-parser
|
|
74
76
|
```
|
|
75
77
|
|
|
76
|
-
|
|
78
|
+
Uses [YARA-X](https://virustotal.github.io/yara-x/) (installed automatically via prebuilt Python wheels; no separate native YARA installation is required).
|
|
77
79
|
|
|
78
80
|
### Usage Help
|
|
79
81
|
|
|
@@ -91,16 +93,16 @@ options:
|
|
|
91
93
|
-n, --normalize Attempt to translate common variations of config keys to normalized field names
|
|
92
94
|
-p, --preserve-keys Preserve potentially obfuscated configuration keys as-is instead of replacing them with placeholder "obfuscated key" entries
|
|
93
95
|
-r, --recompile Recompile the YARA rule file used for family detection prior to running the parser
|
|
94
|
-
-y, --yara YARA
|
|
96
|
+
-y, --yara YARA Uses the yara-x compiled (.yarc) or source (.yar/.yara) rule at this path to determine the potential family of each payload (uses a prepackaged rule at rules.yarc by default)
|
|
95
97
|
```
|
|
96
98
|
|
|
97
99
|
### Using YARA for Payload Identification
|
|
98
100
|
|
|
99
|
-
A [YARA](https://
|
|
101
|
+
A [YARA-X](https://virustotal.github.io/yara-x/) rule for RAT family identification is included with this script in `yara_utils` in both source (`rules.yar`) and compiled (`rules.yarc`) forms.
|
|
100
102
|
|
|
101
|
-
|
|
103
|
+
Using the `--yara` flag allows a user to specify their own custom YARA rule, either as a YARA-X compiled `.yarc` file or directly as a `.yar`/`.yara` source file.
|
|
102
104
|
|
|
103
|
-
If you encounter errors
|
|
105
|
+
If you encounter errors loading the included compiled YARA rule (for example, due to mismatched `yara-x` versions), RKP automatically falls back to compiling the bundled `rules.yar` from source, or you can recompile the bundled `.yarc` in place with `--recompile`. Custom `.yarc` files compiled with legacy `yara-python` or an incompatible `yara-x` version must be recompiled with `yara-x` (or passed as `.yar`/`.yara` source files directly).
|
|
104
106
|
|
|
105
107
|
`yara_utils/recompile.py`, which is the script invoked by the `--recompile` flag, can also be executed on its own to (re)compile any YARA rule:
|
|
106
108
|
|
|
@@ -1070,7 +1072,10 @@ $ rat-king-parser -np dangerzone/* | jq
|
|
|
1070
1072
|
|
|
1071
1073
|
|
|
1072
1074
|
## Development Guide
|
|
1073
|
-
|
|
1075
|
+
|
|
1076
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the architecture walkthrough, dnSpy IL inspection examples, and step-by-step instructions for adding new RAT families, CIL patterns, decryptors, and YARA-X rules.
|
|
1077
|
+
|
|
1078
|
+
For AI coding agents, a cross-agent workflow skill is included at [`skills/rat-king-parser-dev/SKILL.md`](skills/rat-king-parser-dev/SKILL.md) (installable via `gh skill install jeFF0Falltrades/rat_king_parser rat-king-parser-dev`) alongside [`AGENTS.md`](AGENTS.md).
|
|
1074
1079
|
|
|
1075
1080
|
### Development Dependencies
|
|
1076
1081
|
|
|
@@ -34,7 +34,7 @@ As of `v3.1.2`, the RAT King Parser is now available on PyPI and can be installe
|
|
|
34
34
|
pip install rat-king-parser
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
Uses [YARA-X](https://virustotal.github.io/yara-x/) (installed automatically via prebuilt Python wheels; no separate native YARA installation is required).
|
|
38
38
|
|
|
39
39
|
### Usage Help
|
|
40
40
|
|
|
@@ -52,16 +52,16 @@ options:
|
|
|
52
52
|
-n, --normalize Attempt to translate common variations of config keys to normalized field names
|
|
53
53
|
-p, --preserve-keys Preserve potentially obfuscated configuration keys as-is instead of replacing them with placeholder "obfuscated key" entries
|
|
54
54
|
-r, --recompile Recompile the YARA rule file used for family detection prior to running the parser
|
|
55
|
-
-y, --yara YARA
|
|
55
|
+
-y, --yara YARA Uses the yara-x compiled (.yarc) or source (.yar/.yara) rule at this path to determine the potential family of each payload (uses a prepackaged rule at rules.yarc by default)
|
|
56
56
|
```
|
|
57
57
|
|
|
58
58
|
### Using YARA for Payload Identification
|
|
59
59
|
|
|
60
|
-
A [YARA](https://
|
|
60
|
+
A [YARA-X](https://virustotal.github.io/yara-x/) rule for RAT family identification is included with this script in `yara_utils` in both source (`rules.yar`) and compiled (`rules.yarc`) forms.
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
Using the `--yara` flag allows a user to specify their own custom YARA rule, either as a YARA-X compiled `.yarc` file or directly as a `.yar`/`.yara` source file.
|
|
63
63
|
|
|
64
|
-
If you encounter errors
|
|
64
|
+
If you encounter errors loading the included compiled YARA rule (for example, due to mismatched `yara-x` versions), RKP automatically falls back to compiling the bundled `rules.yar` from source, or you can recompile the bundled `.yarc` in place with `--recompile`. Custom `.yarc` files compiled with legacy `yara-python` or an incompatible `yara-x` version must be recompiled with `yara-x` (or passed as `.yar`/`.yara` source files directly).
|
|
65
65
|
|
|
66
66
|
`yara_utils/recompile.py`, which is the script invoked by the `--recompile` flag, can also be executed on its own to (re)compile any YARA rule:
|
|
67
67
|
|
|
@@ -1031,7 +1031,10 @@ $ rat-king-parser -np dangerzone/* | jq
|
|
|
1031
1031
|
|
|
1032
1032
|
|
|
1033
1033
|
## Development Guide
|
|
1034
|
-
|
|
1034
|
+
|
|
1035
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the architecture walkthrough, dnSpy IL inspection examples, and step-by-step instructions for adding new RAT families, CIL patterns, decryptors, and YARA-X rules.
|
|
1036
|
+
|
|
1037
|
+
For AI coding agents, a cross-agent workflow skill is included at [`skills/rat-king-parser-dev/SKILL.md`](skills/rat-king-parser-dev/SKILL.md) (installable via `gh skill install jeFF0Falltrades/rat_king_parser rat-king-parser-dev`) alongside [`AGENTS.md`](AGENTS.md).
|
|
1035
1038
|
|
|
1036
1039
|
### Development Dependencies
|
|
1037
1040
|
|
|
@@ -33,11 +33,12 @@ classifiers = [
|
|
|
33
33
|
"Programming Language :: Python :: 3.11",
|
|
34
34
|
"Programming Language :: Python :: 3.12",
|
|
35
35
|
"Programming Language :: Python :: 3.13",
|
|
36
|
+
"Programming Language :: Python :: 3.14",
|
|
36
37
|
]
|
|
37
38
|
dynamic = ["version"]
|
|
38
|
-
dependencies = ["dnfile", "pycryptodomex", "yara-
|
|
39
|
+
dependencies = ["dnfile", "pefile", "pycryptodomex", "yara-x"]
|
|
39
40
|
optional-dependencies.dev = ["pre-commit", "pytest"]
|
|
40
|
-
optional-dependencies.maco = ["maco", "validators"]
|
|
41
|
+
optional-dependencies.maco = ["maco>=1.2.22", "validators"]
|
|
41
42
|
urls."Bug Reports" = "https://github.com/jeFF0Falltrades/rat_king_parser/issues"
|
|
42
43
|
urls."Homepage" = "https://github.com/jeFF0Falltrades/rat_king_parser"
|
|
43
44
|
urls."Say Thanks!" = "https://www.buymeacoffee.com/jeff0falltrades"
|
|
@@ -55,7 +56,7 @@ namespaces = false
|
|
|
55
56
|
"rat_king_parser.yara_utils" = ["*.yar", "*.yarc"]
|
|
56
57
|
|
|
57
58
|
[tool.ruff]
|
|
58
|
-
lint.extend-select = ["I"]
|
|
59
|
+
lint.extend-select = ["I", "B"]
|
|
59
60
|
|
|
60
61
|
[tool.pre-commit]
|
|
61
62
|
hook-config = "file:.pre-commit-config.yaml"
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
#
|
|
3
|
+
# rat_config_parser.py
|
|
4
|
+
#
|
|
5
|
+
# Author: jeFF0Falltrades
|
|
6
|
+
#
|
|
7
|
+
# Provides the primary functionality for parsing configurations from RATs
|
|
8
|
+
#
|
|
9
|
+
# MIT License
|
|
10
|
+
#
|
|
11
|
+
# Copyright (c) 2024 Jeff Archer
|
|
12
|
+
#
|
|
13
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
# in the Software without restriction, including without limitation the rights
|
|
16
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
# furnished to do so, subject to the following conditions:
|
|
19
|
+
#
|
|
20
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
# copies or substantial portions of the Software.
|
|
22
|
+
#
|
|
23
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
# SOFTWARE.
|
|
30
|
+
from logging import getLogger
|
|
31
|
+
from os.path import isfile
|
|
32
|
+
from re import DOTALL, compile, search
|
|
33
|
+
from typing import Any, Tuple
|
|
34
|
+
|
|
35
|
+
from yara_x import Rules
|
|
36
|
+
|
|
37
|
+
from .config_parser_exception import ConfigParserException
|
|
38
|
+
from .utils import config_item
|
|
39
|
+
from .utils.config_normalization import check_key_n_value
|
|
40
|
+
from .utils.decryptors import (
|
|
41
|
+
SUPPORTED_DECRYPTORS,
|
|
42
|
+
ConfigDecryptor,
|
|
43
|
+
IncompatibleDecryptorException,
|
|
44
|
+
)
|
|
45
|
+
from .utils.decryptors.config_decryptor_plaintext import (
|
|
46
|
+
KNOWN_CONFIG_FIELD_NAMES_NORMALIZED,
|
|
47
|
+
)
|
|
48
|
+
from .utils.dotnetpe_payload import DotNetPEPayload
|
|
49
|
+
|
|
50
|
+
logger = getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class RATConfigParser:
|
|
54
|
+
# Min and max number of items in a potential config section
|
|
55
|
+
_MIN_CONFIG_LEN_FLOOR = 5
|
|
56
|
+
_MIN_CONFIG_LEN_CEILING = 9
|
|
57
|
+
|
|
58
|
+
# Pattern to find the VerifyHash() method
|
|
59
|
+
_PATTERN_VERIFY_HASH = compile(
|
|
60
|
+
rb"\x7e.{3}\x04(?:\x6f.{3}\x0a){2}\x74.{3}\x01", DOTALL
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
file_path: str = "",
|
|
66
|
+
yara_rule: Rules | None = None,
|
|
67
|
+
data: bytes | None = None,
|
|
68
|
+
remap_config: bool = False,
|
|
69
|
+
preserve_obfuscated_keys: bool = False,
|
|
70
|
+
) -> None:
|
|
71
|
+
self.report = {
|
|
72
|
+
"file_path": file_path,
|
|
73
|
+
"sha256": "",
|
|
74
|
+
"yara_possible_family": "",
|
|
75
|
+
"key": "",
|
|
76
|
+
"salt": "",
|
|
77
|
+
"config": {},
|
|
78
|
+
}
|
|
79
|
+
self.error: str | None = None
|
|
80
|
+
self.remap_config = remap_config
|
|
81
|
+
self.preserve_obfuscated_keys = preserve_obfuscated_keys
|
|
82
|
+
self._dnpp: DotNetPEPayload | None = None
|
|
83
|
+
self._decryptor: ConfigDecryptor | None = None
|
|
84
|
+
# Binary-level decryptor cache so metadata regexes run once per payload
|
|
85
|
+
self._decryptor_cache: dict[type[ConfigDecryptor], ConfigDecryptor] = {}
|
|
86
|
+
self._incompatible_decryptors: set[type[ConfigDecryptor]] = set()
|
|
87
|
+
try:
|
|
88
|
+
if data is None and not isfile(file_path):
|
|
89
|
+
raise ConfigParserException("File not found")
|
|
90
|
+
self._dnpp = DotNetPEPayload(file_path, yara_rule, data)
|
|
91
|
+
self.report["sha256"] = self._dnpp.sha256
|
|
92
|
+
self.report["yara_possible_family"] = self._dnpp.yara_match
|
|
93
|
+
|
|
94
|
+
# Assigned in _decrypt_and_decode_config()
|
|
95
|
+
self.report["config"] = self._get_config()
|
|
96
|
+
key_hex = "None"
|
|
97
|
+
if self._decryptor is not None and self._decryptor.key is not None:
|
|
98
|
+
if isinstance(self._decryptor.key, bytes):
|
|
99
|
+
key_hex = self._decryptor.key.hex()
|
|
100
|
+
else:
|
|
101
|
+
key_hex = str(self._decryptor.key)
|
|
102
|
+
self.report["key"] = key_hex
|
|
103
|
+
self.report["salt"] = (
|
|
104
|
+
self._decryptor.salt.hex()
|
|
105
|
+
if self._decryptor is not None and self._decryptor.salt is not None
|
|
106
|
+
else "None"
|
|
107
|
+
)
|
|
108
|
+
except Exception as e:
|
|
109
|
+
self.error = f"Exception encountered for {file_path}: {e}"
|
|
110
|
+
self.report["config"] = self.error
|
|
111
|
+
|
|
112
|
+
# Extracts raw config items (without running decryption) once per method body
|
|
113
|
+
def _extract_raw_config_items(
|
|
114
|
+
self, encrypted_config: bytes
|
|
115
|
+
) -> tuple[list[tuple[config_item.ConfigItem, dict[str, Any]]], dict[int, str], int]:
|
|
116
|
+
parsed_buckets = config_item.parse_config_items(
|
|
117
|
+
encrypted_config,
|
|
118
|
+
field_sig_lookup=self._dnpp.field_signature_from_rva,
|
|
119
|
+
)
|
|
120
|
+
extracted: list[tuple[config_item.ConfigItem, dict[str, Any]]] = []
|
|
121
|
+
config_fields_map: dict[int, str] = {}
|
|
122
|
+
raw_field_names: set[str] = set()
|
|
123
|
+
|
|
124
|
+
for item, raw_entries in parsed_buckets:
|
|
125
|
+
if not raw_entries:
|
|
126
|
+
continue
|
|
127
|
+
item_data: dict[str, Any] = {}
|
|
128
|
+
for k, v in raw_entries.items():
|
|
129
|
+
try:
|
|
130
|
+
field_name = self._dnpp.field_name_from_rva(k)
|
|
131
|
+
except ConfigParserException as e:
|
|
132
|
+
logger.debug(
|
|
133
|
+
"Skipping invalid Field RVA %s in method body: %s",
|
|
134
|
+
hex(k),
|
|
135
|
+
e,
|
|
136
|
+
)
|
|
137
|
+
continue
|
|
138
|
+
if isinstance(item, config_item.EncryptedStringConfigItem):
|
|
139
|
+
try:
|
|
140
|
+
v = self._dnpp.user_string_from_rva(v)
|
|
141
|
+
except ConfigParserException as e:
|
|
142
|
+
logger.debug(
|
|
143
|
+
"Skipping invalid UserString RVA %s for field %s: %s",
|
|
144
|
+
hex(v),
|
|
145
|
+
field_name,
|
|
146
|
+
e,
|
|
147
|
+
)
|
|
148
|
+
continue
|
|
149
|
+
elif isinstance(item, config_item.ByteArrayConfigItem):
|
|
150
|
+
arr_size, arr_rva = v
|
|
151
|
+
try:
|
|
152
|
+
v = self._dnpp.byte_array_from_size_and_rva(
|
|
153
|
+
arr_size, arr_rva
|
|
154
|
+
).hex()
|
|
155
|
+
except ConfigParserException as e:
|
|
156
|
+
logger.debug(
|
|
157
|
+
"Skipping invalid ByteArray for field %s: %s",
|
|
158
|
+
field_name,
|
|
159
|
+
e,
|
|
160
|
+
)
|
|
161
|
+
continue
|
|
162
|
+
config_fields_map[k] = field_name
|
|
163
|
+
item_data[field_name] = v
|
|
164
|
+
raw_field_names.add(field_name)
|
|
165
|
+
if item_data:
|
|
166
|
+
extracted.append((item, item_data))
|
|
167
|
+
|
|
168
|
+
return extracted, config_fields_map, len(raw_field_names)
|
|
169
|
+
|
|
170
|
+
# Decrypts/decodes values from pre-extracted raw config items
|
|
171
|
+
def _decode_extracted_config(
|
|
172
|
+
self,
|
|
173
|
+
extracted: list[tuple[config_item.ConfigItem, dict[str, Any]]],
|
|
174
|
+
config_fields_map: dict[int, str],
|
|
175
|
+
raw_count: int,
|
|
176
|
+
min_config_len: int,
|
|
177
|
+
) -> dict[str, Any]:
|
|
178
|
+
# Fast-reject before running expensive decryptors (allow +1 for
|
|
179
|
+
# decryptors that append a dynamic field such as hardcoded_hosts or
|
|
180
|
+
# xor_decoded_strings).
|
|
181
|
+
has_url_host = any("UrlHost" in item_data for _, item_data in extracted)
|
|
182
|
+
if raw_count + 1 < min_config_len and not has_url_host:
|
|
183
|
+
raise ConfigParserException(
|
|
184
|
+
f"Minimum threshold of config items not met: {raw_count}/{min_config_len}"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
decoded_config: dict[str, Any] = {}
|
|
188
|
+
self._decryptor = None
|
|
189
|
+
for item, item_data in extracted:
|
|
190
|
+
if isinstance(item, config_item.EncryptedStringConfigItem):
|
|
191
|
+
item_data = self._attempt_decryption(item_data)
|
|
192
|
+
decoded_config.update(item_data)
|
|
193
|
+
|
|
194
|
+
# UrlHost is a marker of a special case until this can be standardized
|
|
195
|
+
if len(decoded_config) < min_config_len and "UrlHost" not in decoded_config:
|
|
196
|
+
self._decryptor = None
|
|
197
|
+
raise ConfigParserException(
|
|
198
|
+
f"Minimum threshold of config items not met: {len(decoded_config)}/{min_config_len}"
|
|
199
|
+
)
|
|
200
|
+
if self.remap_config:
|
|
201
|
+
return self._remap_config(decoded_config, config_fields_map)
|
|
202
|
+
return decoded_config
|
|
203
|
+
|
|
204
|
+
# Decrypts/decodes values from an encrypted config and returns the
|
|
205
|
+
# decrypted/decoded config
|
|
206
|
+
def _decrypt_and_decode_config(
|
|
207
|
+
self, encrypted_config: bytes, min_config_len: int
|
|
208
|
+
) -> dict[str, Any]:
|
|
209
|
+
extracted, config_fields_map, raw_count = self._extract_raw_config_items(
|
|
210
|
+
encrypted_config
|
|
211
|
+
)
|
|
212
|
+
return self._decode_extracted_config(
|
|
213
|
+
extracted, config_fields_map, raw_count, min_config_len
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
def _attempt_decryption(self, item_data: dict[str, Any]) -> dict[str, Any]:
|
|
217
|
+
# Always evaluate decryptors in priority order without leaking state
|
|
218
|
+
# from any previous failed .cctor candidate.
|
|
219
|
+
self._decryptor = None
|
|
220
|
+
for decryptor_cls in SUPPORTED_DECRYPTORS:
|
|
221
|
+
if decryptor_cls in self._incompatible_decryptors:
|
|
222
|
+
continue
|
|
223
|
+
|
|
224
|
+
decryptor_instance = self._decryptor_cache.get(decryptor_cls)
|
|
225
|
+
if decryptor_instance is None:
|
|
226
|
+
# Try to instantiate the selected decryptor once per payload;
|
|
227
|
+
# mark incompatible on failure so we never re-scan the binary.
|
|
228
|
+
try:
|
|
229
|
+
decryptor_instance = decryptor_cls(self._dnpp)
|
|
230
|
+
except IncompatibleDecryptorException as ide:
|
|
231
|
+
logger.debug(
|
|
232
|
+
"Decryptor incompatible %s : %s", decryptor_cls, ide
|
|
233
|
+
)
|
|
234
|
+
self._incompatible_decryptors.add(decryptor_cls)
|
|
235
|
+
continue
|
|
236
|
+
self._decryptor_cache[decryptor_cls] = decryptor_instance
|
|
237
|
+
else:
|
|
238
|
+
decryptor_instance.reset_per_config_state()
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
# Try to decrypt the encrypted strings; continue to next
|
|
242
|
+
# compatible decryptor on failure
|
|
243
|
+
decrypted = decryptor_instance.decrypt_encrypted_strings(item_data)
|
|
244
|
+
self._decryptor = decryptor_instance
|
|
245
|
+
return decrypted
|
|
246
|
+
except Exception as e:
|
|
247
|
+
logger.debug(
|
|
248
|
+
"Decryption failed with decryptor %s : %s", decryptor_cls, e
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
# If we exit the loop without returning, no decryptor succeeded
|
|
252
|
+
raise ConfigParserException("All decryptors failed")
|
|
253
|
+
|
|
254
|
+
@staticmethod
|
|
255
|
+
def _merge_remapped_value(existing_val: Any, value: Any) -> Any:
|
|
256
|
+
if isinstance(existing_val, list):
|
|
257
|
+
if isinstance(value, list):
|
|
258
|
+
return existing_val + value
|
|
259
|
+
if value not in ("", None):
|
|
260
|
+
return [*existing_val, value]
|
|
261
|
+
return existing_val
|
|
262
|
+
|
|
263
|
+
if isinstance(existing_val, str):
|
|
264
|
+
if not value:
|
|
265
|
+
return existing_val
|
|
266
|
+
new_val = ",".join(map(str, value)) if isinstance(value, list) else str(value)
|
|
267
|
+
if not existing_val:
|
|
268
|
+
return new_val
|
|
269
|
+
return f"{existing_val},{new_val}"
|
|
270
|
+
|
|
271
|
+
# Preserve non-str/non-list collisions (e.g. int + str/list) as a list
|
|
272
|
+
if value in ("", None, []):
|
|
273
|
+
return existing_val
|
|
274
|
+
if isinstance(value, list):
|
|
275
|
+
return [existing_val, *value]
|
|
276
|
+
return [existing_val, value]
|
|
277
|
+
|
|
278
|
+
def _remap_config(
|
|
279
|
+
self, decoded_config: dict[str, Any], config_fields_map: dict[int, str]
|
|
280
|
+
) -> dict[str, Any]:
|
|
281
|
+
remapped_config: dict[str, Any] = {}
|
|
282
|
+
processed_keys: set[str] = set()
|
|
283
|
+
|
|
284
|
+
for k in sorted(config_fields_map.keys()):
|
|
285
|
+
key_name = config_fields_map[k]
|
|
286
|
+
if key_name in processed_keys or key_name not in decoded_config:
|
|
287
|
+
continue
|
|
288
|
+
processed_keys.add(key_name)
|
|
289
|
+
value = decoded_config[key_name]
|
|
290
|
+
|
|
291
|
+
# Run normalization (e.g. converting HostsFE -> Hosts)
|
|
292
|
+
key_normalized, value = check_key_n_value(key_name, value)
|
|
293
|
+
|
|
294
|
+
# --- LOGIC TO APPEND INSTEAD OF OVERWRITE ---
|
|
295
|
+
if key_normalized in remapped_config:
|
|
296
|
+
remapped_config[key_normalized] = self._merge_remapped_value(
|
|
297
|
+
remapped_config[key_normalized], value
|
|
298
|
+
)
|
|
299
|
+
else:
|
|
300
|
+
# Key does not exist yet, create it
|
|
301
|
+
remapped_config[key_normalized] = value
|
|
302
|
+
|
|
303
|
+
# Ensure config items added by decryptors dynamically (e.g. hardcoded_hosts,
|
|
304
|
+
# xor_decoded_strings) are also normalized and preserved
|
|
305
|
+
for key, val in decoded_config.items():
|
|
306
|
+
if key in processed_keys:
|
|
307
|
+
continue
|
|
308
|
+
key_normalized, norm_val = check_key_n_value(key, val)
|
|
309
|
+
if key_normalized in remapped_config:
|
|
310
|
+
remapped_config[key_normalized] = self._merge_remapped_value(
|
|
311
|
+
remapped_config[key_normalized], norm_val
|
|
312
|
+
)
|
|
313
|
+
else:
|
|
314
|
+
remapped_config[key_normalized] = norm_val
|
|
315
|
+
|
|
316
|
+
return remapped_config
|
|
317
|
+
|
|
318
|
+
# Searches for the RAT configuration section, using the VerifyHash() marker
|
|
319
|
+
# or brute-force, returning the decrypted config on success
|
|
320
|
+
def _get_config(self) -> dict[str, Any]:
|
|
321
|
+
logger.debug("Extracting config...")
|
|
322
|
+
try:
|
|
323
|
+
config_start, decrypted_config = self._get_config_verify_hash_method()
|
|
324
|
+
except Exception:
|
|
325
|
+
logger.debug("VerifyHash() method failed; Attempting .cctor brute force...")
|
|
326
|
+
# If the VerifyHash() method does not work, move to brute-forcing
|
|
327
|
+
# static constructors
|
|
328
|
+
try:
|
|
329
|
+
config_start, decrypted_config = self._get_config_cctor_brute_force()
|
|
330
|
+
except Exception as e:
|
|
331
|
+
raise ConfigParserException(f"Could not identify config: {e}") from e
|
|
332
|
+
logger.debug("Config found at RVA %s...", hex(config_start))
|
|
333
|
+
if not self.preserve_obfuscated_keys and self._is_likely_obfuscated_config(
|
|
334
|
+
decrypted_config
|
|
335
|
+
):
|
|
336
|
+
logger.debug(
|
|
337
|
+
"Preserve keys set to False and possible obfuscation detected; Translating keys..."
|
|
338
|
+
)
|
|
339
|
+
decrypted_config = {
|
|
340
|
+
f"obfuscated_key_{idx}": v
|
|
341
|
+
for idx, (_, v) in enumerate(decrypted_config.items(), 1)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return decrypted_config
|
|
345
|
+
|
|
346
|
+
# Attempts to retrieve the config via brute-force, looking through every
|
|
347
|
+
# static constructor (.cctor) and attempting to decode/decrypt a valid
|
|
348
|
+
# config from that constructor, returning the config RVA and decrypted
|
|
349
|
+
# config on success
|
|
350
|
+
def _get_config_cctor_brute_force(self) -> Tuple[int, dict[str, Any]]:
|
|
351
|
+
candidates = self._dnpp.methods_from_name(".cctor")
|
|
352
|
+
if len(candidates) == 0:
|
|
353
|
+
raise ConfigParserException("No .cctor method could be found")
|
|
354
|
+
|
|
355
|
+
# Pre-extract raw config items once per .cctor method and bucket by
|
|
356
|
+
# raw item count (highest priority first) so each .cctor is parsed and
|
|
357
|
+
# decrypted at most once instead of repeating across min_config_len.
|
|
358
|
+
extracted_candidates: list[
|
|
359
|
+
tuple[
|
|
360
|
+
int,
|
|
361
|
+
list[tuple[config_item.ConfigItem, dict[str, Any]]],
|
|
362
|
+
dict[int, str],
|
|
363
|
+
int,
|
|
364
|
+
bool,
|
|
365
|
+
]
|
|
366
|
+
] = []
|
|
367
|
+
for method in candidates:
|
|
368
|
+
method_body = self._dnpp.method_body_from_method(method)
|
|
369
|
+
extracted, fields_map, raw_count = self._extract_raw_config_items(
|
|
370
|
+
method_body
|
|
371
|
+
)
|
|
372
|
+
has_url_host = any("UrlHost" in item_data for _, item_data in extracted)
|
|
373
|
+
if raw_count + 1 < self._MIN_CONFIG_LEN_FLOOR and not has_url_host:
|
|
374
|
+
continue
|
|
375
|
+
extracted_candidates.append(
|
|
376
|
+
(method.rva, extracted, fields_map, raw_count, has_url_host)
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
# Preserve original priority: >= CEILING first, then descending down to
|
|
380
|
+
# FLOOR, preserving original .cctor order within each bucket.
|
|
381
|
+
def _priority_bucket(entry: tuple) -> int:
|
|
382
|
+
raw_count, has_url_host = entry[3], entry[4]
|
|
383
|
+
if has_url_host or raw_count >= self._MIN_CONFIG_LEN_CEILING:
|
|
384
|
+
return self._MIN_CONFIG_LEN_CEILING
|
|
385
|
+
return raw_count
|
|
386
|
+
|
|
387
|
+
extracted_candidates.sort(key=_priority_bucket, reverse=True)
|
|
388
|
+
|
|
389
|
+
for method_rva, extracted, fields_map, raw_count, _ in extracted_candidates:
|
|
390
|
+
logger.debug(
|
|
391
|
+
"Attempting brute force at .cctor method at %s", hex(method_rva)
|
|
392
|
+
)
|
|
393
|
+
try:
|
|
394
|
+
decrypted_config = self._decode_extracted_config(
|
|
395
|
+
extracted,
|
|
396
|
+
fields_map,
|
|
397
|
+
raw_count,
|
|
398
|
+
self._MIN_CONFIG_LEN_FLOOR,
|
|
399
|
+
)
|
|
400
|
+
return method_rva, decrypted_config
|
|
401
|
+
except Exception as e:
|
|
402
|
+
logger.debug(
|
|
403
|
+
"Brute force failed for method at %s: %s", hex(method_rva), e
|
|
404
|
+
)
|
|
405
|
+
continue
|
|
406
|
+
|
|
407
|
+
raise ConfigParserException(
|
|
408
|
+
"No valid configuration could be parsed from any .cctor methods"
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
# Attempts to retrieve the config via looking for a config section preceded
|
|
412
|
+
# by the VerifyHash() method typically found in a Settings module,
|
|
413
|
+
# returning the config RVA and decrypted config on success
|
|
414
|
+
def _get_config_verify_hash_method(self) -> Tuple[int, dict[str, Any]]:
|
|
415
|
+
# Identify the VerifyHash() Method code
|
|
416
|
+
verify_hash_hit = search(self._PATTERN_VERIFY_HASH, self._dnpp.data)
|
|
417
|
+
if verify_hash_hit is None:
|
|
418
|
+
raise ConfigParserException("Could not identify VerifyHash() marker")
|
|
419
|
+
|
|
420
|
+
# Reverse the hit to find the VerifyHash() method, then grab the
|
|
421
|
+
# subsequent function
|
|
422
|
+
config_method = self._dnpp.method_from_instruction_offset(
|
|
423
|
+
verify_hash_hit.start(), 1
|
|
424
|
+
)
|
|
425
|
+
encrypted_config = self._dnpp.method_body_from_method(config_method)
|
|
426
|
+
decrypted_config = self._decrypt_and_decode_config(
|
|
427
|
+
encrypted_config, self._MIN_CONFIG_LEN_FLOOR
|
|
428
|
+
)
|
|
429
|
+
return config_method.rva, decrypted_config
|
|
430
|
+
|
|
431
|
+
def _is_likely_obfuscated_config(self, config: dict[str, Any]) -> bool:
|
|
432
|
+
# Order-independent check: any non-ASCII key signals obfuscation;
|
|
433
|
+
# otherwise check whether any key matches a known config field name
|
|
434
|
+
# (including underscore-stripped normalized forms).
|
|
435
|
+
has_known_key = False
|
|
436
|
+
for key in config.keys():
|
|
437
|
+
if not key.isascii():
|
|
438
|
+
return True
|
|
439
|
+
if key.replace("_", "") in KNOWN_CONFIG_FIELD_NAMES_NORMALIZED:
|
|
440
|
+
has_known_key = True
|
|
441
|
+
return not has_known_key
|