|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2025 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +""" |
| 17 | +Fetch the VMRay Function Log (flog.txt) for a sample and optionally run capa against it. |
| 18 | +
|
| 19 | +Given a sample SHA-256 hash and VMRay credentials, this script: |
| 20 | + 1. Looks up the sample on the VMRay instance. |
| 21 | + 2. Finds the most-recent analysis for that sample. |
| 22 | + 3. Downloads the flog.txt (Download Function Log) from the analysis archive. |
| 23 | + 4. Optionally runs capa against the downloaded file. |
| 24 | +
|
| 25 | +Requirements: |
| 26 | + pip install requests |
| 27 | +
|
| 28 | +Usage:: |
| 29 | +
|
| 30 | + python scripts/fetch-vmray-flog.py \\ |
| 31 | + --url https://your-vmray.example.com \\ |
| 32 | + --apikey YOUR_API_KEY \\ |
| 33 | + --sha256 d46900384c78863420fb3e297d0a2f743cd2b6b3f7f82bf64059a168e07aceb7 \\ |
| 34 | + --output /tmp/sample_flog.txt |
| 35 | +
|
| 36 | + # Fetch and immediately run capa: |
| 37 | + python scripts/fetch-vmray-flog.py \\ |
| 38 | + --url https://your-vmray.example.com \\ |
| 39 | + --apikey YOUR_API_KEY \\ |
| 40 | + --sha256 d46900384c78863420fb3e297d0a2f743cd2b6b3f7f82bf64059a168e07aceb7 \\ |
| 41 | + --run-capa |
| 42 | +
|
| 43 | +VMRay API reference: |
| 44 | + https://docs.vmray.com/documents/api-reference/ |
| 45 | +
|
| 46 | +Note: this script requires a VMRay account. The flog.txt itself is freely available |
| 47 | +("Download Function Log") in the VMRay Threat Feed web UI, but downloading it |
| 48 | +programmatically via the REST API requires valid API credentials. |
| 49 | +""" |
| 50 | + |
| 51 | +import argparse |
| 52 | +import logging |
| 53 | +import subprocess |
| 54 | +import sys |
| 55 | +from pathlib import Path |
| 56 | + |
| 57 | +import requests |
| 58 | + |
| 59 | +logger = logging.getLogger(__name__) |
| 60 | + |
| 61 | +# --------------------------------------------------------------------------- |
| 62 | +# VMRay REST API helpers |
| 63 | +# --------------------------------------------------------------------------- |
| 64 | + |
| 65 | +_FLOG_TXT_ARCHIVE_PATH = "logs/flog_txt" |
| 66 | + |
| 67 | + |
| 68 | +def _session(url: str, apikey: str) -> requests.Session: |
| 69 | + """Return an authenticated requests.Session for the given VMRay instance.""" |
| 70 | + s = requests.Session() |
| 71 | + s.headers.update( |
| 72 | + { |
| 73 | + "Authorization": f"api_key {apikey}", |
| 74 | + "Accept": "application/json", |
| 75 | + } |
| 76 | + ) |
| 77 | + s.verify = True # set to False only when using self-signed certificates |
| 78 | + s.base_url = url.rstrip("/") # type: ignore[attr-defined] |
| 79 | + return s |
| 80 | + |
| 81 | + |
| 82 | +def _get(session: requests.Session, path: str, **kwargs) -> dict: |
| 83 | + url = f"{session.base_url}{path}" # type: ignore[attr-defined] |
| 84 | + resp = session.get(url, **kwargs) |
| 85 | + resp.raise_for_status() |
| 86 | + return resp.json() |
| 87 | + |
| 88 | + |
| 89 | +def _get_bytes(session: requests.Session, path: str, **kwargs) -> bytes: |
| 90 | + url = f"{session.base_url}{path}" # type: ignore[attr-defined] |
| 91 | + resp = session.get(url, **kwargs) |
| 92 | + resp.raise_for_status() |
| 93 | + return resp.content |
| 94 | + |
| 95 | + |
| 96 | +def lookup_sample(session: requests.Session, sha256: str) -> dict: |
| 97 | + """ |
| 98 | + Return the VMRay sample record for the given SHA-256. |
| 99 | + Raises ValueError if the sample is not found. |
| 100 | + """ |
| 101 | + data = _get(session, f"/rest/sample/sha256/{sha256}") |
| 102 | + if data.get("result") != "ok" or not data.get("data"): |
| 103 | + raise ValueError(f"sample not found on VMRay instance: {sha256}") |
| 104 | + # data["data"] is a list; take the first entry |
| 105 | + return data["data"][0] |
| 106 | + |
| 107 | + |
| 108 | +def get_latest_analysis(session: requests.Session, sample_id: int) -> dict: |
| 109 | + """ |
| 110 | + Return the most-recent finished analysis for the given VMRay sample ID. |
| 111 | + Raises ValueError if no analysis is found. |
| 112 | + """ |
| 113 | + data = _get(session, "/rest/analysis", params={"sample_id": sample_id}) |
| 114 | + analyses = data.get("data", []) |
| 115 | + if not analyses: |
| 116 | + raise ValueError(f"no analyses found for sample_id={sample_id}") |
| 117 | + # Sort by analysis_id descending (newest first) |
| 118 | + analyses.sort(key=lambda a: a.get("analysis_id", 0), reverse=True) |
| 119 | + return analyses[0] |
| 120 | + |
| 121 | + |
| 122 | +def download_flog_txt(session: requests.Session, analysis_id: int) -> bytes: |
| 123 | + """ |
| 124 | + Download the flog.txt content for the given VMRay analysis ID. |
| 125 | +
|
| 126 | + VMRay exposes the function log via the analysis archive endpoint. |
| 127 | + We request only the flog_txt entry from the archive using the |
| 128 | + ``file_filter`` query parameter. |
| 129 | + """ |
| 130 | + # Try the dedicated log endpoint first (VMRay >= 2024.x) |
| 131 | + try: |
| 132 | + content = _get_bytes( |
| 133 | + session, |
| 134 | + f"/rest/analysis/{analysis_id}/export/v2/logs/flog_txt/binary", |
| 135 | + ) |
| 136 | + if content: |
| 137 | + return content |
| 138 | + except requests.HTTPError: |
| 139 | + pass |
| 140 | + |
| 141 | + # Fallback: download via the analysis archive with a file filter |
| 142 | + content = _get_bytes( |
| 143 | + session, |
| 144 | + f"/rest/analysis/{analysis_id}/archive", |
| 145 | + params={"file_filter[]": _FLOG_TXT_ARCHIVE_PATH}, |
| 146 | + ) |
| 147 | + return content |
| 148 | + |
| 149 | + |
| 150 | +# --------------------------------------------------------------------------- |
| 151 | +# main |
| 152 | +# --------------------------------------------------------------------------- |
| 153 | + |
| 154 | + |
| 155 | +def main(argv=None): |
| 156 | + if argv is None: |
| 157 | + argv = sys.argv[1:] |
| 158 | + |
| 159 | + parser = argparse.ArgumentParser( |
| 160 | + description="Download VMRay flog.txt for a sample hash and (optionally) run capa." |
| 161 | + ) |
| 162 | + parser.add_argument( |
| 163 | + "--url", |
| 164 | + required=True, |
| 165 | + metavar="URL", |
| 166 | + help="Base URL of your VMRay instance, e.g. https://cloud.vmray.com", |
| 167 | + ) |
| 168 | + parser.add_argument( |
| 169 | + "--apikey", |
| 170 | + required=True, |
| 171 | + metavar="KEY", |
| 172 | + help="VMRay REST API key (Settings → API Keys).", |
| 173 | + ) |
| 174 | + parser.add_argument( |
| 175 | + "--sha256", |
| 176 | + required=True, |
| 177 | + metavar="SHA256", |
| 178 | + help="SHA-256 hash of the sample to analyse.", |
| 179 | + ) |
| 180 | + parser.add_argument( |
| 181 | + "--output", |
| 182 | + metavar="PATH", |
| 183 | + help="Where to save the downloaded flog.txt. Defaults to <sha256>_flog.txt in the current directory.", |
| 184 | + ) |
| 185 | + parser.add_argument( |
| 186 | + "--run-capa", |
| 187 | + action="store_true", |
| 188 | + dest="run_capa", |
| 189 | + help="After downloading, run 'capa <output>' and print the results.", |
| 190 | + ) |
| 191 | + parser.add_argument( |
| 192 | + "--capa-args", |
| 193 | + metavar="ARGS", |
| 194 | + default="", |
| 195 | + help="Extra arguments forwarded to capa (only used with --run-capa).", |
| 196 | + ) |
| 197 | + parser.add_argument( |
| 198 | + "--no-verify-ssl", |
| 199 | + action="store_false", |
| 200 | + dest="verify_ssl", |
| 201 | + help="Disable SSL certificate verification (useful for on-premise instances with self-signed certs).", |
| 202 | + ) |
| 203 | + parser.add_argument( |
| 204 | + "-d", "--debug", action="store_true", help="Enable debug logging." |
| 205 | + ) |
| 206 | + args = parser.parse_args(argv) |
| 207 | + |
| 208 | + logging.basicConfig( |
| 209 | + level=logging.DEBUG if args.debug else logging.INFO, |
| 210 | + format="%(levelname)s: %(message)s", |
| 211 | + ) |
| 212 | + |
| 213 | + output_path = Path(args.output) if args.output else Path(f"{args.sha256}_flog.txt") |
| 214 | + |
| 215 | + session = _session(args.url, args.apikey) |
| 216 | + session.verify = args.verify_ssl # type: ignore[assignment] |
| 217 | + |
| 218 | + # Step 1 — look up sample |
| 219 | + logger.info("looking up sample %s …", args.sha256) |
| 220 | + try: |
| 221 | + sample = lookup_sample(session, args.sha256) |
| 222 | + except (requests.HTTPError, ValueError) as exc: |
| 223 | + logger.error("failed to find sample: %s", exc) |
| 224 | + return 1 |
| 225 | + |
| 226 | + sample_id: int = sample["sample_id"] |
| 227 | + logger.debug("found sample_id=%d", sample_id) |
| 228 | + |
| 229 | + # Step 2 — find the latest analysis |
| 230 | + logger.info("fetching analysis list for sample_id=%d …", sample_id) |
| 231 | + try: |
| 232 | + analysis = get_latest_analysis(session, sample_id) |
| 233 | + except (requests.HTTPError, ValueError) as exc: |
| 234 | + logger.error("failed to find analysis: %s", exc) |
| 235 | + return 1 |
| 236 | + |
| 237 | + analysis_id: int = analysis["analysis_id"] |
| 238 | + logger.debug("using analysis_id=%d", analysis_id) |
| 239 | + |
| 240 | + # Step 3 — download flog.txt |
| 241 | + logger.info("downloading flog.txt for analysis_id=%d …", analysis_id) |
| 242 | + try: |
| 243 | + flog_bytes = download_flog_txt(session, analysis_id) |
| 244 | + except requests.HTTPError as exc: |
| 245 | + logger.error("failed to download flog.txt: %s", exc) |
| 246 | + return 1 |
| 247 | + |
| 248 | + if not flog_bytes: |
| 249 | + logger.error( |
| 250 | + "received empty response — flog.txt may not be available for this analysis" |
| 251 | + ) |
| 252 | + return 1 |
| 253 | + |
| 254 | + output_path.write_bytes(flog_bytes) |
| 255 | + logger.info("saved flog.txt → %s (%d bytes)", output_path, len(flog_bytes)) |
| 256 | + |
| 257 | + # Step 4 (optional) — run capa |
| 258 | + if args.run_capa: |
| 259 | + capa_cmd = ["capa", str(output_path)] + ( |
| 260 | + args.capa_args.split() if args.capa_args else [] |
| 261 | + ) |
| 262 | + logger.info("running: %s", " ".join(capa_cmd)) |
| 263 | + result = subprocess.run(capa_cmd) |
| 264 | + return result.returncode |
| 265 | + |
| 266 | + return 0 |
| 267 | + |
| 268 | + |
| 269 | +if __name__ == "__main__": |
| 270 | + sys.exit(main()) |
0 commit comments