|
| 1 | +import os |
| 2 | +import zipfile |
| 3 | +import logging |
| 4 | + |
1 | 5 | from lib.common.abstracts import Package |
2 | 6 | from lib.common.common import check_file_extension |
3 | 7 | from lib.common.constants import OPT_ARGUMENTS |
4 | 8 |
|
| 9 | +log = logging.getLogger(__name__) |
| 10 | + |
| 11 | +# CONFIGURATION - allow non installed nodejs |
| 12 | +# Best practice: Keep filenames in one place |
| 13 | +# Grab a copy of https://nodejs.org/download/release/latest-v25.x/node-v25.2.1-win-x64.zip or another version of your interest |
| 14 | +# Store it in extras as nodejs.zip |
| 15 | +NODE_ZIP_NAME = "nodejs.zip" |
| 16 | +NODE_DIR_NAME = "nodejs" |
| 17 | + |
| 18 | + |
| 19 | +def setup_node_environment(): |
| 20 | + """ |
| 21 | + Attempts to unzip a portable Node environment. |
| 22 | + Returns: (path_to_node_exe, None) on success (None, error_message) on failure |
| 23 | + """ |
| 24 | + try: |
| 25 | + # Determine paths |
| 26 | + user_profile = os.environ.get("USERPROFILE", "C:\\Users\\Admin") |
| 27 | + install_path = os.path.join(user_profile, "AppData", "Local", "app") |
| 28 | + |
| 29 | + # Look for zip in absolute path relative to current execution or fixed 'extras' |
| 30 | + # Assuming 'extras' is in the current working dir of the analyzer |
| 31 | + node_zip_path = os.path.abspath(os.path.join("extras", NODE_ZIP_NAME)) |
| 32 | + node_bin_path = os.path.join(install_path, NODE_DIR_NAME) |
| 33 | + |
| 34 | + if not os.path.exists(node_zip_path): |
| 35 | + return None, f"Zip not found at {node_zip_path}" |
| 36 | + |
| 37 | + if not os.path.exists(node_bin_path): |
| 38 | + os.makedirs(node_bin_path) |
| 39 | + |
| 40 | + node_exe_path = None |
| 41 | + |
| 42 | + # 1. Open Zip and Find node.exe BEFORE extracting |
| 43 | + with zipfile.ZipFile(node_zip_path, 'r') as z: |
| 44 | + # list of all files in zip |
| 45 | + file_list = z.namelist() |
| 46 | + |
| 47 | + # Find the internal path to node.exe |
| 48 | + # This works for both "node.exe" (root) and "node-v25.../node.exe" (subfolder) |
| 49 | + node_internal_path = next((f for f in file_list if f.lower().endswith("node.exe")), None) |
| 50 | + |
| 51 | + if not node_internal_path: |
| 52 | + return None, "Archive does not contain node.exe" |
| 53 | + |
| 54 | + # 2. Extract |
| 55 | + # We extract to a specific folder to avoid cluttering if it's a "root-files" zip |
| 56 | + # We use the zip name (minus extension) as a container folder |
| 57 | + extract_path = node_bin_path |
| 58 | + |
| 59 | + if not os.path.exists(extract_path): |
| 60 | + # Security: Check for path traversal before extraction. |
| 61 | + for member in z.infolist(): |
| 62 | + if member.filename.startswith("/") or ".." in member.filename: |
| 63 | + return None, f"Aborting extraction. Zip contains potentially malicious path: {member.filename}" |
| 64 | + |
| 65 | + os.makedirs(extract_path) |
| 66 | + log.info("Extracting to %s...", extract_path) |
| 67 | + z.extractall(extract_path) |
| 68 | + |
| 69 | + # 3. Construct the full path |
| 70 | + # extract_path + internal_path_inside_zip |
| 71 | + # e.g. C:\Apps\node-v25\ + node-v25-win-x64/node.exe |
| 72 | + node_exe_path = os.path.join(extract_path, node_internal_path) |
| 73 | + |
| 74 | + # Normalizing path separators (fixes mix of / and \) |
| 75 | + node_exe_path = os.path.normpath(node_exe_path) |
| 76 | + |
| 77 | + # 4. Final Verification and Env Setup |
| 78 | + if node_exe_path and os.path.exists(node_exe_path): |
| 79 | + # Add the folder containing node.exe to PATH |
| 80 | + node_dir = os.path.dirname(node_exe_path) |
| 81 | + current_path = os.environ.get("PATH", "") |
| 82 | + os.environ["PATH"] = f"{node_dir};{current_path}" |
| 83 | + |
| 84 | + return node_exe_path, None |
| 85 | + else: |
| 86 | + return None, "Extraction finished but node.exe not found on disk." |
| 87 | + |
| 88 | + except (zipfile.BadZipFile, OSError) as e: |
| 89 | + return None, f"Exception during Node setup: {str(e)}" |
| 90 | + |
5 | 91 |
|
6 | 92 | class NodeJS(Package): |
7 | 93 | """Package for executing JavaScript files using NodeJS.""" |
8 | 94 |
|
9 | 95 | PATHS = [ |
10 | | - ("ProgramFiles", "NodeJS", "node.exe"), |
| 96 | + # Standard 64-bit Install (most common) |
| 97 | + # Default folder is usually lowercase "nodejs" |
| 98 | + ("ProgramFiles", "nodejs", "node.exe"), |
| 99 | + |
| 100 | + # 32-bit Node on 64-bit Windows |
| 101 | + ("ProgramFiles(x86)", "nodejs", "node.exe"), |
| 102 | + |
| 103 | + # Your specific custom paths (Case insensitive, so NodeJS works too) |
11 | 104 | ("LOCALAPPDATA", "Programs", "NodeJS", "node.exe"), |
| 105 | + |
| 106 | + # Fallback for manual installs at root |
| 107 | + ("SystemDrive", "nodejs", "node.exe"), |
12 | 108 | ] |
| 109 | + |
13 | 110 | summary = "Executes a JS sample using NodeJS." |
14 | | - description = "Uses node.exe instead of wscript.exe to execute JavaScript files." |
| 111 | + description = "Uses node.exe to execute JavaScript files." |
15 | 112 | option_names = (OPT_ARGUMENTS,) |
16 | 113 |
|
17 | 114 | def start(self, path): |
18 | | - node = self.get_path("node.exe") |
19 | 115 | path = check_file_extension(path, ".js") |
20 | 116 | args = self.options.get(OPT_ARGUMENTS, "") |
21 | | - return self.execute(node, f'"{path}" {args}', path) |
| 117 | + |
| 118 | + # Prepare the argument list |
| 119 | + # CAPE expects a list of arguments for the process |
| 120 | + node_args = f'"{path}"' |
| 121 | + |
| 122 | + # Append additional arguments if they exist |
| 123 | + if args: |
| 124 | + node_args += f" {args}" |
| 125 | + |
| 126 | + # 1. Try to set up Custom Node |
| 127 | + binary = None |
| 128 | + |
| 129 | + # Check if the zip exists before trying setup |
| 130 | + if os.path.exists(os.path.join("extras", NODE_ZIP_NAME)): |
| 131 | + custom_bin, error = setup_node_environment() |
| 132 | + if custom_bin: |
| 133 | + binary = custom_bin |
| 134 | + log.info("Using Custom Node.js: %s", binary) |
| 135 | + else: |
| 136 | + log.error("Failed to setup Custom Node: %s", error) |
| 137 | + # Do NOT return here, fall through to system node |
| 138 | + |
| 139 | + # 2. Fallback to System Node if custom failed or zip missing |
| 140 | + if not binary: |
| 141 | + log.info("Falling back to system installed Node.js") |
| 142 | + binary = self.get_path("node.exe") |
| 143 | + |
| 144 | + # 3. Execution |
| 145 | + if not binary: |
| 146 | + raise Exception("Node.js executable not found in custom bundle OR system paths.") |
| 147 | + |
| 148 | + return self.execute(binary, node_args, path) |
0 commit comments