|
| 1 | +import os |
| 2 | +import logging |
| 3 | +import zipfile |
| 4 | +import shutil |
| 5 | +from pathlib import Path |
| 6 | +from typing import Any, List, Dict |
| 7 | +import importlib.util |
| 8 | +from lib.cuckoo.core.data import task as db_task |
| 9 | +from lib.cuckoo.core.data.audit_data import TEST_RUNNING, TEST_COMPLETE, TEST_FAILED, TEST_QUEUED |
| 10 | + |
| 11 | +log = logging.getLogger(__name__) |
| 12 | + |
| 13 | +def load_module(module_path): |
| 14 | + module_name = "test_py_module" |
| 15 | + spec = importlib.util.spec_from_file_location(module_name, str(module_path)) |
| 16 | + module = importlib.util.module_from_spec(spec) |
| 17 | + spec.loader.exec_module(module) |
| 18 | + |
| 19 | + if not hasattr(module, 'CapeDynamicTest'): |
| 20 | + log.warning(str(dir(module))) |
| 21 | + raise ValueError("Module has no CapeDynamicTest class") |
| 22 | + tester = module.CapeDynamicTest() |
| 23 | + |
| 24 | + if not hasattr(tester, 'get_metadata'): |
| 25 | + raise ValueError(f"CapeDynamicTest from {module_path} lacks get_metadata() function") |
| 26 | + return tester |
| 27 | + |
| 28 | + |
| 29 | +class TestLoader(): |
| 30 | + def __init__(self, tests_directory): |
| 31 | + if not os.path.exists(tests_directory): |
| 32 | + raise ValueError(f"Tests directory '{tests_directory}' does not exist.") |
| 33 | + self.tests_root = tests_directory |
| 34 | + |
| 35 | + def _extract_payload(self, payload_archive, payload_output_dir, zip_password=None): |
| 36 | + |
| 37 | + # Verify payload ZIP integrity |
| 38 | + try: |
| 39 | + with zipfile.ZipFile(payload_archive, 'r') as z: |
| 40 | + # If a password is provided in JSON, verify we can access the list |
| 41 | + if zip_password: |
| 42 | + z.setpassword(zip_password.encode()) |
| 43 | + # Test if the zip is actually readable/not corrupt |
| 44 | + z.testzip() |
| 45 | + except zipfile.BadZipFile: |
| 46 | + if zip_password: |
| 47 | + raise zipfile.BadZipFile(f"{payload_archive} is not usable with the given password") |
| 48 | + else: |
| 49 | + raise zipfile.BadZipFile(f"{payload_archive} is corrupt") |
| 50 | + |
| 51 | + # delete the unwrapped payload in case a new zip has been uploaded |
| 52 | + if os.path.exists(payload_output_dir): |
| 53 | + shutil.rmtree(payload_output_dir) |
| 54 | + |
| 55 | + with zipfile.ZipFile(payload_archive, 'r') as zip_ref: |
| 56 | + if zip_password: |
| 57 | + zip_ref.extractall(payload_output_dir, pwd=zip_password) |
| 58 | + else: |
| 59 | + zip_ref.extractall(payload_output_dir) |
| 60 | + |
| 61 | + payload_path = None |
| 62 | + if not os.path.isdir(payload_output_dir): |
| 63 | + raise NotADirectoryError("Bad payload directory extracted") |
| 64 | + |
| 65 | + dir_path = Path(payload_output_dir) |
| 66 | + dir_contents = list(dir_path.iterdir()) |
| 67 | + if not dir_contents: |
| 68 | + raise FileNotFoundError("Nothing in extracted payload directory") |
| 69 | + |
| 70 | + if len(dir_contents) == 1: |
| 71 | + payload_path = str(dir_contents[0]) |
| 72 | + else: |
| 73 | + # If multiple items, treat the directory itself as the payload |
| 74 | + payload_path = payload_output_dir |
| 75 | + |
| 76 | + if not os.path.exists(payload_path): |
| 77 | + raise FileNotFoundError("Nothing extracted from payload archive or it could not be written to disk") |
| 78 | + |
| 79 | + return payload_path |
| 80 | + |
| 81 | + def validate_test_directory(self, test_path: str) -> Dict[str, Any]: |
| 82 | + """ |
| 83 | + Validates a single test directory and returns the metadata from the test module. |
| 84 | + Raises ValueError if the anything is invalid. |
| 85 | + """ |
| 86 | + payload_archive = os.path.join(test_path, "payload.zip") |
| 87 | + module_path = os.path.join(test_path, "test.py") |
| 88 | + |
| 89 | + # Check for required files |
| 90 | + if not os.path.exists(payload_archive): |
| 91 | + raise ValueError(f"Missing payload.zip in {payload_archive}") |
| 92 | + if not os.path.exists(module_path): |
| 93 | + raise ValueError(f"Missing test.py in {module_path}") |
| 94 | + |
| 95 | + test_metadata = {} |
| 96 | + test_metadata['module_path'] = module_path |
| 97 | + |
| 98 | + # Load and instantiate the python test module and fetch metadata |
| 99 | + try: |
| 100 | + tester = load_module(module_path) |
| 101 | + test_metadata['info'] = tester.get_metadata() |
| 102 | + |
| 103 | + test_metadata['objectives'] = [] |
| 104 | + |
| 105 | + def load_objective(objective): |
| 106 | + objdict = {'name': objective.name, |
| 107 | + 'requirement': objective.requirement, |
| 108 | + 'children': [load_objective(child) for child in objective.children] |
| 109 | + } |
| 110 | + return objdict |
| 111 | + for objective in tester.get_objectives(): |
| 112 | + test_metadata['objectives'].append(load_objective(objective)) |
| 113 | + |
| 114 | + except Exception as e: |
| 115 | + raise ValueError(f"Failed to load test module or fetch metadata from {module_path}: {e}") |
| 116 | + |
| 117 | + conf = test_metadata['info'].get("Task Config", None) |
| 118 | + if conf: |
| 119 | + if conf.get("Request Options",None) is None: |
| 120 | + test_metadata['info']["Request Options"] = "" |
| 121 | + |
| 122 | + if 'Name' not in test_metadata['info']: |
| 123 | + raise ValueError(f"Metadata in {module_path} missing 'Name' field") |
| 124 | + if 'Package' not in test_metadata['info']: |
| 125 | + raise ValueError(f"Metadata in {module_path} missing 'Package' field") |
| 126 | + |
| 127 | + zip_password = test_metadata['info'].get("Zip Password", None) |
| 128 | + payload_output_dir = os.path.join(test_path, "payload") |
| 129 | + test_metadata['payload_path'] = self._extract_payload(payload_archive, payload_output_dir, zip_password) |
| 130 | + |
| 131 | + # Return prepared metadata for DB ingest |
| 132 | + return test_metadata |
| 133 | + |
| 134 | + def load_tests(self) -> List[Dict[str, Any]]: |
| 135 | + """ |
| 136 | + Walks the root directory and yields validated test configurations. |
| 137 | + """ |
| 138 | + available_tests = [] |
| 139 | + unavailable_tests = [] |
| 140 | + |
| 141 | + if not os.path.exists(self.tests_root): |
| 142 | + log.error("Tests root %s does not exist.", self.tests_root) |
| 143 | + return {"error": f"Tests root {self.tests_root} does not exist."} |
| 144 | + |
| 145 | + for entry in os.scandir(self.tests_root): |
| 146 | + if entry.is_dir(): |
| 147 | + test_config = None |
| 148 | + try: |
| 149 | + test_config = self.validate_test_directory(entry.path) |
| 150 | + available_tests.append(test_config) |
| 151 | + log.info("Loaded test: %s",test_config['info']['Name']) |
| 152 | + except Exception as e: |
| 153 | + log.exception("Skipping directory %s due to exception",entry.path) |
| 154 | + unavailable_tests.append({"module_path":entry.path, "error":str(e)}) |
| 155 | + |
| 156 | + return {'available':available_tests, 'unavailable': unavailable_tests} |
| 157 | + |
| 158 | + |
| 159 | +class TestResultValidator(): |
| 160 | + def __init__(self, test_module_path:str, task_storage_directory: str): |
| 161 | + if os.path.isdir(task_storage_directory): |
| 162 | + self.task_directory = task_storage_directory |
| 163 | + else: |
| 164 | + raise NotADirectoryError(f"Invalid task directory: {task_storage_directory}") |
| 165 | + |
| 166 | + try: |
| 167 | + self.test_module = load_module(test_module_path) |
| 168 | + except Exception as e: |
| 169 | + raise ValueError(f"Failed to load test evaluation module {test_module_path}: {e}") |
| 170 | + |
| 171 | + def evaluate(self): |
| 172 | + self.test_module.evaluate_results(self.task_directory) |
| 173 | + return self.test_module.get_results() |
| 174 | + |
| 175 | +def task_status_to_run_status(cape_task_status): |
| 176 | + if cape_task_status == db_task.TASK_REPORTED: |
| 177 | + return TEST_COMPLETE |
| 178 | + if cape_task_status == db_task.TASK_PENDING: |
| 179 | + return TEST_QUEUED |
| 180 | + if cape_task_status in [db_task.TASK_RUNNING, |
| 181 | + db_task.TASK_DISTRIBUTED, |
| 182 | + db_task.TASK_RECOVERED, |
| 183 | + db_task.TASK_COMPLETED, |
| 184 | + db_task.TASK_DISTRIBUTED_COMPLETED]: |
| 185 | + return TEST_RUNNING |
| 186 | + if cape_task_status in [db_task.TASK_BANNED, |
| 187 | + db_task.TASK_FAILED_ANALYSIS, |
| 188 | + db_task.TASK_FAILED_PROCESSING, |
| 189 | + db_task.TASK_FAILED_REPORTING |
| 190 | + ]: |
| 191 | + return TEST_FAILED |
| 192 | + |
| 193 | + raise Exception(f"Unknown cape task status: {cape_task_status}") |
0 commit comments