rat-king-parser 3.1.3__py3-none-any.whl

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 (31) hide show
  1. rat_king_parser/__init__.py +28 -0
  2. rat_king_parser/_version.py +26 -0
  3. rat_king_parser/config_parser/__init__.py +28 -0
  4. rat_king_parser/config_parser/config_parser_exception.py +31 -0
  5. rat_king_parser/config_parser/rat_config_parser.py +251 -0
  6. rat_king_parser/config_parser/utils/__init__.py +25 -0
  7. rat_king_parser/config_parser/utils/config_item.py +151 -0
  8. rat_king_parser/config_parser/utils/data_utils.py +64 -0
  9. rat_king_parser/config_parser/utils/decryptors/__init__.py +50 -0
  10. rat_king_parser/config_parser/utils/decryptors/config_decryptor.py +55 -0
  11. rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_cbc.py +319 -0
  12. rat_king_parser/config_parser/utils/decryptors/config_decryptor_aes_ecb.py +156 -0
  13. rat_king_parser/config_parser/utils/decryptors/config_decryptor_decrypt_xor.py +128 -0
  14. rat_king_parser/config_parser/utils/decryptors/config_decryptor_plaintext.py +128 -0
  15. rat_king_parser/config_parser/utils/decryptors/config_decryptor_random_hardcoded.py +108 -0
  16. rat_king_parser/config_parser/utils/dotnet_constants.py +86 -0
  17. rat_king_parser/config_parser/utils/dotnetpe_payload.py +207 -0
  18. rat_king_parser/extern/__init__.py +0 -0
  19. rat_king_parser/extern/maco/__init__.py +0 -0
  20. rat_king_parser/extern/maco/rkp_maco.py +216 -0
  21. rat_king_parser/rkp.py +122 -0
  22. rat_king_parser/yara_utils/__init__.py +28 -0
  23. rat_king_parser/yara_utils/recompile.py +52 -0
  24. rat_king_parser/yara_utils/rules.yar +123 -0
  25. rat_king_parser/yara_utils/rules.yarc +0 -0
  26. rat_king_parser-3.1.3.dist-info/LICENSE +7 -0
  27. rat_king_parser-3.1.3.dist-info/METADATA +504 -0
  28. rat_king_parser-3.1.3.dist-info/RECORD +31 -0
  29. rat_king_parser-3.1.3.dist-info/WHEEL +5 -0
  30. rat_king_parser-3.1.3.dist-info/entry_points.txt +2 -0
  31. rat_king_parser-3.1.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # config_decryptor.py
