rat-king-parser 4.2.3__tar.gz → 4.2.4__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.3/src/rat_king_parser.egg-info → rat_king_parser-4.2.4}/PKG-INFO +1 -1
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/_version.py +1 -1
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/rat_config_parser.py +77 -53
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/config_normalization.py +14 -5
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv.py +96 -63
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/dotnetpe_payload.py +47 -18
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4/src/rat_king_parser.egg-info}/PKG-INFO +1 -1
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/LICENSE +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/README.md +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/pyproject.toml +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/setup.cfg +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/config_parser_exception.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/config_item.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/data_utils.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv_pbkdf.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_decrypt_xor.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_ecb.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_plaintext.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_random_hardcoded.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_rijndael.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/dotnet_constants.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/maco/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/maco/rkp_maco.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/rkp.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/__init__.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/recompile.py +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/rules.yar +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/rules.yarc +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/SOURCES.txt +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/dependency_links.txt +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/entry_points.txt +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/requires.txt +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/top_level.txt +0 -0
- {rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/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.4
|
|
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>
|
|
@@ -27,7 +27,6 @@
|
|
|
27
27
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
28
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
29
|
# SOFTWARE.
|
|
30
|
-
from collections import OrderedDict
|
|
31
30
|
from logging import getLogger
|
|
32
31
|
from os.path import isfile
|
|
33
32
|
from re import DOTALL, compile, search
|
|
@@ -77,11 +76,13 @@ class RATConfigParser:
|
|
|
77
76
|
}
|
|
78
77
|
self.remap_config = remap_config
|
|
79
78
|
self.preserve_obfuscated_keys = preserve_obfuscated_keys
|
|
79
|
+
self._dnpp: DotNetPEPayload | None = None
|
|
80
|
+
self._decryptor: ConfigDecryptor | None = None
|
|
80
81
|
try:
|
|
81
82
|
if data is None and not isfile(file_path):
|
|
82
83
|
raise ConfigParserException("File not found")
|
|
83
84
|
# Filled in _decrypt_and_decode_config()
|
|
84
|
-
self._incompatible_decryptors: list[
|
|
85
|
+
self._incompatible_decryptors: list[Any] = []
|
|
85
86
|
try:
|
|
86
87
|
self._dnpp = DotNetPEPayload(file_path, yara_rule, data)
|
|
87
88
|
except Exception as e:
|
|
@@ -90,7 +91,6 @@ class RATConfigParser:
|
|
|
90
91
|
self.report["yara_possible_family"] = self._dnpp.yara_match
|
|
91
92
|
|
|
92
93
|
# Assigned in _decrypt_and_decode_config()
|
|
93
|
-
self._decryptor: ConfigDecryptor = None
|
|
94
94
|
self.report["config"] = self._get_config()
|
|
95
95
|
key_hex = "None"
|
|
96
96
|
if self._decryptor is not None and self._decryptor.key is not None:
|
|
@@ -128,38 +128,7 @@ class RATConfigParser:
|
|
|
128
128
|
# Translate config value RVAs to string values
|
|
129
129
|
for k in item_data:
|
|
130
130
|
item_data[k] = self._dnpp.user_string_from_rva(item_data[k])
|
|
131
|
-
|
|
132
|
-
# Attempt to decrypt encrypted values
|
|
133
|
-
for decryptor in SUPPORTED_DECRYPTORS:
|
|
134
|
-
if decryptor in self._incompatible_decryptors:
|
|
135
|
-
continue
|
|
136
|
-
|
|
137
|
-
if self._decryptor is None:
|
|
138
|
-
# Try to instantiate the selected decryptor
|
|
139
|
-
# Add to incompatible list and move on upon failure
|
|
140
|
-
try:
|
|
141
|
-
self._decryptor = decryptor(self._dnpp)
|
|
142
|
-
except IncompatibleDecryptorException as ide:
|
|
143
|
-
logger.debug(
|
|
144
|
-
f"Decryptor incompatible {decryptor} : {ide}"
|
|
145
|
-
)
|
|
146
|
-
self._incompatible_decryptors.append(decryptor)
|
|
147
|
-
continue
|
|
148
|
-
try:
|
|
149
|
-
# Try to decrypt the encrypted strings
|
|
150
|
-
# Continue to next compatible decryptor on failure
|
|
151
|
-
item_data = self._decryptor.decrypt_encrypted_strings(
|
|
152
|
-
item_data
|
|
153
|
-
)
|
|
154
|
-
break
|
|
155
|
-
except Exception as e:
|
|
156
|
-
logger.debug(
|
|
157
|
-
f"Decryption failed with decryptor {decryptor} : {e}"
|
|
158
|
-
)
|
|
159
|
-
self._decryptor = None
|
|
160
|
-
|
|
161
|
-
if self._decryptor is None:
|
|
162
|
-
raise ConfigParserException("All decryptors failed")
|
|
131
|
+
item_data = self._attempt_decryption(item_data)
|
|
163
132
|
|
|
164
133
|
elif isinstance(item, config_item.ByteArrayConfigItem):
|
|
165
134
|
for k in item_data:
|
|
@@ -169,32 +138,87 @@ class RATConfigParser:
|
|
|
169
138
|
).hex()
|
|
170
139
|
|
|
171
140
|
decoded_config.update(item_data)
|
|
141
|
+
|
|
172
142
|
# UrlHost is a marker of a special case until this can be standardized
|
|
173
143
|
if len(decoded_config) < min_config_len and "UrlHost" not in decoded_config:
|
|
174
144
|
raise ConfigParserException(
|
|
175
145
|
f"Minimum threshold of config items not met: {len(decoded_config)}/{min_config_len}"
|
|
176
146
|
)
|
|
177
147
|
if self.remap_config:
|
|
178
|
-
|
|
179
|
-
normalized_fields = []
|
|
180
|
-
for k in sorted(config_fields_map.keys()):
|
|
181
|
-
key_name = config_fields_map[k]
|
|
182
|
-
value = decoded_config[key_name]
|
|
183
|
-
key_normalized, value = check_key_n_value(key_name, value)
|
|
184
|
-
if key_normalized != key_name:
|
|
185
|
-
normalized_fields.append(key_name)
|
|
186
|
-
sorted_decoded_config[key_normalized] = value
|
|
187
|
-
# Ensure config items added by decryptors dynamically are preserved
|
|
188
|
-
sorted_decoded_config.update(
|
|
189
|
-
{
|
|
190
|
-
key: decoded_config[key]
|
|
191
|
-
for key in decoded_config
|
|
192
|
-
if key not in sorted_decoded_config and key not in normalized_fields
|
|
193
|
-
}
|
|
194
|
-
)
|
|
195
|
-
return sorted_decoded_config
|
|
148
|
+
return self._remap_config(decoded_config, config_fields_map)
|
|
196
149
|
return decoded_config
|
|
197
150
|
|
|
151
|
+
def _attempt_decryption(self, item_data: dict[str, Any]) -> dict[str, Any]:
|
|
152
|
+
# Attempt to decrypt encrypted values
|
|
153
|
+
for decryptor in SUPPORTED_DECRYPTORS:
|
|
154
|
+
if decryptor in self._incompatible_decryptors:
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
if self._decryptor is None:
|
|
158
|
+
# Try to instantiate the selected decryptor
|
|
159
|
+
# Add to incompatible list and move on upon failure
|
|
160
|
+
try:
|
|
161
|
+
self._decryptor = decryptor(self._dnpp)
|
|
162
|
+
except IncompatibleDecryptorException as ide:
|
|
163
|
+
logger.debug(f"Decryptor incompatible {decryptor} : {ide}")
|
|
164
|
+
self._incompatible_decryptors.append(decryptor)
|
|
165
|
+
continue
|
|
166
|
+
try:
|
|
167
|
+
# Try to decrypt the encrypted strings
|
|
168
|
+
# Continue to next compatible decryptor on failure
|
|
169
|
+
return self._decryptor.decrypt_encrypted_strings(item_data)
|
|
170
|
+
except Exception as e:
|
|
171
|
+
logger.debug(f"Decryption failed with decryptor {decryptor} : {e}")
|
|
172
|
+
self._decryptor = None
|
|
173
|
+
|
|
174
|
+
# If we exit the loop without returning, no decryptor succeeded
|
|
175
|
+
raise ConfigParserException("All decryptors failed")
|
|
176
|
+
|
|
177
|
+
def _remap_config(
|
|
178
|
+
self, decoded_config: dict[str, Any], config_fields_map: dict[int, str]
|
|
179
|
+
) -> dict[str, Any]:
|
|
180
|
+
remapped_config = {}
|
|
181
|
+
normalized_fields = []
|
|
182
|
+
for k in sorted(config_fields_map.keys()):
|
|
183
|
+
key_name = config_fields_map[k]
|
|
184
|
+
value = decoded_config[key_name]
|
|
185
|
+
|
|
186
|
+
# Run your normalization (e.g. converting HostsFE -> Hosts)
|
|
187
|
+
key_normalized, value = check_key_n_value(key_name, value)
|
|
188
|
+
|
|
189
|
+
if key_normalized != key_name:
|
|
190
|
+
normalized_fields.append(key_name)
|
|
191
|
+
|
|
192
|
+
# --- LOGIC TO APPEND INSTEAD OF OVERWRITE ---
|
|
193
|
+
if key_normalized in remapped_config:
|
|
194
|
+
existing_val = remapped_config[key_normalized]
|
|
195
|
+
|
|
196
|
+
# Case 1: Values are Strings (e.g. "1.2.3.4:80")
|
|
197
|
+
if isinstance(existing_val, str) and value:
|
|
198
|
+
# Append with a comma separator
|
|
199
|
+
new_val = ",".join(map(str, value)) if isinstance(value, list) else value
|
|
200
|
+
remapped_config[key_normalized] = f"{existing_val},{new_val}"
|
|
201
|
+
|
|
202
|
+
# Case 2: Values are Lists (e.g. ["1.2.3.4:80"])
|
|
203
|
+
elif isinstance(existing_val, list):
|
|
204
|
+
# If the new value is also a list, extend; otherwise append
|
|
205
|
+
if isinstance(value, list):
|
|
206
|
+
remapped_config[key_normalized] = existing_val + value
|
|
207
|
+
else:
|
|
208
|
+
remapped_config[key_normalized].append(value)
|
|
209
|
+
else:
|
|
210
|
+
# Key does not exist yet, create it
|
|
211
|
+
remapped_config[key_normalized] = value
|
|
212
|
+
# Ensure config items added by decryptors dynamically are preserved
|
|
213
|
+
remapped_config.update(
|
|
214
|
+
{
|
|
215
|
+
key: decoded_config[key]
|
|
216
|
+
for key in decoded_config
|
|
217
|
+
if key not in remapped_config and key not in normalized_fields
|
|
218
|
+
}
|
|
219
|
+
)
|
|
220
|
+
return remapped_config
|
|
221
|
+
|
|
198
222
|
# Searches for the RAT configuration section, using the VerifyHash() marker
|
|
199
223
|
# or brute-force, returning the decrypted config on success
|
|
200
224
|
def _get_config(self) -> dict[str, Any]:
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
from typing import Any
|
|
32
32
|
|
|
33
33
|
normalized_keys = {
|
|
34
|
-
"Hosts": ("HOSTS", "Hosts", "ServerIp", "hardcodedhosts", "PasteUrl"),
|
|
34
|
+
"Hosts": ("HOSTS", "Hosts", "HostsFE", "ServerIp", "hardcodedhosts", "PasteUrl"),
|
|
35
35
|
"Ports": ("Port", "Ports", "ServerPort"),
|
|
36
36
|
"Mutex": ("MTX", "MUTEX", "Mutex", "mutex_string"),
|
|
37
37
|
"Version": ("VERSION", "Version"),
|
|
@@ -39,14 +39,23 @@ normalized_keys = {
|
|
|
39
39
|
"Group": ("Group", "Groub", "GroupTag", "TAG"),
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
# Strip underscores from aliases at build time so the lookup is consistent
|
|
43
|
+
# with the underscore-stripped input key (e.g. so "mutex_string" actually
|
|
44
|
+
# resolves to "Mutex")
|
|
45
|
+
_normalized_keys_map = {
|
|
46
|
+
alias.replace("_", ""): k
|
|
47
|
+
for k, aliases in normalized_keys.items()
|
|
48
|
+
for alias in aliases
|
|
49
|
+
}
|
|
50
|
+
|
|
42
51
|
|
|
43
52
|
# Normalizes config keys/values for easier mapping
|
|
44
53
|
def check_key_n_value(key: str, value: Any) -> tuple[str, Any]:
|
|
54
|
+
# Always strip underscores from the returned key to preserve the prior
|
|
55
|
+
# behavior of this function for unrecognized keys
|
|
45
56
|
key = key.replace("_", "")
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
key = k
|
|
49
|
-
break
|
|
57
|
+
if key in _normalized_keys_map:
|
|
58
|
+
key = _normalized_keys_map[key]
|
|
50
59
|
|
|
51
60
|
if key in ("Hosts", "Ports") and isinstance(value, str):
|
|
52
61
|
if value not in ("null", "false"):
|
|
@@ -36,8 +36,6 @@ from logging import getLogger
|
|
|
36
36
|
from typing import Tuple
|
|
37
37
|
|
|
38
38
|
from Cryptodome.Cipher import AES
|
|
39
|
-
from Cryptodome.Cipher.AES import MODE_CBC as CBC
|
|
40
|
-
from Cryptodome.Cipher.AES import MODE_CFB as CFB
|
|
41
39
|
from Cryptodome.Protocol.KDF import PBKDF2
|
|
42
40
|
from Cryptodome.Util.Padding import unpad
|
|
43
41
|
|
|
@@ -54,8 +52,8 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
54
52
|
# Minimum length of valid ciphertext
|
|
55
53
|
_MIN_CIPHERTEXT_LEN = 48
|
|
56
54
|
_ALGO_MAP = {
|
|
57
|
-
b"\x17":
|
|
58
|
-
b"\x1a":
|
|
55
|
+
b"\x17": AES.MODE_CBC,
|
|
56
|
+
b"\x1a": AES.MODE_CFB,
|
|
59
57
|
}
|
|
60
58
|
|
|
61
59
|
# Patterns for identifying AES metadata
|
|
@@ -66,9 +64,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
66
64
|
# Do not re.compile in-line replacement patterns
|
|
67
65
|
_PATTERN_AES_KEY_BASE = b"(.{3}\x04).%b"
|
|
68
66
|
_PATTERN_AES_SALT_INIT = b"\x80%b\x2a"
|
|
69
|
-
_PATTERN_AES_SALT_ITER = re.compile(
|
|
70
|
-
b"[\x02-\x05]\x7e(.{4})\x20(.{4})\x73", re.DOTALL
|
|
71
|
-
)
|
|
67
|
+
_PATTERN_AES_SALT_ITER = re.compile(b"[\x02-\x05]\x7e(.{4})\x20(.{4})\x73", re.DOTALL)
|
|
72
68
|
|
|
73
69
|
def __init__(self, payload: DotNetPEPayload) -> None:
|
|
74
70
|
super().__init__(payload)
|
|
@@ -77,7 +73,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
77
73
|
self._key_candidates: list[bytes] = None
|
|
78
74
|
self._key_size: int = None
|
|
79
75
|
self._key_rva: int = None
|
|
80
|
-
self._aes_algo =
|
|
76
|
+
self._aes_algo = AES.MODE_CBC
|
|
81
77
|
try:
|
|
82
78
|
self._get_aes_metadata()
|
|
83
79
|
except Exception as e:
|
|
@@ -89,19 +85,16 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
89
85
|
logger.debug(
|
|
90
86
|
f"Decrypting {ciphertext} with key {self.key.hex()} and IV {iv.hex()}..."
|
|
91
87
|
)
|
|
92
|
-
|
|
93
88
|
cipher = AES.new(self.key, mode=self._aes_algo, iv=iv)
|
|
94
89
|
|
|
95
|
-
unpadded_text = ""
|
|
96
90
|
padded_text = cipher.decrypt(ciphertext)
|
|
97
91
|
try:
|
|
98
|
-
# Attempt to unpad
|
|
92
|
+
# Attempt to unpad
|
|
99
93
|
unpadded_text = unpad(padded_text, AES.block_size)
|
|
100
94
|
except Exception as e:
|
|
101
95
|
raise ConfigParserException(
|
|
102
96
|
f"Error decrypting ciphertext {ciphertext} with IV {iv.hex()} and key {self.key.hex()} : {e}"
|
|
103
97
|
)
|
|
104
|
-
|
|
105
98
|
logger.debug(f"Decryption result: {unpadded_text}")
|
|
106
99
|
return unpadded_text
|
|
107
100
|
|
|
@@ -125,6 +118,10 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
125
118
|
self._key_candidates = self._get_aes_key_candidates(encrypted_strings)
|
|
126
119
|
|
|
127
120
|
decrypted_config_strings = {}
|
|
121
|
+
attempted_decryptions = 0
|
|
122
|
+
successfully_decrypted_count = 0
|
|
123
|
+
successful_key = None
|
|
124
|
+
|
|
128
125
|
for k, v in encrypted_strings.items():
|
|
129
126
|
# Leave empty strings as they are
|
|
130
127
|
if len(v) == 0:
|
|
@@ -145,64 +142,101 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
145
142
|
decrypted_config_strings[k] = v
|
|
146
143
|
continue
|
|
147
144
|
|
|
148
|
-
#
|
|
149
|
-
|
|
150
|
-
#
|
|
145
|
+
# Past this point we are actually attempting a decryption
|
|
146
|
+
attempted_decryptions += 1
|
|
147
|
+
# Extract the IV from the 16 bytes after the HMAC (first 32 bytes)
|
|
148
|
+
# and the ciphertext from the rest of the data after the IV, and
|
|
149
|
+
# run the decryption
|
|
151
150
|
iv, ciphertext = decoded_val[32:48], decoded_val[48:]
|
|
152
151
|
result, last_exc = None, None
|
|
153
|
-
|
|
154
|
-
#
|
|
155
|
-
|
|
152
|
+
|
|
153
|
+
# Try the successful key first if we found one
|
|
154
|
+
if successful_key:
|
|
156
155
|
try:
|
|
157
|
-
self.key =
|
|
158
|
-
key_idx += 1
|
|
156
|
+
self.key = successful_key
|
|
159
157
|
result = decode_bytes(self._decrypt(iv, ciphertext))
|
|
160
|
-
except ConfigParserException as e:
|
|
158
|
+
except (ValueError, ConfigParserException) as e:
|
|
161
159
|
last_exc = e
|
|
160
|
+
result = None
|
|
161
|
+
|
|
162
|
+
# Run through key candidates until suitable one found or failure
|
|
163
|
+
if result is None:
|
|
164
|
+
for candidate_key in self._key_candidates:
|
|
165
|
+
if candidate_key == successful_key:
|
|
166
|
+
continue
|
|
167
|
+
try:
|
|
168
|
+
self.key = candidate_key
|
|
169
|
+
result = decode_bytes(self._decrypt(iv, ciphertext))
|
|
170
|
+
successful_key = candidate_key
|
|
171
|
+
break
|
|
172
|
+
except (ValueError, ConfigParserException) as e:
|
|
173
|
+
last_exc = e
|
|
162
174
|
|
|
163
175
|
if result is None:
|
|
164
176
|
logger.debug(
|
|
165
177
|
f"Decryption failed for item {v}: {last_exc}; Leaving as original value..."
|
|
166
178
|
)
|
|
167
179
|
result = v
|
|
180
|
+
else:
|
|
181
|
+
successfully_decrypted_count += 1
|
|
168
182
|
|
|
169
183
|
logger.debug(f"Key: {k}, Value: {result}")
|
|
170
184
|
decrypted_config_strings[k] = result
|
|
171
185
|
|
|
186
|
+
# Only raise if we actually tried to decrypt at least one string and
|
|
187
|
+
# none succeeded. Template/builder samples have 0 attempts (all values
|
|
188
|
+
# are placeholders that fail the b64/length filter above), and should
|
|
189
|
+
# fall through cleanly so this AES decryptor remains the active one
|
|
190
|
+
# and its salt is still reported.
|
|
191
|
+
if attempted_decryptions > 0 and successfully_decrypted_count == 0:
|
|
192
|
+
raise ConfigParserException(
|
|
193
|
+
"No strings could be decrypted with the available keys"
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# Set the key to the successful one for reporting
|
|
197
|
+
if successful_key:
|
|
198
|
+
self.key = successful_key
|
|
199
|
+
|
|
172
200
|
logger.debug("Successfully decrypted strings")
|
|
173
201
|
return decrypted_config_strings
|
|
174
202
|
|
|
175
203
|
# Extracts AES key candidates from the payload
|
|
176
|
-
def _get_aes_key_candidates(
|
|
204
|
+
def _get_aes_key_candidates(
|
|
205
|
+
self, encrypted_strings: dict[str, str]
|
|
206
|
+
) -> list[bytes]:
|
|
177
207
|
logger.debug("Extracting AES key candidates...")
|
|
178
208
|
keys = []
|
|
179
209
|
|
|
180
|
-
#
|
|
181
|
-
|
|
182
|
-
self._payload.field_name_from_rva(
|
|
183
|
-
|
|
184
|
-
passphrase_candidates = self._derive_aes_passphrase_candidates(key_raw_value)
|
|
185
|
-
|
|
186
|
-
for candidate in passphrase_candidates:
|
|
187
|
-
try:
|
|
188
|
-
key = PBKDF2(candidate, self.salt, self._key_size, self._iterations)
|
|
189
|
-
keys.append(key)
|
|
190
|
-
logger.debug(f"AES key derived: {keys[-1]}")
|
|
191
|
-
except Exception as e:
|
|
192
|
-
logger.debug(f"Error in key generation: {e}")
|
|
210
|
+
# We need to try all combinations of metadata candidates and their passphrase candidates
|
|
211
|
+
for meta in self._metadata_candidates:
|
|
212
|
+
field_name = self._payload.field_name_from_rva(meta["key_rva"])
|
|
213
|
+
if field_name not in encrypted_strings:
|
|
193
214
|
continue
|
|
215
|
+
|
|
216
|
+
key_raw_value = encrypted_strings[field_name]
|
|
217
|
+
passphrase_candidates = self._derive_aes_passphrase_candidates(key_raw_value)
|
|
218
|
+
|
|
219
|
+
for candidate in passphrase_candidates:
|
|
220
|
+
try:
|
|
221
|
+
key = PBKDF2(
|
|
222
|
+
candidate, meta["salt"], self._key_size, meta["iterations"]
|
|
223
|
+
)
|
|
224
|
+
if key not in keys:
|
|
225
|
+
keys.append(key)
|
|
226
|
+
logger.debug(f"AES key derived: {key.hex()}")
|
|
227
|
+
except Exception as e:
|
|
228
|
+
logger.debug(f"Error in key generation: {e}")
|
|
229
|
+
continue
|
|
194
230
|
if len(keys) == 0:
|
|
195
231
|
raise ConfigParserException(
|
|
196
|
-
|
|
232
|
+
"Could not derive key from any metadata candidate"
|
|
197
233
|
)
|
|
198
234
|
return keys
|
|
199
235
|
|
|
200
236
|
# Extracts the AES key and block size from the payload
|
|
201
237
|
def _get_aes_key_and_block_size_and_algo(self) -> Tuple[int, int, int]:
|
|
202
238
|
logger.debug("Extracting AES key and block size...")
|
|
203
|
-
hit = re.search(
|
|
204
|
-
self._PATTERN_AES_KEY_AND_BLOCK_SIZE_AND_ALGO, self._payload.data
|
|
205
|
-
)
|
|
239
|
+
hit = re.search(self._PATTERN_AES_KEY_AND_BLOCK_SIZE_AND_ALGO, self._payload.data)
|
|
206
240
|
if hit is None:
|
|
207
241
|
raise ConfigParserException("Could not extract AES key or block size")
|
|
208
242
|
|
|
@@ -222,9 +256,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
222
256
|
logger.debug("Extracting AES key RVA...")
|
|
223
257
|
|
|
224
258
|
# Get the RVA of the method that sets up AES256 metadata
|
|
225
|
-
metadata_method_token = self._payload.method_from_instruction_offset(
|
|
226
|
-
metadata_ins_offset, by_token=True
|
|
227
|
-
).token
|
|
259
|
+
metadata_method_token = self._payload.method_from_instruction_offset(metadata_ins_offset, by_token=True).token
|
|
228
260
|
# Insert this RVA into the KEY_BASE pattern to find where the AES key
|
|
229
261
|
# is initialized
|
|
230
262
|
key_hit = re.search(
|
|
@@ -243,29 +275,36 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
243
275
|
# sets the necessary values needed for decryption
|
|
244
276
|
def _get_aes_metadata(self) -> None:
|
|
245
277
|
logger.debug("Extracting AES metadata...")
|
|
246
|
-
|
|
278
|
+
self._metadata_candidates = []
|
|
247
279
|
# Some payloads have multiple embedded salt values:
|
|
248
|
-
# Find the
|
|
249
|
-
for
|
|
280
|
+
# Find the ones that are actually used for initialization
|
|
281
|
+
for hit in re.finditer(self._PATTERN_AES_SALT_ITER, self._payload.data):
|
|
250
282
|
try:
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
283
|
+
salt = self._get_aes_salt(hit.groups()[0])
|
|
284
|
+
key_rva = self._get_aes_key_rva(hit.start())
|
|
285
|
+
iterations = bytes_to_int(hit.groups()[1])
|
|
286
|
+
self._metadata_candidates.append(
|
|
287
|
+
{"salt": salt, "key_rva": key_rva, "iterations": iterations}
|
|
288
|
+
)
|
|
254
289
|
except ConfigParserException as cfe:
|
|
255
290
|
logger.info(
|
|
256
|
-
f"Initialization using salt candidate {hex(bytes_to_int(
|
|
291
|
+
f"Initialization using salt candidate {hex(bytes_to_int(hit.groups()[0]))} failed: {cfe}"
|
|
257
292
|
)
|
|
258
293
|
continue
|
|
259
|
-
if
|
|
294
|
+
if not self._metadata_candidates:
|
|
260
295
|
raise ConfigParserException("Could not identify AES metadata")
|
|
261
|
-
|
|
296
|
+
|
|
297
|
+
# Key size, block size, and algo are properties of the embedded AES
|
|
298
|
+
# class definition, not of any single salt/iter candidate, so they are
|
|
299
|
+
# extracted once and shared across all metadata candidates
|
|
262
300
|
self._key_size, self._block_size, self._aes_algo = (
|
|
263
301
|
self._get_aes_key_and_block_size_and_algo()
|
|
264
302
|
)
|
|
265
303
|
|
|
266
|
-
|
|
267
|
-
self.
|
|
268
|
-
|
|
304
|
+
# Legacy fields for backward compatibility, use first valid candidate
|
|
305
|
+
self.salt = self._metadata_candidates[0]["salt"]
|
|
306
|
+
self._key_rva = self._metadata_candidates[0]["key_rva"]
|
|
307
|
+
self._iterations = self._metadata_candidates[0]["iterations"]
|
|
269
308
|
|
|
270
309
|
# Extracts the AES salt from the payload, accounting for both hardcoded
|
|
271
310
|
# salt byte arrays, and salts derived from hardcoded strings
|
|
@@ -278,9 +317,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
278
317
|
#
|
|
279
318
|
# stsfld uint8[] Client.Algorithm.Aes256::Salt
|
|
280
319
|
# ret
|
|
281
|
-
aes_salt_initialization = self._payload.data.find(
|
|
282
|
-
self._PATTERN_AES_SALT_INIT % salt_rva
|
|
283
|
-
)
|
|
320
|
+
aes_salt_initialization = self._payload.data.find(self._PATTERN_AES_SALT_INIT % salt_rva)
|
|
284
321
|
if aes_salt_initialization == -1:
|
|
285
322
|
raise ConfigParserException("Could not identify AES salt initialization")
|
|
286
323
|
|
|
@@ -292,9 +329,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
292
329
|
salt_op = bytes([self._payload.data[salt_op_offset]])
|
|
293
330
|
|
|
294
331
|
# Get the salt RVA from the 4 bytes following the initialization op
|
|
295
|
-
salt_strings_rva_packed = self._payload.data[
|
|
296
|
-
salt_op_offset + 1 : salt_op_offset + 5
|
|
297
|
-
]
|
|
332
|
+
salt_strings_rva_packed = self._payload.data[salt_op_offset + 1 : salt_op_offset + 5]
|
|
298
333
|
salt_strings_rva = bytes_to_int(salt_strings_rva_packed)
|
|
299
334
|
|
|
300
335
|
# If the op is a ldstr op, just get the bytes value of the string being
|
|
@@ -309,9 +344,7 @@ class ConfigDecryptorAESWithIV(ConfigDecryptor):
|
|
|
309
344
|
# byte array value from the FieldRVA table
|
|
310
345
|
elif salt_op == OPCODE_LDTOKEN:
|
|
311
346
|
salt_size = self._payload.data[salt_op_offset - 7]
|
|
312
|
-
salt = self._payload.byte_array_from_size_and_rva(
|
|
313
|
-
salt_size, salt_strings_rva
|
|
314
|
-
)
|
|
347
|
+
salt = self._payload.byte_array_from_size_and_rva(salt_size, salt_strings_rva)
|
|
315
348
|
else:
|
|
316
349
|
raise ConfigParserException(f"Unknown salt opcode found: {salt_op.hex()}")
|
|
317
350
|
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
29
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
30
|
# SOFTWARE.
|
|
31
|
+
from bisect import bisect_right
|
|
31
32
|
from dataclasses import dataclass
|
|
32
33
|
from hashlib import sha256
|
|
33
34
|
from logging import getLogger
|
|
@@ -72,6 +73,8 @@ class DotNetPEPayload:
|
|
|
72
73
|
self.dotnetpe = dnPE(data=self.data, clr_lazy_load=True)
|
|
73
74
|
else:
|
|
74
75
|
self.dotnetpe = dnPE(self.file_path, clr_lazy_load=True)
|
|
76
|
+
if not self.dotnetpe.net or not self.dotnetpe.net.mdtables:
|
|
77
|
+
raise ConfigParserException("Failed to load project as dotnet executable (missing Metadata)")
|
|
75
78
|
except Exception:
|
|
76
79
|
raise ConfigParserException("Failed to load project as dotnet executable")
|
|
77
80
|
|
|
@@ -83,13 +86,23 @@ class DotNetPEPayload:
|
|
|
83
86
|
self._methods = self._generate_method_list()
|
|
84
87
|
self._methods_by_offset = sorted(self._methods, key=lambda m: m.offset)
|
|
85
88
|
self._methods_by_token = sorted(self._methods, key=lambda m: m.token)
|
|
89
|
+
self._offsets = [m.offset for m in self._methods_by_offset]
|
|
90
|
+
self._tokens = [m.token for m in self._methods_by_token]
|
|
91
|
+
|
|
92
|
+
# Pre-compute FieldRva mapping for O(1) lookups
|
|
93
|
+
self._field_rva_map = {}
|
|
94
|
+
if getattr(self.dotnetpe.net.mdtables, "FieldRva", None):
|
|
95
|
+
self._field_rva_map = {
|
|
96
|
+
row.struct.Field_Index: row.struct.Rva
|
|
97
|
+
for row in self.dotnetpe.net.mdtables.FieldRva
|
|
98
|
+
}
|
|
86
99
|
|
|
87
100
|
# Given a byte array's size and RVA, translates the RVA to the offset of
|
|
88
101
|
# the byte array and returns the bytes of the array as a byte string
|
|
89
102
|
def byte_array_from_size_and_rva(self, arr_size: int, arr_rva: int) -> bytes:
|
|
90
103
|
arr_field_rva = self.fieldrva_from_rva(arr_rva)
|
|
91
104
|
arr_offset = self.offset_from_rva(arr_field_rva)
|
|
92
|
-
return self.data[arr_offset
|
|
105
|
+
return self.data[arr_offset: arr_offset + arr_size]
|
|
93
106
|
|
|
94
107
|
# Given an offset, and either a terminating offset or delimiter, extracts
|
|
95
108
|
# the byte string
|
|
@@ -113,7 +126,10 @@ class DotNetPEPayload:
|
|
|
113
126
|
# Given an RVA, derives the corresponding Field name
|
|
114
127
|
def field_name_from_rva(self, rva: int) -> str:
|
|
115
128
|
try:
|
|
116
|
-
|
|
129
|
+
field_table = getattr(self.dotnetpe.net.mdtables, "Field", None)
|
|
130
|
+
if not field_table:
|
|
131
|
+
raise ConfigParserException(f"Could not find Field table for RVA {rva}")
|
|
132
|
+
return field_table.rows[
|
|
117
133
|
(rva ^ MDT_FIELD_DEF) - 1
|
|
118
134
|
].Name.value
|
|
119
135
|
except Exception:
|
|
@@ -122,9 +138,8 @@ class DotNetPEPayload:
|
|
|
122
138
|
# Given an RVA, derives the corresponding FieldRVA value
|
|
123
139
|
def fieldrva_from_rva(self, rva: int) -> int:
|
|
124
140
|
field_id = rva ^ MDT_FIELD_DEF
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
return row.struct.Rva
|
|
141
|
+
if field_id in self._field_rva_map:
|
|
142
|
+
return self._field_rva_map[field_id]
|
|
128
143
|
raise ConfigParserException(f"Could not find FieldRVA for RVA {rva}")
|
|
129
144
|
|
|
130
145
|
# Generates a list of DotNetPEMethod objects for efficient lookups of method
|
|
@@ -133,8 +148,11 @@ class DotNetPEPayload:
|
|
|
133
148
|
self,
|
|
134
149
|
) -> list[DotNetPEMethod]:
|
|
135
150
|
method_objs = []
|
|
151
|
+
method_def_table = getattr(self.dotnetpe.net.mdtables, "MethodDef", None)
|
|
152
|
+
if not method_def_table:
|
|
153
|
+
return method_objs
|
|
136
154
|
|
|
137
|
-
for idx, method in enumerate(
|
|
155
|
+
for idx, method in enumerate(method_def_table.rows):
|
|
138
156
|
method_offset = self.offset_from_rva(method.Rva)
|
|
139
157
|
|
|
140
158
|
# Parse size from flags
|
|
@@ -144,7 +162,7 @@ class DotNetPEPayload:
|
|
|
144
162
|
method_size = flags >> 2
|
|
145
163
|
elif flags & 3 == 3: # Fat format (add 12-byte header)
|
|
146
164
|
method_size = 12 + bytes_to_int(
|
|
147
|
-
self.data[method_offset + 4
|
|
165
|
+
self.data[method_offset + 4: method_offset + 8]
|
|
148
166
|
)
|
|
149
167
|
|
|
150
168
|
method_objs.append(
|
|
@@ -194,10 +212,14 @@ class DotNetPEPayload:
|
|
|
194
212
|
def method_from_instruction_offset(
|
|
195
213
|
self, ins_offset: int, step: int = 0, by_token: bool = False
|
|
196
214
|
) -> DotNetPEMethod:
|
|
197
|
-
|
|
215
|
+
idx = bisect_right(self._offsets, ins_offset) - 1
|
|
216
|
+
if idx >= 0:
|
|
217
|
+
method = self._methods_by_offset[idx]
|
|
198
218
|
if method.offset <= ins_offset < method.offset + method.size:
|
|
219
|
+
if step == 0:
|
|
220
|
+
return method
|
|
199
221
|
return (
|
|
200
|
-
self._methods_by_token[self.
|
|
222
|
+
self._methods_by_token[bisect_right(self._tokens, method.token) - 1 + step]
|
|
201
223
|
if by_token
|
|
202
224
|
else self._methods_by_offset[idx + step]
|
|
203
225
|
)
|
|
@@ -240,21 +262,28 @@ class DotNetPEPayload:
|
|
|
240
262
|
config = {}
|
|
241
263
|
try:
|
|
242
264
|
ca_map = {}
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
265
|
+
ca_table = getattr(self.dotnetpe.net.mdtables, "CustomAttribute", None)
|
|
266
|
+
if ca_table:
|
|
267
|
+
for ca in ca_table.rows:
|
|
268
|
+
idx = ca.Parent.row_index
|
|
269
|
+
if idx not in ca_map:
|
|
270
|
+
ca_map[idx] = []
|
|
271
|
+
ca_map[idx].append(ca)
|
|
272
|
+
|
|
273
|
+
td_table = getattr(self.dotnetpe.net.mdtables, "TypeDef", None)
|
|
274
|
+
if not td_table:
|
|
275
|
+
return config
|
|
248
276
|
|
|
249
|
-
for td in
|
|
277
|
+
for td in td_table.rows:
|
|
250
278
|
if (
|
|
251
279
|
td.TypeNamespace.value != typespacename
|
|
252
280
|
and td.TypeName.value != typename
|
|
253
281
|
):
|
|
254
282
|
continue
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
283
|
+
prop_table = getattr(self.dotnetpe.net.mdtables, "Property", None)
|
|
284
|
+
if not prop_table:
|
|
285
|
+
continue
|
|
286
|
+
for pd_row_index, pd in enumerate(prop_table.rows):
|
|
258
287
|
if pd.Name.value.startswith((
|
|
259
288
|
"Boolean_",
|
|
260
289
|
"BorderStyle_",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rat-king-parser
|
|
3
|
-
Version: 4.2.
|
|
3
|
+
Version: 4.2.4
|
|
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>
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{rat_king_parser-4.2.3 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|