rat-king-parser 4.2.2__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.
Files changed (40) hide show
  1. {rat_king_parser-4.2.2/src/rat_king_parser.egg-info → rat_king_parser-4.2.4}/PKG-INFO +1 -1
  2. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/_version.py +1 -1
  3. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/rat_config_parser.py +77 -53
  4. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/config_item.py +1 -1
  5. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/config_normalization.py +14 -5
  6. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv.py +96 -63
  7. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/dotnetpe_payload.py +55 -21
  8. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/maco/rkp_maco.py +4 -5
  9. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4/src/rat_king_parser.egg-info}/PKG-INFO +1 -1
  10. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/LICENSE +0 -0
  11. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/README.md +0 -0
  12. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/pyproject.toml +0 -0
  13. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/setup.cfg +0 -0
  14. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/__init__.py +0 -0
  15. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/__init__.py +0 -0
  16. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/config_parser_exception.py +0 -0
  17. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/__init__.py +0 -0
  18. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/data_utils.py +0 -0
  19. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/__init__.py +0 -0
  20. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor.py +0 -0
  21. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_with_iv_pbkdf.py +0 -0
  22. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_decrypt_xor.py +0 -0
  23. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_ecb.py +0 -0
  24. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_plaintext.py +0 -0
  25. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_random_hardcoded.py +0 -0
  26. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/decryptors/config_decryptor_rijndael.py +0 -0
  27. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/config_parser/utils/dotnet_constants.py +0 -0
  28. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/__init__.py +0 -0
  29. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/extern/maco/__init__.py +0 -0
  30. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/rkp.py +0 -0
  31. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/__init__.py +0 -0
  32. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/recompile.py +0 -0
  33. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/rules.yar +0 -0
  34. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser/yara_utils/rules.yarc +0 -0
  35. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/SOURCES.txt +0 -0
  36. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/dependency_links.txt +0 -0
  37. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/entry_points.txt +0 -0
  38. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/requires.txt +0 -0
  39. {rat_king_parser-4.2.2 → rat_king_parser-4.2.4}/src/rat_king_parser.egg-info/top_level.txt +0 -0
  40. {rat_king_parser-4.2.2 → 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.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>
@@ -23,4 +23,4 @@
23
23
  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
24
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
25
  # SOFTWARE.
26
- __version__ = "4.2.2"
26
+ __version__ = "4.2.4"
@@ -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[int] = []
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
- sorted_decoded_config = OrderedDict()
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]:
@@ -132,7 +132,7 @@ class SpecialFolderConfigItem(ConfigItem):
132
132
  try:
133
133
  return SpecialFolder(bytes_to_int(folder_id)).name
134
134
  except ValueError:
135
- return None
135
+ return f"UnknownFolder({bytes_to_int(folder_id)})"
136
136
 
137
137
  class EncryptedStringConfigItem(ConfigItem):
138
138
  def __init__(self) -> None:
@@ -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
- for k, v in normalized_keys.items():
47
- if key in v:
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": CBC,
58
- b"\x1a": CFB,
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 = CBC
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 first
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
- # Otherwise, extract the IV from the 16 bytes after the HMAC
149
- # (first 32 bytes) and the ciphertext from the rest of the data
150
- # after the IV, and run the decryption
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
- key_idx = 0
154
- # Run through key candidates until suitable one found or failure
155
- while result is None and key_idx < len(self._key_candidates):
152
+
153
+ # Try the successful key first if we found one
154
+ if successful_key:
156
155
  try:
157
- self.key = self._key_candidates[key_idx]
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(self, encrypted_strings: dict[str, str]) -> list[bytes]:
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
- # Use the key Field name to index into our existing config
181
- key_raw_value = encrypted_strings[
182
- self._payload.field_name_from_rva(self._key_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
- f"Could not derive key from passphrase candidates: {passphrase_candidates}"
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
- metadata = None
278
+ self._metadata_candidates = []
247
279
  # Some payloads have multiple embedded salt values:
248
- # Find the one that is actually used for initialization
249
- for candidate in re.finditer(self._PATTERN_AES_SALT_ITER, self._payload.data):
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
- self.salt = self._get_aes_salt(candidate.groups()[0])
252
- metadata = candidate
253
- self._key_rva = self._get_aes_key_rva(metadata.start())
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(candidate.groups()[0]))} failed: {cfe}"
291
+ f"Initialization using salt candidate {hex(bytes_to_int(hit.groups()[0]))} failed: {cfe}"
257
292
  )
258
293
  continue
259
- if metadata is None:
294
+ if not self._metadata_candidates:
260
295
  raise ConfigParserException("Could not identify AES metadata")
