maco 1.2.14__py3-none-any.whl → 1.2.16__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.
- demo_extractors/complex/complex.py +12 -0
- demo_extractors/complex/complex_utils.py +11 -2
- demo_extractors/elfy.py +12 -0
- demo_extractors/limit_other.py +15 -0
- demo_extractors/nothing.py +11 -3
- demo_extractors/shared.py +6 -0
- demo_extractors/terminator.py +12 -1
- maco/base_test.py +24 -7
- maco/cli.py +19 -5
- maco/collector.py +25 -9
- maco/exceptions.py +31 -1
- maco/extractor.py +7 -8
- maco/model/model.py +34 -0
- maco/utils.py +139 -83
- maco/yara.py +47 -5
- {maco-1.2.14.dist-info → maco-1.2.16.dist-info}/METADATA +3 -3
- maco-1.2.16.dist-info/RECORD +49 -0
- {maco-1.2.14.dist-info → maco-1.2.16.dist-info}/WHEEL +1 -1
- model_setup/maco/base_test.py +24 -7
- model_setup/maco/cli.py +19 -5
- model_setup/maco/collector.py +25 -9
- model_setup/maco/exceptions.py +31 -1
- model_setup/maco/extractor.py +7 -8
- model_setup/maco/model/model.py +34 -0
- model_setup/maco/utils.py +139 -83
- model_setup/maco/yara.py +47 -5
- tests/extractors/basic.py +10 -2
- tests/extractors/basic_longer.py +9 -2
- tests/extractors/bob/bob.py +2 -0
- tests/extractors/import_rewriting/__init__.py +0 -0
- tests/extractors/import_rewriting/importer.py +10341 -0
- tests/extractors/test_basic.py +4 -0
- maco-1.2.14.dist-info/RECORD +0 -47
- {maco-1.2.14.dist-info → maco-1.2.16.dist-info}/entry_points.txt +0 -0
- {maco-1.2.14.dist-info → maco-1.2.16.dist-info/licenses}/LICENSE.md +0 -0
- {maco-1.2.14.dist-info → maco-1.2.16.dist-info}/top_level.txt +0 -0
maco/utils.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
"""Common utilities shared between the MACO collector and configextractor-py."""
|
|
2
|
+
|
|
2
3
|
import importlib
|
|
3
|
-
import importlib.machinery
|
|
4
|
-
import importlib.util
|
|
5
4
|
import inspect
|
|
6
5
|
import json
|
|
7
6
|
import logging
|
|
@@ -12,8 +11,9 @@ import shutil
|
|
|
12
11
|
import subprocess
|
|
13
12
|
import sys
|
|
14
13
|
import tempfile
|
|
14
|
+
from importlib.machinery import SourceFileLoader
|
|
15
15
|
|
|
16
|
-
from multiprocess import Queue
|
|
16
|
+
from multiprocess import Process, Queue
|
|
17
17
|
|
|
18
18
|
from maco import yara
|
|
19
19
|
|
|
@@ -26,15 +26,14 @@ from base64 import b64decode
|
|
|
26
26
|
from copy import deepcopy
|
|
27
27
|
from glob import glob
|
|
28
28
|
from logging import Logger
|
|
29
|
-
from pkgutil import walk_packages
|
|
30
29
|
from types import ModuleType
|
|
31
|
-
from typing import Callable, Dict, List,
|
|
30
|
+
from typing import Callable, Dict, List, Tuple, Union
|
|
32
31
|
|
|
33
32
|
from uv import find_uv_bin
|
|
34
33
|
|
|
35
34
|
from maco import model
|
|
36
|
-
from maco.extractor import Extractor
|
|
37
35
|
from maco.exceptions import AnalysisAbortedException
|
|
36
|
+
from maco.extractor import Extractor
|
|
38
37
|
|
|
39
38
|
logger = logging.getLogger("maco.lib.utils")
|
|
40
39
|
|
|
@@ -50,10 +49,14 @@ VENV_CREATE_CMD = f"{UV_BIN} venv"
|
|
|
50
49
|
|
|
51
50
|
|
|
52
51
|
class Base64Decoder(json.JSONDecoder):
|
|
52
|
+
"""JSON decoder that also base64 encodes binary data."""
|
|
53
|
+
|
|
53
54
|
def __init__(self, *args, **kwargs):
|
|
55
|
+
"""Initialize the decoder."""
|
|
54
56
|
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
|
|
55
57
|
|
|
56
58
|
def object_hook(self, obj):
|
|
59
|
+
"""Hook to decode base64 encoded binary data.""" # noqa: DOC201
|
|
57
60
|
if "__class__" not in obj:
|
|
58
61
|
return obj
|
|
59
62
|
type = obj["__class__"]
|
|
@@ -131,17 +134,38 @@ rule MACO {
|
|
|
131
134
|
|
|
132
135
|
|
|
133
136
|
def maco_extractor_validation(module: ModuleType) -> bool:
|
|
137
|
+
"""Validation function for extractors.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
(bool): True if extractor belongs to MACO, False otherwise.
|
|
141
|
+
"""
|
|
134
142
|
if inspect.isclass(module):
|
|
135
143
|
# 'author' has to be implemented otherwise will raise an exception according to MACO
|
|
136
144
|
return hasattr(module, "author") and module.author
|
|
137
145
|
return False
|
|
138
146
|
|
|
139
147
|
|
|
140
|
-
def maco_extract_rules(module: Extractor) ->
|
|
148
|
+
def maco_extract_rules(module: Extractor) -> str:
|
|
149
|
+
"""Extracts YARA rules from extractor.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
(str): YARA rules
|
|
153
|
+
"""
|
|
141
154
|
return module.yara_rule
|
|
142
155
|
|
|
143
156
|
|
|
144
157
|
def scan_for_extractors(root_directory: str, scanner: yara.Rules, logger: Logger) -> Tuple[List[str], List[str]]:
|
|
158
|
+
"""Looks for extractors using YARA rules.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
root_directory (str): Root directory containing extractors
|
|
162
|
+
scanner (yara.Rules): Scanner to look for extractors using YARA rules
|
|
163
|
+
logger (Logger): Logger to use
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Tuple[List[str], List[str]]: Returns a list of extractor directories and extractor files
|
|
167
|
+
|
|
168
|
+
"""
|
|
145
169
|
extractor_dirs = set([root_directory])
|
|
146
170
|
extractor_files = []
|
|
147
171
|
|
|
@@ -177,17 +201,22 @@ def scan_for_extractors(root_directory: str, scanner: yara.Rules, logger: Logger
|
|
|
177
201
|
with open(path, "rb") as f:
|
|
178
202
|
data = f.read()
|
|
179
203
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
204
|
+
# Replace any relative importing with absolute
|
|
205
|
+
changed_imports = False
|
|
206
|
+
curr_dir = os.path.dirname(path)
|
|
207
|
+
split = curr_dir.split("/")[::-1]
|
|
208
|
+
for pattern in [RELATIVE_FROM_IMPORT_RE, RELATIVE_FROM_RE]:
|
|
209
|
+
for match in pattern.findall(data):
|
|
210
|
+
depth = match.count(b".")
|
|
211
|
+
abspath = ".".join(split[depth - 1 : split.index(package) + 1][::-1])
|
|
212
|
+
abspath += "." if pattern == RELATIVE_FROM_RE else ""
|
|
213
|
+
data = data.replace(f"from {match.decode()}".encode(), f"from {abspath}".encode(), 1)
|
|
214
|
+
changed_imports = True
|
|
215
|
+
|
|
216
|
+
# only write extractor files if imports were changed
|
|
217
|
+
if changed_imports:
|
|
218
|
+
with open(path, "wb") as f:
|
|
219
|
+
f.write(data)
|
|
191
220
|
|
|
192
221
|
if scanner.match(path):
|
|
193
222
|
# Add directory to list of hits for venv creation
|
|
@@ -282,7 +311,16 @@ def _install_required_packages(create_venv: bool, directories: List[str], python
|
|
|
282
311
|
return venvs
|
|
283
312
|
|
|
284
313
|
|
|
285
|
-
def find_and_insert_venv(path: str, venvs: List[str]):
|
|
314
|
+
def find_and_insert_venv(path: str, venvs: List[str]) -> Tuple[str, str]:
|
|
315
|
+
"""Finds the closest virtual environment to the extractor and inserts it into the PATH.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
path (str): Path of extractor
|
|
319
|
+
venvs (List[str]): List of virtual environments
|
|
320
|
+
|
|
321
|
+
Returns:
|
|
322
|
+
(Tuple[str, str]): Virtual environment and site-packages path that's closest to the extractor
|
|
323
|
+
"""
|
|
286
324
|
venv = None
|
|
287
325
|
for venv in sorted(venvs, reverse=True):
|
|
288
326
|
venv_parent = os.path.dirname(venv)
|
|
@@ -303,14 +341,53 @@ def find_and_insert_venv(path: str, venvs: List[str]):
|
|
|
303
341
|
return venv, site_package
|
|
304
342
|
|
|
305
343
|
|
|
344
|
+
def register_extractor_module(
|
|
345
|
+
extractor_source_file: str,
|
|
346
|
+
module_name: str,
|
|
347
|
+
venvs: List[str],
|
|
348
|
+
extractor_module_callback: Callable[[ModuleType, str], None],
|
|
349
|
+
logger: Logger,
|
|
350
|
+
):
|
|
351
|
+
"""Register the extractor module in isolation.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
extractor_source_file (str): Path to source file of extractor
|
|
355
|
+
module_name (str): The name of the module relative to the package directory
|
|
356
|
+
venvs (List[str]): List of virtual environments
|
|
357
|
+
extractor_module_callback (Callable[[ModuleType, str], None]): Callback used to register extractors
|
|
358
|
+
logger (Logger): Logger to use
|
|
359
|
+
|
|
360
|
+
"""
|
|
361
|
+
try:
|
|
362
|
+
logger.info(f"Inspecting '{extractor_source_file}' for extractors..")
|
|
363
|
+
venv, site_packages = find_and_insert_venv(extractor_source_file, venvs)
|
|
364
|
+
loader = SourceFileLoader(
|
|
365
|
+
module_name,
|
|
366
|
+
extractor_source_file,
|
|
367
|
+
)
|
|
368
|
+
extractor_module_callback(loader.load_module(), venv)
|
|
369
|
+
finally:
|
|
370
|
+
# Cleanup virtual environment that was loaded into PATH
|
|
371
|
+
if venv and site_packages in sys.path:
|
|
372
|
+
sys.path.remove(site_packages)
|
|
373
|
+
|
|
374
|
+
|
|
306
375
|
def register_extractors(
|
|
307
376
|
current_directory: str,
|
|
308
377
|
venvs: List[str],
|
|
309
378
|
extractor_files: List[str],
|
|
310
379
|
extractor_module_callback: Callable[[ModuleType, str], None],
|
|
311
380
|
logger: Logger,
|
|
312
|
-
default_loaded_modules: Set[str] = set(sys.modules.keys()),
|
|
313
381
|
):
|
|
382
|
+
"""Register extractors with in the current directory.
|
|
383
|
+
|
|
384
|
+
Args:
|
|
385
|
+
current_directory (str): Current directory to register extractors found
|
|
386
|
+
venvs (List[str]): List of virtual environments
|
|
387
|
+
extractor_files (List[str]): List of extractor files found
|
|
388
|
+
extractor_module_callback (Callable[[ModuleType, str], None]): Callback used to register extractors
|
|
389
|
+
logger (Logger): Logger to use
|
|
390
|
+
"""
|
|
314
391
|
package_name = os.path.basename(current_directory)
|
|
315
392
|
parent_directory = os.path.dirname(current_directory)
|
|
316
393
|
if venvs and package_name in sys.modules:
|
|
@@ -325,74 +402,25 @@ def register_extractors(
|
|
|
325
402
|
sys.path.insert(1, current_directory)
|
|
326
403
|
sys.path.insert(1, parent_directory)
|
|
327
404
|
|
|
328
|
-
#
|
|
329
|
-
|
|
330
|
-
|
|
405
|
+
# Load the potential extractors directly from the source file
|
|
406
|
+
registration_processes = []
|
|
407
|
+
for extractor_source_file in extractor_files:
|
|
408
|
+
module_name = extractor_source_file.replace(f"{parent_directory}/", "").replace("/", ".")[:-3]
|
|
409
|
+
p = Process(
|
|
410
|
+
target=register_extractor_module,
|
|
411
|
+
args=(extractor_source_file, module_name, venvs, extractor_module_callback, logger),
|
|
412
|
+
)
|
|
413
|
+
p.start()
|
|
414
|
+
registration_processes.append(p)
|
|
331
415
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
if ispkg:
|
|
335
|
-
# Skip packages
|
|
336
|
-
continue
|
|
416
|
+
for p in registration_processes:
|
|
417
|
+
p.join()
|
|
337
418
|
|
|
338
|
-
module_path = os.path.realpath(os.path.join(module_path.path, module_name.rsplit(".", 1)[1]) + ".py")
|
|
339
|
-
if module_path in extractor_files:
|
|
340
|
-
# Cross this extractor off the list of extractors to find
|
|
341
|
-
logger.debug(f"Inspecting '{module_name}' for extractors..")
|
|
342
|
-
extractor_files.remove(module_path)
|
|
343
|
-
try:
|
|
344
|
-
# This is an extractor we've been looking for, load the module and invoke callback
|
|
345
|
-
venv, site_packages = find_and_insert_venv(module_path, venvs)
|
|
346
|
-
module = importlib.import_module(module_name)
|
|
347
|
-
module.__file__ = os.path.realpath(module.__file__)
|
|
348
|
-
|
|
349
|
-
# Patch the original directory information into the module
|
|
350
|
-
original_package_name = os.path.basename(current_directory)
|
|
351
|
-
module.__name__ = module.__name__.replace(package_name, original_package_name)
|
|
352
|
-
module.__package__ = module.__package__.replace(package_name, original_package_name)
|
|
353
|
-
extractor_module_callback(module, venv)
|
|
354
|
-
finally:
|
|
355
|
-
# Cleanup virtual environment that was loaded into PATH
|
|
356
|
-
if venv and site_packages in sys.path:
|
|
357
|
-
sys.path.remove(site_packages)
|
|
358
|
-
|
|
359
|
-
if not extractor_files:
|
|
360
|
-
return
|
|
361
419
|
finally:
|
|
362
420
|
# Cleanup changes made to PATH
|
|
363
421
|
sys.path.remove(parent_directory)
|
|
364
422
|
sys.path.remove(current_directory)
|
|
365
423
|
|
|
366
|
-
if package_venv and package_site_packages in sys.path:
|
|
367
|
-
sys.path.remove(package_site_packages)
|
|
368
|
-
|
|
369
|
-
# Remove any modules that were loaded to deconflict with later modules loads
|
|
370
|
-
[sys.modules.pop(k) for k in set(sys.modules.keys()) - default_loaded_modules]
|
|
371
|
-
|
|
372
|
-
# If there still exists extractor files we haven't found yet, try searching in the available subdirectories
|
|
373
|
-
if extractor_files:
|
|
374
|
-
for dir in os.listdir(current_directory):
|
|
375
|
-
path = os.path.join(current_directory, dir)
|
|
376
|
-
if dir == "__pycache__":
|
|
377
|
-
# Ignore the cache created
|
|
378
|
-
continue
|
|
379
|
-
elif dir.endswith(".egg-info"):
|
|
380
|
-
# Ignore these directories
|
|
381
|
-
continue
|
|
382
|
-
elif dir.startswith("."):
|
|
383
|
-
# Ignore hidden directories
|
|
384
|
-
continue
|
|
385
|
-
|
|
386
|
-
if os.path.isdir(path):
|
|
387
|
-
# Check subdirectory to find the rest of the detected extractors
|
|
388
|
-
register_extractors(
|
|
389
|
-
path, venvs, extractor_files, extractor_module_callback, logger, default_loaded_modules
|
|
390
|
-
)
|
|
391
|
-
|
|
392
|
-
if not extractor_files:
|
|
393
|
-
# We were able to find all the extractor files
|
|
394
|
-
break
|
|
395
|
-
|
|
396
424
|
|
|
397
425
|
def proxy_logging(queue: Queue, callback: Callable[[ModuleType, str], None], *args, **kwargs):
|
|
398
426
|
"""Ensures logging is set up correctly for a child process and then executes the callback."""
|
|
@@ -413,6 +441,17 @@ def import_extractors(
|
|
|
413
441
|
python_version: str = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
|
414
442
|
skip_install: bool = False,
|
|
415
443
|
):
|
|
444
|
+
"""Import extractors in a given directory.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
extractor_module_callback (Callable[[ModuleType, str], bool]): Callback used to register extractors
|
|
448
|
+
root_directory (str): Root directory to look for extractors
|
|
449
|
+
scanner (yara.Rules): Scanner to look for extractors that match YARA rule
|
|
450
|
+
create_venv (bool): Create/Use virtual environments
|
|
451
|
+
logger (Logger): Logger to use
|
|
452
|
+
python_version (str): Version of python to use when creating virtual environments
|
|
453
|
+
skip_install (bool): Skip installation of Python dependencies for extractors
|
|
454
|
+
"""
|
|
416
455
|
extractor_dirs, extractor_files = scan_for_extractors(root_directory, scanner, logger)
|
|
417
456
|
|
|
418
457
|
logger.info(f"Extractor files found based on scanner ({len(extractor_files)}).")
|
|
@@ -448,7 +487,24 @@ def run_extractor(
|
|
|
448
487
|
venv_script=VENV_SCRIPT,
|
|
449
488
|
json_decoder=Base64Decoder,
|
|
450
489
|
) -> Union[Dict[str, dict], model.ExtractorModel]:
|
|
451
|
-
"""Runs the maco extractor against sample either in current process or child process.
|
|
490
|
+
"""Runs the maco extractor against sample either in current process or child process.
|
|
491
|
+
|
|
492
|
+
Args:
|
|
493
|
+
sample_path (str): Path to sample
|
|
494
|
+
module_name (str): Name of extractor module
|
|
495
|
+
extractor_class (str): Name of extractor class in module
|
|
496
|
+
module_path (str): Path to Python module containing extractor
|
|
497
|
+
venv (str): Path to virtual environment associated to extractor
|
|
498
|
+
venv_script (str): Script to run extractor in a virtual environment
|
|
499
|
+
json_decoder (Base64Decoder): Decoder used for JSON
|
|
500
|
+
|
|
501
|
+
Raises:
|
|
502
|
+
AnalysisAbortedException: Raised when extractor voluntarily terminates execution
|
|
503
|
+
Exception: Raised when extractor raises an exception
|
|
504
|
+
|
|
505
|
+
Returns:
|
|
506
|
+
Union[Dict[str, dict], model.ExtractorModel]: Results from extractor
|
|
507
|
+
"""
|
|
452
508
|
if not venv:
|
|
453
509
|
key = f"{module_name}_{extractor_class}"
|
|
454
510
|
if key not in _loaded_extractors:
|
maco/yara.py
CHANGED
|
@@ -1,25 +1,34 @@
|
|
|
1
|
+
"""yara-python facade that uses yara-x."""
|
|
2
|
+
|
|
1
3
|
import re
|
|
2
4
|
from collections import namedtuple
|
|
3
5
|
from itertools import cycle
|
|
4
|
-
from typing import Dict
|
|
6
|
+
from typing import Dict, List
|
|
5
7
|
|
|
6
8
|
import yara_x
|
|
7
9
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
from maco.exceptions import SyntaxError
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
RULE_ID_RE = re.compile("(\w+)? ?rule (\w+)")
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
# Create interfaces that resembles yara-python (but is running yara-x under the hood)
|
|
15
16
|
class StringMatchInstance:
|
|
17
|
+
"""Instance of a string match."""
|
|
18
|
+
|
|
16
19
|
def __init__(self, match: yara_x.Match, file_content: bytes):
|
|
20
|
+
"""Initializes StringMatchInstance."""
|
|
17
21
|
self.matched_data = file_content[match.offset : match.offset + match.length]
|
|
18
22
|
self.matched_length = match.length
|
|
19
23
|
self.offset = match.offset
|
|
20
24
|
self.xor_key = match.xor_key
|
|
21
25
|
|
|
22
26
|
def plaintext(self) -> bytes:
|
|
27
|
+
"""Plaintext of the matched data.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
(bytes): Plaintext of the matched cipher text
|
|
31
|
+
"""
|
|
23
32
|
if not self.xor_key:
|
|
24
33
|
# No need to XOR the matched data
|
|
25
34
|
return self.matched_data
|
|
@@ -28,17 +37,28 @@ class StringMatchInstance:
|
|
|
28
37
|
|
|
29
38
|
|
|
30
39
|
class StringMatch:
|
|
40
|
+
"""String match."""
|
|
41
|
+
|
|
31
42
|
def __init__(self, pattern: yara_x.Pattern, file_content: bytes):
|
|
43
|
+
"""Initializes StringMatch."""
|
|
32
44
|
self.identifier = pattern.identifier
|
|
33
45
|
self.instances = [StringMatchInstance(match, file_content) for match in pattern.matches]
|
|
34
46
|
self._is_xor = any([match.xor_key for match in pattern.matches])
|
|
35
47
|
|
|
36
48
|
def is_xor(self):
|
|
49
|
+
"""Checks if string match is xor'd.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
(bool): True if match is xor'd
|
|
53
|
+
"""
|
|
37
54
|
return self._is_xor
|
|
38
55
|
|
|
39
56
|
|
|
40
57
|
class Match:
|
|
58
|
+
"""Match."""
|
|
59
|
+
|
|
41
60
|
def __init__(self, rule: yara_x.Rule, file_content: bytes):
|
|
61
|
+
"""Initializes Match."""
|
|
42
62
|
self.rule = rule.identifier
|
|
43
63
|
self.namespace = rule.namespace
|
|
44
64
|
self.tags = list(rule.tags) or []
|
|
@@ -50,7 +70,14 @@ class Match:
|
|
|
50
70
|
|
|
51
71
|
|
|
52
72
|
class Rules:
|
|
73
|
+
"""Rules."""
|
|
74
|
+
|
|
53
75
|
def __init__(self, source: str = None, sources: Dict[str, str] = None):
|
|
76
|
+
"""Initializes Rules.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
SyntaxError: Raised when there's a syntax error in the YARA rule.
|
|
80
|
+
"""
|
|
54
81
|
Rule = namedtuple("Rule", "identifier namespace is_global")
|
|
55
82
|
if source:
|
|
56
83
|
sources = {"default": source}
|
|
@@ -69,10 +96,20 @@ class Rules:
|
|
|
69
96
|
raise SyntaxError(e)
|
|
70
97
|
|
|
71
98
|
def __iter__(self):
|
|
99
|
+
"""Iterate over rules.
|
|
100
|
+
|
|
101
|
+
Yields:
|
|
102
|
+
YARA rules
|
|
103
|
+
"""
|
|
72
104
|
for rule in self._rules:
|
|
73
105
|
yield rule
|
|
74
106
|
|
|
75
|
-
def match(self, filepath: str = None, data: bytes = None):
|
|
107
|
+
def match(self, filepath: str = None, data: bytes = None) -> List[Match]:
|
|
108
|
+
"""Performs a scan to check for YARA rules matches based on the file, either given by path or buffer.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
(List[Match]): A list of YARA matches.
|
|
112
|
+
"""
|
|
76
113
|
if filepath:
|
|
77
114
|
with open(filepath, "rb") as fp:
|
|
78
115
|
data = fp.read()
|
|
@@ -81,4 +118,9 @@ class Rules:
|
|
|
81
118
|
|
|
82
119
|
|
|
83
120
|
def compile(source: str = None, sources: Dict[str, str] = None) -> Rules:
|
|
121
|
+
"""Compiles YARA rules from source or from sources.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
(Rules): a Rules object
|
|
125
|
+
"""
|
|
84
126
|
return Rules(source, sources)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: maco
|
|
3
|
-
Version: 1.2.
|
|
3
|
+
Version: 1.2.16
|
|
4
4
|
Author: sl-govau
|
|
5
5
|
Maintainer: cccs-rs
|
|
6
6
|
License: MIT License
|
|
@@ -35,6 +35,7 @@ Requires-Dist: tomli>=1.1.0; python_version < "3.11"
|
|
|
35
35
|
Requires-Dist: uv
|
|
36
36
|
Requires-Dist: yara-x==0.11.0
|
|
37
37
|
Requires-Dist: multiprocess>=0.70.17
|
|
38
|
+
Dynamic: license-file
|
|
38
39
|
|
|
39
40
|
# Maco - Malware config extractor framework
|
|
40
41
|
|
|
@@ -69,7 +70,6 @@ This framework is actively being used by:
|
|
|
69
70
|
| <a href="https://cybercentrecanada.github.io/assemblyline4_docs/"><img src="https://images.weserv.nl/?url=cybercentrecanada.github.io/assemblyline4_docs/images/crane.png?v=4&h=100&w=100&fit=cover&maxage=7d"></a> | A malware analysis platform that uses the MACO model to export malware configuration extractions into a parseable, machine-friendly format | [](https://github.com/CybercentreCanada/assemblyline/blob/main/LICENSE.md) |
|
|
70
71
|
| [configextractor-py](https://github.com/CybercentreCanada/configextractor-py) | A tool designed to run extractors from multiple frameworks and uses the MACO model for output harmonization | [](https://github.com/CybercentreCanada/configextractor-py/blob/main/LICENSE.md) |
|
|
71
72
|
| <a href="https://github.com/jeFF0Falltrades/rat_king_parser"><img src="https://images.weserv.nl/?url=raw.githubusercontent.com/jeFF0Falltrades/rat_king_parser/master/.github/logo.png?v=4&h=100&w=100&fit=cover&maxage=7d"/> </a> | A robust, multiprocessing-capable, multi-family RAT config parser/extractor that is compatible with MACO | [](https://github.com/jeFF0Falltrades/rat_king_parser/blob/master/LICENSE) |
|
|
72
|
-
| <a href="https://github.com/apophis133/apophis-YARA-Rules"><img src="https://images.weserv.nl/?url=github.com/apophis133.png?v=4&h=100&w=100&fit=cover&maxage=7d"/> </a> | A parser/extractor repository that supports MACO for performing malware configuration extraction with YARA rule detection | |
|
|
73
73
|
| <a href="https://github.com/CAPESandbox/community"><img src="https://images.weserv.nl/?url=github.com/CAPESandbox.png?v=4&h=100&w=100&fit=cover&maxage=7d0&mask=circle"/> </a> | A parser/extractor repository containing MACO extractors that's authored by the CAPE community but is integrated in [CAPE](https://github.com/kevoreilly/CAPEv2) deployments.<br>**Note: These MACO extractors wrap and parse the original CAPE extractors.** | [](https://github.com/kevoreilly/CAPEv2/blob/master/LICENSE) |
|
|
74
74
|
|
|
75
75
|
## Model Example
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
demo_extractors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
demo_extractors/elfy.py,sha256=PQpX956WaKmGzxF0pvpXECbwSPF_j3-_SElvboYPlF8,1083
|
|
3
|
+
demo_extractors/limit_other.py,sha256=lR0-7KPPDyl2UK917ev7ALhqvnPcFGsUObq7b-dESBE,1718
|
|
4
|
+
demo_extractors/nothing.py,sha256=0pLL9vZESWSdNOmtzTv33Ird0QaQUmXmeW_rwu6MExU,784
|
|
5
|
+
demo_extractors/requirements.txt,sha256=nD7BPNv7YEPUr9MDcaKYNs2UfHtxvN8FOKKesgC_L5g,50
|
|
6
|
+
demo_extractors/shared.py,sha256=GxdUKic4N1Bu2dODo-zjvm8JMLxFIXGkgoz4PUBo-Xw,432
|
|
7
|
+
demo_extractors/terminator.py,sha256=nxoZYRteYDQS7wp-aAsCaxCSJ9FSE54jPrW3fJpRVho,925
|
|
8
|
+
demo_extractors/complex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
demo_extractors/complex/complex.py,sha256=GYKmPOD8-fyVHxwjZb-3t1IghKVMuLtdUvCs5C5yPe0,2625
|
|
10
|
+
demo_extractors/complex/complex_utils.py,sha256=5kdMl-niSH9d-d3ChuItpmlPT4U-S9g-iyBZlR4tfmQ,296
|
|
11
|
+
maco/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
maco/base_test.py,sha256=DrVE7vOazeLQpOQeIDwBYK1WtlmdJrRe50JOqP5t4Y0,3198
|
|
13
|
+
maco/cli.py,sha256=nrSukAJAthbstZT3-lQNPz4zOOMcBhvfYQqLh_B5Jdk,9457
|
|
14
|
+
maco/collector.py,sha256=R3zw-fUJBlwmcSqvkQ-PnoJdHfRm2V0JAOl7N8MTAbY,8240
|
|
15
|
+
maco/exceptions.py,sha256=XBHUrs1kr1ZayPI9B_W-WejKgVmC8sWL_o4RL0b4DQE,745
|
|
16
|
+
maco/extractor.py,sha256=s36aGcsXSc-9iCik6iihVt5G1a1DZUA7TquvWYQNwdE,2912
|
|
17
|
+
maco/utils.py,sha256=wzecqu1W_BbhDHSs07sweOKNeFrmC4CDYmAN_qyYJS4,23362
|
|
18
|
+
maco/yara.py,sha256=gkHHxwZNxzZV7nHZM3HNUmhHXB7VW82voCHK5mHpt2Q,3970
|
|
19
|
+
maco/model/__init__.py,sha256=ULdyHx8R5D2ICHZo3VoCk1YTlewTok36TYIpwx__pNY,45
|
|
20
|
+
maco/model/model.py,sha256=DBHTmZXMzjpVq0s2mzZv3VCzPhwPnv7sH6u_QZCTcA4,24484
|
|
21
|
+
maco-1.2.16.dist-info/licenses/LICENSE.md,sha256=gMSjshPhXvV_F1qxmeNkKdBqGWkd__fEJf4glS504bM,1478
|
|
22
|
+
model_setup/maco/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
+
model_setup/maco/base_test.py,sha256=DrVE7vOazeLQpOQeIDwBYK1WtlmdJrRe50JOqP5t4Y0,3198
|
|
24
|
+
model_setup/maco/cli.py,sha256=nrSukAJAthbstZT3-lQNPz4zOOMcBhvfYQqLh_B5Jdk,9457
|
|
25
|
+
model_setup/maco/collector.py,sha256=R3zw-fUJBlwmcSqvkQ-PnoJdHfRm2V0JAOl7N8MTAbY,8240
|
|
26
|
+
model_setup/maco/exceptions.py,sha256=XBHUrs1kr1ZayPI9B_W-WejKgVmC8sWL_o4RL0b4DQE,745
|
|
27
|
+
model_setup/maco/extractor.py,sha256=s36aGcsXSc-9iCik6iihVt5G1a1DZUA7TquvWYQNwdE,2912
|
|
28
|
+
model_setup/maco/utils.py,sha256=wzecqu1W_BbhDHSs07sweOKNeFrmC4CDYmAN_qyYJS4,23362
|
|
29
|
+
model_setup/maco/yara.py,sha256=gkHHxwZNxzZV7nHZM3HNUmhHXB7VW82voCHK5mHpt2Q,3970
|
|
30
|
+
model_setup/maco/model/__init__.py,sha256=ULdyHx8R5D2ICHZo3VoCk1YTlewTok36TYIpwx__pNY,45
|
|
31
|
+
model_setup/maco/model/model.py,sha256=DBHTmZXMzjpVq0s2mzZv3VCzPhwPnv7sH6u_QZCTcA4,24484
|
|
32
|
+
pipelines/publish.yaml,sha256=xt3WNU-5kIICJgKIiiE94M3dWjS3uEiun-n4OmIssK8,1471
|
|
33
|
+
pipelines/test.yaml,sha256=btJVI-R39UBeYosGu7TOpU6V9ogFW3FT3ROtWygQGQ0,1472
|
|
34
|
+
tests/data/example.txt.cart,sha256=j4ZdDnFNVq7lb-Qi4pY4evOXKQPKG-GSg-n-uEqPhV0,289
|
|
35
|
+
tests/data/trigger_complex.txt,sha256=uqnLSrnyDGCmXwuPmZ2s8vdhH0hJs8DxvyaW_tuYY24,64
|
|
36
|
+
tests/data/trigger_complex.txt.cart,sha256=Z7qF1Zi640O45Znkl9ooP2RhSLAEqY0NRf51d-q7utU,345
|
|
37
|
+
tests/extractors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
38
|
+
tests/extractors/basic.py,sha256=BpOgVoeeAYoRF4PYDP4llS0GrvlqcEKw1588RsnSHFc,952
|
|
39
|
+
tests/extractors/basic_longer.py,sha256=2I7wWJugOB9tHtgdIvG9crbV9pEuDsuvr9OR-aHRRbs,990
|
|
40
|
+
tests/extractors/test_basic.py,sha256=RZPKBP6we2DlY2qpbxYjvf8u-TPcD96ofphLQ117WPk,775
|
|
41
|
+
tests/extractors/bob/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
42
|
+
tests/extractors/bob/bob.py,sha256=4fpqy_O6NDinJImghyW5OwYgnaB05aY4kgoIS_C3c_U,253
|
|
43
|
+
tests/extractors/import_rewriting/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
44
|
+
tests/extractors/import_rewriting/importer.py,sha256=wqF1AG2zXXuj9EMt9qlDorab-UD0GYuFggtrCuz4sf0,289735
|
|
45
|
+
maco-1.2.16.dist-info/METADATA,sha256=v5ZV9RoifsSn6im1tO0wpUJeKPGW3Wf-_C_BjF7qNmM,15232
|
|
46
|
+
maco-1.2.16.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
47
|
+
maco-1.2.16.dist-info/entry_points.txt,sha256=TpcwG1gedIg8Y7a9ZOv8aQpuwEUftCefDrAjzeP-o6U,39
|
|
48
|
+
maco-1.2.16.dist-info/top_level.txt,sha256=iMRwuzmrHA3zSwiSeMIl6FWhzRpn_st-I4fAv-kw5_o,49
|
|
49
|
+
maco-1.2.16.dist-info/RECORD,,
|
model_setup/maco/base_test.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Foundation for unit testing an extractor.
|
|
2
2
|
|
|
3
3
|
Example:
|
|
4
|
-
|
|
5
4
|
from maco import base_test
|
|
6
5
|
class TestExample(base_test.BaseTest):
|
|
7
6
|
name = "Example"
|
|
@@ -20,13 +19,12 @@ import unittest
|
|
|
20
19
|
import cart
|
|
21
20
|
|
|
22
21
|
from maco import collector
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
class NoHitException(Exception):
|
|
26
|
-
pass
|
|
22
|
+
from maco.exceptions import NoHitException
|
|
27
23
|
|
|
28
24
|
|
|
29
25
|
class BaseTest(unittest.TestCase):
|
|
26
|
+
"""Base test class."""
|
|
27
|
+
|
|
30
28
|
name: str = None # name of the extractor
|
|
31
29
|
# folder and/or file where extractor is.
|
|
32
30
|
# I recommend something like os.path.join(__file__, "../../extractors")
|
|
@@ -36,6 +34,11 @@ class BaseTest(unittest.TestCase):
|
|
|
36
34
|
|
|
37
35
|
@classmethod
|
|
38
36
|
def setUpClass(cls) -> None:
|
|
37
|
+
"""Initialization of class.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
Exception: when name or path is not set.
|
|
41
|
+
"""
|
|
39
42
|
if not cls.name or not cls.path:
|
|
40
43
|
raise Exception("name and path must be set")
|
|
41
44
|
cls.c = collector.Collector(cls.path, include=[cls.name], create_venv=cls.create_venv)
|
|
@@ -47,7 +50,11 @@ class BaseTest(unittest.TestCase):
|
|
|
47
50
|
self.assertEqual(len(self.c.extractors), 1)
|
|
48
51
|
|
|
49
52
|
def extract(self, stream):
|
|
50
|
-
"""Return results for running extractor over stream, including yara check.
|
|
53
|
+
"""Return results for running extractor over stream, including yara check.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
NoHitException: when yara rule doesn't hit.
|
|
57
|
+
"""
|
|
51
58
|
runs = self.c.match(stream)
|
|
52
59
|
if not runs:
|
|
53
60
|
raise NoHitException("no yara rule hit")
|
|
@@ -65,7 +72,17 @@ class BaseTest(unittest.TestCase):
|
|
|
65
72
|
|
|
66
73
|
@classmethod
|
|
67
74
|
def load_cart(cls, filepath: str) -> io.BytesIO:
|
|
68
|
-
"""Load and unneuter a test file (likely malware) into memory for processing.
|
|
75
|
+
"""Load and unneuter a test file (likely malware) into memory for processing.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
filepath (str): Path to carted sample
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
(io.BytesIO): Buffered stream containing the un-carted sample
|
|
82
|
+
|
|
83
|
+
Raises:
|
|
84
|
+
FileNotFoundError: if the path to the sample doesn't exist
|
|
85
|
+
"""
|
|
69
86
|
# it is nice if we can load files relative to whatever is implementing base_test
|
|
70
87
|
dirpath = os.path.split(cls._get_location())[0]
|
|
71
88
|
# either filepath is absolute, or should be loaded relative to child of base_test
|
model_setup/maco/cli.py
CHANGED
|
@@ -3,19 +3,18 @@
|
|
|
3
3
|
import argparse
|
|
4
4
|
import base64
|
|
5
5
|
import binascii
|
|
6
|
-
import cart
|
|
7
6
|
import hashlib
|
|
8
7
|
import io
|
|
9
8
|
import json
|
|
10
9
|
import logging
|
|
11
10
|
import os
|
|
12
11
|
import sys
|
|
13
|
-
|
|
14
12
|
from importlib.metadata import version
|
|
15
13
|
from typing import BinaryIO, List, Tuple
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
import cart
|
|
18
16
|
|
|
17
|
+
from maco import collector
|
|
19
18
|
|
|
20
19
|
logger = logging.getLogger("maco.lib.cli")
|
|
21
20
|
|
|
@@ -29,7 +28,20 @@ def process_file(
|
|
|
29
28
|
force: bool,
|
|
30
29
|
include_base64: bool,
|
|
31
30
|
):
|
|
32
|
-
"""Process a filestream with the extractors and rules.
|
|
31
|
+
"""Process a filestream with the extractors and rules.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
collected (collector.Collector): a Collector instance
|
|
35
|
+
path_file (str): path to sample to be analyzed
|
|
36
|
+
stream (BinaryIO): binary stream to be analyzed
|
|
37
|
+
pretty (bool): Pretty print the JSON output
|
|
38
|
+
force (bool): Run all extractors regardless of YARA rule match
|
|
39
|
+
include_base64 (bool): include base64'd data in output
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
(dict): The output from the extractors analyzing the sample
|
|
43
|
+
|
|
44
|
+
"""
|
|
33
45
|
unneutered = io.BytesIO()
|
|
34
46
|
try:
|
|
35
47
|
cart.unpack_stream(stream, unneutered)
|
|
@@ -98,7 +110,8 @@ def process_filesystem(
|
|
|
98
110
|
) -> Tuple[int, int, int]:
|
|
99
111
|
"""Process filesystem with extractors and print results of extraction.
|
|
100
112
|
|
|
101
|
-
Returns
|
|
113
|
+
Returns:
|
|
114
|
+
(Tuple[int, int, int]): Total number of analysed files, yara hits and successful maco extractions.
|
|
102
115
|
"""
|
|
103
116
|
if force:
|
|
104
117
|
logger.warning("force execute will cause errors if an extractor requires a yara rule hit during execution")
|
|
@@ -163,6 +176,7 @@ def process_filesystem(
|
|
|
163
176
|
|
|
164
177
|
|
|
165
178
|
def main():
|
|
179
|
+
"""Main block for CLI."""
|
|
166
180
|
parser = argparse.ArgumentParser(description="Run extractors over samples.")
|
|
167
181
|
parser.add_argument("extractors", type=str, help="path to extractors")
|
|
168
182
|
parser.add_argument("samples", type=str, help="path to samples")
|