4
+ #
5
+ # Author: jeFF0Falltrades
6
+ #
7
+ # Provides a simple abstract base class for different types of config decryptors
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 abc import ABC, abstractmethod
31
+ from logging import getLogger
32
+
33
+ from ..dotnetpe_payload import DotNetPEPayload
34
+
35
+ logger = getLogger(__name__)
36
+
37
+
38
+ # Custom Exception to denote that a decryptor is incompatible with a payload
39
+ class IncompatibleDecryptorException(Exception):
40
+ pass
41
+
42
+
43
+ class ConfigDecryptor(ABC):
44
+ def __init__(self, payload: DotNetPEPayload) -> None:
45
+ self.key: bytes | str = None
46
+ self._payload = payload
47
+ self.salt: bytes = None
48
+
49
+ # Abstract method to take in a map representing a configuration of config
50
+ # Field names and values and return a decoded/decrypted configuration
51
+ @abstractmethod
52
+ def decrypt_encrypted_strings(
53
+ self, encrypted_strings: dict[str, str]
54
+ ) -> dict[str, list[str] | str]:
55
+ pass
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # config_decryptor_aes_cbc.py
4
+ #
5
+ # Author: jeFF0Falltrades
6
+ #
7
+ # Provides a custom AES decryptor for RAT payloads utilizing CBC mode
8
+ #
9
+ # Example Hash: 6b99acfa5961591c39b3f889cf29970c1dd48ddb0e274f14317940cf279a4412
10
+ #
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2024 Jeff Archer
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in all
23
+ # copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ # SOFTWARE.
32
+ import re
33
+ from base64 import b64decode
34
+ from logging import getLogger
35
+ from typing import Tuple
36
+
37
+ from cryptography.hazmat.backends import default_backend
38
+ from cryptography.hazmat.primitives.ciphers import Cipher
39
+ from cryptography.hazmat.primitives.ciphers.algorithms import AES
40
+ from cryptography.hazmat.primitives.ciphers.modes import CBC
41
+ from cryptography.hazmat.primitives.hashes import SHA1
42
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
43
+ from cryptography.hazmat.primitives.padding import PKCS7
44
+
45
+ from ...config_parser_exception import ConfigParserException
46
+ from ..data_utils import bytes_to_int, decode_bytes, int_to_bytes
47
+ from ..dotnet_constants import OPCODE_LDSTR, OPCODE_LDTOKEN
48
+ from ..dotnetpe_payload import DotNetPEPayload
49
+ from .config_decryptor import ConfigDecryptor, IncompatibleDecryptorException
50
+
51
+ logger = getLogger(__name__)
52
+
53
+
54
+ class ConfigDecryptorAESCBC(ConfigDecryptor):
55
+ # Minimum length of valid ciphertext
56
+ _MIN_CIPHERTEXT_LEN = 48
57
+
58
+ # Patterns for identifying AES metadata
59
+ _PATTERN_AES_KEY_AND_BLOCK_SIZE = re.compile(
60
+ b"[\x06-\x09]\x20(.{4})\x6f.{4}[\x06-\x09]\x20(.{4})", re.DOTALL
61
+ )
62
+ # Do not re.compile in-line replacement patterns
63
+ _PATTERN_AES_KEY_BASE = b"(.{3}\x04).%b"
64
+ _PATTERN_AES_SALT_INIT = b"\x80%b\x2a"
65
+ _PATTERN_AES_SALT_ITER = re.compile(
66
+ b"[\x02-\x05]\x7e(.{4})\x20(.{4})\x73", re.DOTALL
67
+ )
68
+
69
+ def __init__(self, payload: DotNetPEPayload) -> None:
70
+ super().__init__(payload)
71
+ self._block_size: int = None
72
+ self._iterations: int = None
73
+ self._key_candidates: list[bytes] = None
74
+ self._key_size: int = None
75
+ self._key_rva: int = None
76
+ try:
77
+ self._get_aes_metadata()
78
+ except Exception as e:
79
+ raise IncompatibleDecryptorException(e)
80
+
81
+ # Given an initialization vector and ciphertext, creates a Cipher
82
+ # object with the AES key and specified IV and decrypts the ciphertext
83
+ def _decrypt(self, iv: bytes, ciphertext: bytes) -> bytes:
84
+ logger.debug(
85
+ f"Decrypting {ciphertext} with key {self.key.hex()} and IV {iv.hex()}..."
86
+ )
87
+ aes_cipher = Cipher(AES(self.key), CBC(iv), backend=default_backend())
88
+ decryptor = aes_cipher.decryptor()
89
+ # Use a PKCS7 unpadder to remove padding from decrypted value
90
+ # https://cryptography.io/en/latest/hazmat/primitives/padding/
91
+ unpadder = PKCS7(self._block_size).unpadder()
92
+
93
+ try:
94
+ padded_text = decryptor.update(ciphertext) + decryptor.finalize()
95
+ unpadded_text = unpadder.update(padded_text) + unpadder.finalize()
96
+ except Exception as e:
97
+ raise ConfigParserException(
98
+ f"Error decrypting ciphertext {ciphertext} with IV {iv.hex()} and key {self.key.hex()} : {e}"
99
+ )
100
+
101
+ logger.debug(f"Decryption result: {unpadded_text}")
102
+ return unpadded_text
103
+
104
+ # Derives AES passphrase candidates from a config
105
+ #
106
+ # If a passphrase is base64-encoded, both its raw value and decoded value
107
+ # will be added as candidates
108
+ def _derive_aes_passphrase_candidates(self, key_val: str) -> list[bytes]:
109
+ passphrase_candidates = [key_val.encode()]
110
+ try:
111
+ passphrase_candidates.append(b64decode(key_val))
112
+ except Exception:
113
+ pass
114
+ logger.debug(f"AES passphrase candidates found: {passphrase_candidates}")
115
+ return passphrase_candidates
116
+
117
+ # Decrypts encrypted config values with the provided cipher data
118
+ def decrypt_encrypted_strings(
119
+ self, encrypted_strings: dict[str, str]
120
+ ) -> dict[str, str]:
121
+ logger.debug("Decrypting encrypted strings...")
122
+ if self._key_candidates is None:
123
+ self._key_candidates = self._get_aes_key_candidates(encrypted_strings)
124
+
125
+ decrypted_config_strings = {}
126
+ for k, v in encrypted_strings.items():
127
+ # Leave empty strings as they are
128
+ if len(v) == 0:
129
+ logger.debug(f"Key: {k}, Value: {v}")
130
+ decrypted_config_strings[k] = v
131
+ continue
132
+
133
+ # Check if base64-encoded string
134
+ b64_exception = False
135
+ try:
136
+ decoded_val = b64decode(v)
137
+ except Exception:
138
+ b64_exception = True
139
+ # If it was not base64-encoded, or if it is less than our min length
140
+ # for ciphertext, leave the value as it is
141
+ if b64_exception or len(decoded_val) < self._MIN_CIPHERTEXT_LEN:
142
+ logger.debug(f"Key: {k}, Value: {v}")
143
+ decrypted_config_strings[k] = v
144
+ continue
145
+
146
+ # Otherwise, extract the IV from the 16 bytes after the HMAC
147
+ # (first 32 bytes) and the ciphertext from the rest of the data
148
+ # after the IV, and run the decryption
149
+ iv, ciphertext = decoded_val[32:48], decoded_val[48:]
150
+ result, last_exc = None, None
151
+ key_idx = 0
152
+ # Run through key candidates until suitable one found or failure
153
+ while result is None and key_idx < len(self._key_candidates):
154
+ try:
155
+ self.key = self._key_candidates[key_idx]
156
+ key_idx += 1
157
+ result = decode_bytes(self._decrypt(iv, ciphertext))
158
+ except ConfigParserException as e:
159
+ last_exc = e
160
+
161
+ if result is None:
162
+ logger.debug(
163
+ f"Decryption failed for item {v}: {last_exc}; Leaving as original value..."
164
+ )
165
+ result = v
166
+
167
+ logger.debug(f"Key: {k}, Value: {result}")
168
+ decrypted_config_strings[k] = result
169
+
170
+ logger.debug("Successfully decrypted strings")
171
+ return decrypted_config_strings
172
+
173
+ # Extracts AES key candidates from the payload
174
+ def _get_aes_key_candidates(self, encrypted_strings: dict[str, str]) -> list[bytes]:
175
+ logger.debug("Extracting AES key candidates...")
176
+ keys = []
177
+
178
+ # Use the key Field name to index into our existing config
179
+ key_raw_value = encrypted_strings[
180
+ self._payload.field_name_from_rva(self._key_rva)
181
+ ]
182
+ passphrase_candidates = self._derive_aes_passphrase_candidates(key_raw_value)
183
+
184
+ for candidate in passphrase_candidates:
185
+ try:
186
+ # The backend parameter is optional in newer versions of the
187
+ # cryptography library, but we keep it here for compatibility
188
+ kdf = PBKDF2HMAC(
189
+ SHA1(),
190
+ length=self._key_size,
191
+ salt=self.salt,
192
+ iterations=self._iterations,
193
+ backend=default_backend(),
194
+ )
195
+ keys.append(kdf.derive(candidate))
196
+ logger.debug(f"AES key derived: {keys[-1]}")
197
+ except Exception:
198
+ continue
199
+
200
+ if len(keys) == 0:
201
+ raise ConfigParserException(
202
+ f"Could not derive key from passphrase candidates: {passphrase_candidates}"
203
+ )
204
+ return keys
205
+
206
+ # Extracts the AES key and block size from the payload
207
+ def _get_aes_key_and_block_size(self) -> Tuple[int, int]:
208
+ logger.debug("Extracting AES key and block size...")
209
+ hit = re.search(self._PATTERN_AES_KEY_AND_BLOCK_SIZE, self._payload.data)
210
+ if hit is None:
211
+ raise ConfigParserException("Could not extract AES key or block size")
212
+
213
+ # Convert key size from bits to bytes by dividing by 8
214
+ # Note use of // instead of / to ensure integer output, not float
215
+ key_size = bytes_to_int(hit.groups()[0]) // 8
216
+ block_size = bytes_to_int(hit.groups()[1])
217
+
218
+ logger.debug(f"Found key size {key_size} and block size {block_size}")
219
+ return key_size, block_size
220
+
221
+ # Given an offset to an instruction within the Method that sets up the
222
+ # Cipher, extracts the AES key RVA from the payload
223
+ def _get_aes_key_rva(self, metadata_ins_offset: int) -> int:
224
+ logger.debug("Extracting AES key RVA...")
225
+
226
+ # Get the RVA of the method that sets up AES256 metadata
227
+ metadata_method_token = self._payload.method_from_instruction_offset(
228
+ metadata_ins_offset, by_token=True
229
+ ).token
230
+
231
+ # Insert this RVA into the KEY_BASE pattern to find where the AES key
232
+ # is initialized
233
+ key_hit = re.search(
234
+ self._PATTERN_AES_KEY_BASE % re.escape(int_to_bytes(metadata_method_token)),
235
+ self._payload.data,
236
+ re.DOTALL,
237
+ )
238
+ if key_hit is None:
239
+ raise ConfigParserException("Could not find AES key pattern")
240
+
241
+ key_rva = bytes_to_int(key_hit.groups()[0])
242
+ logger.debug(f"AES key RVA: {hex(key_rva)}")
243
+ return key_rva
244
+
245
+ # Identifies the initialization of the AES256 object in the payload and
246
+ # sets the necessary values needed for decryption
247
+ def _get_aes_metadata(self) -> None:
248
+ logger.debug("Extracting AES metadata...")
249
+ metadata = None
250
+ # Some payloads have multiple embedded salt values:
251
+ # Find the one that is actually used for initialization
252
+ for candidate in re.finditer(self._PATTERN_AES_SALT_ITER, self._payload.data):
253
+ try:
254
+ self.salt = self._get_aes_salt(candidate.groups()[0])
255
+ metadata = candidate
256
+ except ConfigParserException:
257
+ continue
258
+ if metadata is None:
259
+ raise ConfigParserException("Could not identify AES metadata")
260
+ logger.debug(f"AES metadata found at offset {hex(metadata.start())}")
261
+
262
+ self._key_size, self._block_size = self._get_aes_key_and_block_size()
263
+
264
+ logger.debug("Extracting AES iterations...")
265
+ self._iterations = bytes_to_int(metadata.groups()[1])
266
+ logger.debug(f"Found AES iteration number of {self._iterations}")
267
+
268
+ self._key_rva = self._get_aes_key_rva(metadata.start())
269
+
270
+ # Extracts the AES salt from the payload, accounting for both hardcoded
271
+ # salt byte arrays, and salts derived from hardcoded strings
272
+ def _get_aes_salt(self, salt_rva: int) -> bytes:
273
+ logger.debug("Extracting AES salt value...")
274
+
275
+ # Use % to insert our salt RVA into our match pattern
276
+ # This pattern will then find the salt initialization ops,
277
+ # specifically:
278
+ #
279
+ # stsfld uint8[] Client.Algorithm.Aes256::Salt
280
+ # ret
281
+ aes_salt_initialization = self._payload.data.find(
282
+ self._PATTERN_AES_SALT_INIT % re.escape(salt_rva)
283
+ )
284
+ if aes_salt_initialization == -1:
285
+ raise ConfigParserException("Could not identify AES salt initialization")
286
+
287
+ # Look at the opcode used to initialize the salt to decide how to
288
+ # proceed with extracting the salt value (start of pattern - 10 bytes)
289
+ salt_op_offset = aes_salt_initialization - 10
290
+ # Need to use bytes([int]) here to properly convert from int to byte
291
+ # string for our comparison below
292
+ salt_op = bytes([self._payload.data[salt_op_offset]])
293
+
294
+ # 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
+ ]
298
+ salt_strings_rva = bytes_to_int(salt_strings_rva_packed)
299
+
300
+ # If the op is a ldstr op, just get the bytes value of the string being
301
+ # used to initialize the salt
302
+ if salt_op == OPCODE_LDSTR:
303
+ salt_encoded = self._payload.user_string_from_rva(salt_strings_rva)
304
+ # We use decode_bytes() here to get the salt string without any
305
+ # null bytes (because it's stored as UTF-16LE), then convert it
306
+ # back to bytes
307
+ salt = decode_bytes(salt_encoded).encode()
308
+ # If the op is a ldtoken (0xd0) operation, we need to get the salt
309
+ # byte array value from the FieldRVA table
310
+ elif salt_op == OPCODE_LDTOKEN:
311
+ 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
+ )
315
+ else:
316
+ raise ConfigParserException(f"Unknown salt opcode found: {salt_op.hex()}")
317
+
318
+ logger.debug(f"Found salt value: {salt.hex()}")
319
+ return salt
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # config_decryptor_aes_ecb.py
4
+ #
5
+ # Author: jeFF0Falltrades
6
+ #
7
+ # Provides a custom AES decryptor for RAT payloads utilizing ECB mode
8
+ #
9
+ # Example Hash: d5028e10a756f2df677f32ebde105d7de8df37e253c431837c8f810260f4428e
10
+ #
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2024 Jeff Archer
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in all
23
+ # copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ # SOFTWARE.
32
+ from base64 import b64decode
33
+ from hashlib import md5
34
+ from logging import getLogger
35
+ from re import DOTALL, compile, search
36
+
37
+ from cryptography.hazmat.backends import default_backend
38
+ from cryptography.hazmat.primitives.ciphers import Cipher
39
+ from cryptography.hazmat.primitives.ciphers.algorithms import AES
40
+ from cryptography.hazmat.primitives.ciphers.modes import ECB
41
+ from cryptography.hazmat.primitives.padding import PKCS7
42
+
43
+ from ...config_parser_exception import ConfigParserException
44
+ from ..data_utils import bytes_to_int, decode_bytes
45
+ from ..dotnetpe_payload import DotNetPEPayload
46
+ from .config_decryptor import ConfigDecryptor, IncompatibleDecryptorException
47
+
48
+ logger = getLogger(__name__)
49
+
50
+
51
+ class ConfigDecryptorAESECB(ConfigDecryptor):
52
+ # MD5 hash pattern used to detect AES key
53
+ _PATTERN_MD5_HASH = compile(rb"\x7e(.{3}\x04)\x28.{3}\x06\x6f", DOTALL)
54
+
55
+ def __init__(self, payload: DotNetPEPayload) -> None:
56
+ super().__init__(payload)
57
+ try:
58
+ self._aes_key_rva = self._get_aes_key_rva()
59
+ except Exception as e:
60
+ raise IncompatibleDecryptorException(e)
61
+
62
+ # Given ciphertext, creates a Cipher object with the AES key and decrypts
63
+ # the ciphertext
64
+ def _decrypt(self, ciphertext: bytes) -> bytes:
65
+ logger.debug(f"Decrypting {ciphertext} with key {self.key.hex()}...")
66
+ aes_cipher = Cipher(AES(self.key), ECB(), backend=default_backend())
67
+ decryptor = aes_cipher.decryptor()
68
+ unpadder = PKCS7(AES.block_size).unpadder()
69
+ # Use a PKCS7 unpadder to remove padding from decrypted value
70
+ # https://cryptography.io/en/latest/hazmat/primitives/padding/
71
+ unpadder = PKCS7(AES.block_size).unpadder()
72
+
73
+ try:
74
+ padded_text = decryptor.update(ciphertext) + decryptor.finalize()
75
+ unpadded_text = unpadder.update(padded_text) + unpadder.finalize()
76
+ except Exception as e:
77
+ raise ConfigParserException(
78
+ f"Error decrypting ciphertext {ciphertext} with key {self.key.hex()}: {e}"
79
+ )
80
+
81
+ logger.debug(f"Decryption result: {unpadded_text}")
82
+ return unpadded_text
83
+
84
+ # Decrypts encrypted config values with the provided cipher data
85
+ def decrypt_encrypted_strings(
86
+ self, encrypted_strings: dict[str, str]
87
+ ) -> dict[str, str]:
88
+ logger.debug("Decrypting encrypted strings...")
89
+
90
+ if self.key is None:
91
+ try:
92
+ raw_key_field = self._payload.field_name_from_rva(self._aes_key_rva)
93
+ self.key = self._derive_aes_key(encrypted_strings[raw_key_field])
94
+ except Exception as e:
95
+ raise ConfigParserException(f"Failed to derive AES key: {e}")
96
+
97
+ decrypted_config_strings = {}
98
+ for k, v in encrypted_strings.items():
99
+ # Leave empty strings as they are
100
+ if len(v) == 0:
101
+ logger.debug(f"Key: {k}, Value: {v}")
102
+ decrypted_config_strings[k] = v
103
+ continue
104
+
105
+ # Check if base64-encoded string
106
+ b64_exception = False
107
+ try:
108
+ decoded_val = b64decode(v)
109
+ except Exception:
110
+ b64_exception = True
111
+ # If it was not base64-encoded, leave the value as it is
112
+ if b64_exception:
113
+ logger.debug(f"Key: {k}, Value: {v}")
114
+ decrypted_config_strings[k] = v
115
+ continue
116
+
117
+ ciphertext = decoded_val
118
+ result, last_exc = None, None
119
+ try:
120
+ result = decode_bytes(self._decrypt(ciphertext))
121
+ except ConfigParserException as e:
122
+ last_exc = e
123
+
124
+ if result is None:
125
+ logger.debug(f"Decryption failed for item {v}: {last_exc}")
126
+ result = v
127
+
128
+ logger.debug(f"Key: {k}, Value: {result}")
129
+ decrypted_config_strings[k] = result
130
+
131
+ logger.debug("Successfully decrypted strings")
132
+ return decrypted_config_strings
133
+
134
+ # Given the raw bytes that will become the key value, derives the AES key
135
+ def _derive_aes_key(self, key_unhashed: str) -> bytes:
136
+ # Generate the MD5 hash
137
+ md5_hash = md5()
138
+ md5_hash.update(key_unhashed.encode("utf-8"))
139
+ md5_digest = md5_hash.digest()
140
+
141
+ # Key is a 32-byte value made up of the MD5 hash overlaying itself,
142
+ # tailed with one null byte
143
+ key = md5_digest[:15] + md5_digest[:16] + b"\x00"
144
+ logger.debug(f"AES key derived: {key}")
145
+ return key
146
+
147
+ # Extracts the AES key RVA from the payload
148
+ def _get_aes_key_rva(self) -> int:
149
+ logger.debug("Extracting AES key value...")
150
+ key_hit = search(self._PATTERN_MD5_HASH, self._payload.data)
151
+ if key_hit is None:
152
+ raise ConfigParserException("Could not find AES key pattern")
153
+
154
+ key_rva = bytes_to_int(key_hit.groups()[0])
155
+ logger.debug(f"AES key RVA: {hex(key_rva)}")
156
+ return key_rva
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # config_decryptor_decrypt_xor.py
4
+ #
5
+ # Author: jeFF0Falltrades
6
+ #
7
+ # Provides a custom decryptor for RAT payloads utilizing the DecryptXOR
8
+ # method of embeddeding config strings
9
+ #
10
+ # Example Hash: 6e5671dec52db7f64557ba8ef70caf53cf0c782795236b03655623640f9e6a83
11
+ #
12
+ # MIT License
13
+ #
14
+ # Copyright (c) 2024 Jeff Archer
15
+ #
16
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ # of this software and associated documentation files (the "Software"), to deal
18
+ # in the Software without restriction, including without limitation the rights
19
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ # copies of the Software, and to permit persons to whom the Software is
21
+ # furnished to do so, subject to the following conditions:
22
+ #
23
+ # The above copyright notice and this permission notice shall be included in all
24
+ # copies or substantial portions of the Software.
25
+ #
26
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
+ # SOFTWARE.
33
+ from logging import getLogger
34
+ from re import DOTALL, compile, findall, search
35
+
36
+ from ...config_parser_exception import ConfigParserException
37
+ from ..data_utils import bytes_to_int, decode_bytes
38
+ from ..dotnet_constants import PATTERN_LDSTR_OP
39
+ from ..dotnetpe_payload import DotNetPEPayload
40
+ from .config_decryptor import ConfigDecryptor, IncompatibleDecryptorException
41
+ from .config_decryptor_plaintext import ConfigDecryptorPlaintext
42
+
43
+ logger = getLogger(__name__)
44
+
45
+
46
+ class ConfigDecryptorDecryptXOR(ConfigDecryptor):
47
+ _KEY_XOR_DECODED_STRINGS = "xor_decoded_strings"
48
+
49
+ # Pattern to detect usage of DecryptXOR Method
50
+ _PATTERN_DECRYPT_XOR_BLOCK = compile(
51
+ rb"(\x2d.\x72.{3}\x70\x28.{3}\x06\x2a(?:\x02[\x16-\x1f].?\x33.\x72.{3}\x70\x28.{3}\x06\x2a){7,}.+?\x72.{3}\x70)",
52
+ flags=DOTALL,
53
+ )
54
+
55
+ def __init__(self, payload: DotNetPEPayload) -> None:
56
+ super().__init__(payload)
57
+ # Filled in _get_xor_metadata()
58
+ self._xor_strings: list[str] = []
59
+ try:
60
+ self._get_xor_metadata()
61
+ except Exception as e:
62
+ raise IncompatibleDecryptorException(e)
63
+
64
+ # Returns a list of decoded XOR-encoded strings found in the payload
65
+ def _decode_encoded_strings(self) -> list[str]:
66
+ decoded_strings = []
67
+
68
+ for string in self._xor_strings:
69
+ decoded = []
70
+ # Do not modify unencoded strings
71
+ if ":" not in string:
72
+ decoded_strings.append(string)
73
+ continue
74
+
75
+ # Split encoded string by ':' and run XOR decoding
76
+ arr, arr2 = (bytes.fromhex(arr) for arr in string.split(":"))
77
+ for idx, byte in enumerate(arr2):
78
+ decoded.append(byte ^ self.key[idx % len(self.key)] ^ arr[idx])
79
+ decoded_strings.append(decode_bytes(bytes(decoded)))
80
+
81
+ logger.debug(f"Decoded {len(decoded_strings)} strings")
82
+ return decoded_strings
83
+
84
+ # Parses the config, adds decoded XOR strings, and returns the decoded
85
+ # config
86
+ def decrypt_encrypted_strings(
87
+ self, encrypted_strings: dict[str, str]
88
+ ) -> dict[str, list[str] | str]:
89
+ config = {}
90
+ # Pass off plaintext config to a ConfigDecryptorPlaintext
91
+ ptcd = ConfigDecryptorPlaintext(self._payload)
92
+ config.update(ptcd.decrypt_encrypted_strings(encrypted_strings))
93
+ config[self._KEY_XOR_DECODED_STRINGS] = self._decode_encoded_strings()
94
+ return config
95
+
96
+ # Gathers XOR metadata from the payload
97
+ def _get_xor_metadata(self):
98
+ dxor_block = search(self._PATTERN_DECRYPT_XOR_BLOCK, self._payload.data)
99
+ if dxor_block is None:
100
+ raise ConfigParserException("Could not identify DecryptXOR block")
101
+ logger.debug(f"DecryptXOR block found at offset {hex(dxor_block.start())}")
102
+
103
+ # Derive all XOR-encoded string references in the DecryptXOR block
104
+ xor_string_rvas = findall(PATTERN_LDSTR_OP, dxor_block.groups()[0])
105
+ self._xor_strings = list(
106
+ filter(
107
+ None,
108
+ [
109
+ self._payload.user_string_from_rva(bytes_to_int(rva))
110
+ for rva in xor_string_rvas
111
+ ],
112
+ )
113
+ )
114
+ logger.debug(f"{len(self._xor_strings)} XOR strings found")
115
+
116
+ # Get the static constructor containing the XOR key
117
+ xor_key_cctor = self._payload.method_from_instruction_offset(
118
+ dxor_block.start(), step=1, by_token=True
119
+ )
120
+ xor_key_cctor_body = self._payload.method_body_from_method(xor_key_cctor)
121
+
122
+ # Derive the XOR key RVA and value
123
+ xor_rva = search(PATTERN_LDSTR_OP, xor_key_cctor_body)
124
+ if xor_rva is None:
125
+ raise ConfigParserException("Could not identify XOR key RVA")
126
+ xor_rva = bytes_to_int(xor_rva.groups()[0])
127
+ self.key = bytes(self._payload.user_string_from_rva(xor_rva), encoding="utf-8")
128
+ logger.debug(f"XOR key found at {hex(xor_rva)} : {self.key}")