261
- logger.debug(f"AES metadata found at offset {hex(metadata.start())}")
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
- logger.debug("Extracting AES iterations...")
267
- self._iterations = bytes_to_int(metadata.groups()[1])
268
- logger.debug(f"Found AES iteration number of {self._iterations}")
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 : arr_offset + arr_size]
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
- return self.dotnetpe.net.mdtables.Field.rows[
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
- for row in self.dotnetpe.net.mdtables.FieldRva:
126
- if row.struct.Field_Index == field_id:
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(self.dotnetpe.net.mdtables.MethodDef.rows):
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 : method_offset + 8]
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
- for idx, method in enumerate(self._methods_by_offset):
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._methods_by_token.index(method) + step]
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
  )
@@ -211,7 +233,12 @@ class DotNetPEPayload:
211
233
 
212
234
  # Given an RVA, derives the corresponding User String
213
235
  def user_string_from_rva(self, rva: int) -> str:
214
- return self.dotnetpe.net.user_strings.get(rva ^ MDT_STRING).value
236
+ result = self.dotnetpe.net.user_strings.get(rva ^ MDT_STRING)
237
+ if result is None:
238
+ raise ConfigParserException(
239
+ f"Could not find user string for RVA {hex(rva)}"
240
+ )
241
+ return result.value
215
242
 
216
243
  def custom_attribute_from_type(self, typespacename: str, typename: str) -> dict:
217
244
  """
@@ -235,22 +262,29 @@ class DotNetPEPayload:
235
262
  config = {}
236
263
  try:
237
264
  ca_map = {}
238
- for ca in self.dotnetpe.net.mdtables.CustomAttribute.rows:
239
- idx = ca.Parent.row_index
240
- if idx not in ca_map:
241
- ca_map[idx] = []
242
- ca_map[idx].append(ca)
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)
243
272
 
244
- for td in self.dotnetpe.net.mdtables.TypeDef.rows:
273
+ td_table = getattr(self.dotnetpe.net.mdtables, "TypeDef", None)
274
+ if not td_table:
275
+ return config
276
+
277
+ for td in td_table.rows:
245
278
  if (
246
279
  td.TypeNamespace.value != typespacename
247
280
  and td.TypeName.value != typename
248
281
  ):
249
282
  continue
250
- for pd_row_index, pd in enumerate(
251
- self.dotnetpe.net.mdtables.Property.rows
252
- ):
253
- if pd.Name.value.startswith(
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):
287
+ if pd.Name.value.startswith((
254
288
  "Boolean_",
255
289
  "BorderStyle_",
256
290
  "Color_",
@@ -258,7 +292,7 @@ class DotNetPEPayload:
258
292
  "Int32_",
259
293
  "SizeF_",
260
294
  "String_",
261
- ):
295
+ )):
262
296
  continue
263
297
  # CustomAttribute Parent index is 1-based
264
298
  target_index = pd_row_index + 1
@@ -30,7 +30,6 @@ from enum import Enum, auto
30
30
  from logging import getLogger
31
31
  from pathlib import Path
32
32
  from re import search
33
- from typing import Optional
34
33
 
35
34
  import validators
36
35
  from maco import extractor, model
@@ -64,13 +63,13 @@ class RKPMACO(extractor.Extractor):
64
63
  author = "jeFF0Falltrades"
65
64
  last_modified = "2024-10-18"
66
65
  sharing = "TLP:WHITE"
67
- yara_rule = open(str(Path(__file__).parent / YARA_PATH)).read()
66
+ yara_rule = (Path(__file__).parent / YARA_PATH).read_text()
68
67
 
69
68
  def run(
70
69
  self, stream: typing.BinaryIO, matches: typing.List[Match]
71
70
  ) -> typing.Optional[model.ExtractorModel]:
72
71
  report = RATConfigParser(
73
- load(str(Path(__file__).parent / YARC_PATH)),
72
+ yara_rule=load(str(Path(__file__).parent / YARC_PATH)),
74
73
  data=stream.read(),
75
74
  remap_config=True,
76
75
  ).report
@@ -191,7 +190,7 @@ class RKPMACO(extractor.Extractor):
191
190
 
192
191
  # Helper function to handle both IPv4 and IPv6 values
193
192
  def _add_tcp_ip(
194
- self, model: model.ExtractorModel, server_ip: str, server_port: Optional[int]
193
+ self, model: model.ExtractorModel, server_ip: str, server_port: typing.Optional[int]
195
194
  ) -> None:
196
195
  model.tcp.append(
197
196
  model.Connection(server_ip=server_ip, server_port=server_port, usage="c2")
@@ -201,7 +200,7 @@ class RKPMACO(extractor.Extractor):
201
200
  # suffixed to the host/IP
202
201
  def _split_network_value(
203
202
  self, network_value: str
204
- ) -> typing.Tuple[str, Optional[int]]:
203
+ ) -> typing.Tuple[str, typing.Optional[int]]:
205
204
  match = search(r":([0-9]+)$", network_value)
206
205
  if match is not None:
207
206
  try:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rat-king-parser
3
- Version: 4.2.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