verdyx 0.1.0__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.
verdyx/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """Verdyx malware and URL scanning.
2
+
3
+ from verdyx import Verdyx
4
+
5
+ client = Verdyx() # reads VERDYX_API_KEY
6
+ result = client.scan("suspicious.exe")
7
+ print(result.verdict, result.report_url)
8
+ """
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .client import ( # noqa: E402
13
+ DEFAULT_API_URL,
14
+ DEFAULT_WEB_URL,
15
+ EngineResult,
16
+ ScanResult,
17
+ ScanTimeoutError,
18
+ Submission,
19
+ Verdyx,
20
+ VerdyxError,
21
+ meets_threshold,
22
+ )
23
+
24
+ __all__ = [
25
+ "DEFAULT_API_URL",
26
+ "DEFAULT_WEB_URL",
27
+ "EngineResult",
28
+ "ScanResult",
29
+ "ScanTimeoutError",
30
+ "Submission",
31
+ "Verdyx",
32
+ "VerdyxError",
33
+ "meets_threshold",
34
+ "__version__",
35
+ ]
verdyx/client.py ADDED
@@ -0,0 +1,396 @@
1
+ """Verdyx API client. Standard library only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import random
8
+ import re
9
+ import time
10
+ import uuid
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Callable, Dict, List, Optional, Union
14
+ from urllib import error as urlerror
15
+ from urllib import request as urlrequest
16
+ from urllib.parse import quote
17
+
18
+ from . import __version__
19
+
20
+ DEFAULT_API_URL = "https://api.verdyx.dev"
21
+ DEFAULT_WEB_URL = "https://verdyx.dev"
22
+
23
+ _FINISHED = {"completed", "failed"}
24
+ _RANK = {"clean": 0, "unknown": 0, "suspicious": 1, "malicious": 2}
25
+ _RETRYABLE = {429, 502, 503, 504}
26
+
27
+
28
+ class VerdyxError(Exception):
29
+ """An error from the API or the client.
30
+
31
+ ``status`` is the HTTP status when the API answered, ``body`` its parsed
32
+ response and ``retry_after`` the seconds from a Retry-After header.
33
+ """
34
+
35
+ def __init__(self, message: str, status: Optional[int] = None, body: Any = None,
36
+ retry_after: Optional[float] = None) -> None:
37
+ super().__init__(message)
38
+ self.status = status
39
+ self.body = body
40
+ self.retry_after = retry_after
41
+
42
+
43
+ class ScanTimeoutError(VerdyxError):
44
+ """The scan didn't finish in time. It keeps running on the server."""
45
+
46
+ def __init__(self, submission_id: str, seconds: float) -> None:
47
+ super().__init__(f"scan {submission_id} did not finish within {seconds:g}s")
48
+ self.submission_id = submission_id
49
+
50
+
51
+ @dataclass
52
+ class Submission:
53
+ id: str
54
+ status: str
55
+ sha256: Optional[str] = None
56
+ filename: Optional[str] = None
57
+ type: Optional[str] = None
58
+
59
+
60
+ @dataclass
61
+ class EngineResult:
62
+ name: str
63
+ type: Optional[str] = None
64
+ #: None when the engine gave no verdict.
65
+ verdict: Optional[str] = None
66
+ #: Percent: how sure the engine is of the verdict it gave.
67
+ confidence: Optional[float] = None
68
+ #: Percent: a model's calibrated chance that the file is malware (the
69
+ #: Windows Program Model). It can say clean at 64% when its line for
70
+ #: suspicious is higher.
71
+ malware_chance: Optional[int] = None
72
+ #: "counted", "no_record", "advisory" or "unavailable".
73
+ vote: Optional[str] = None
74
+ reason: Optional[str] = None
75
+
76
+
77
+ @dataclass
78
+ class ScanResult:
79
+ id: str
80
+ status: str
81
+ #: "malicious", "suspicious", "clean" or "unknown".
82
+ verdict: str
83
+ report_url: str
84
+ target: Optional[str] = None
85
+ sha256: Optional[str] = None
86
+ failure_reason: Optional[str] = None
87
+ explanation: Optional[str] = None
88
+ votes: Dict[str, int] = field(default_factory=dict)
89
+ engines: List[EngineResult] = field(default_factory=list)
90
+ #: The raw API objects, for fields not mapped above.
91
+ submission: Dict[str, Any] = field(default_factory=dict, repr=False)
92
+ consensus: Optional[Dict[str, Any]] = field(default=None, repr=False)
93
+
94
+ def meets(self, threshold: str) -> bool:
95
+ """True when this verdict is at least as bad as ``threshold``."""
96
+ return meets_threshold(self.verdict, threshold)
97
+
98
+
99
+ def meets_threshold(verdict: str, threshold: str) -> bool:
100
+ """True when ``verdict`` is at least as bad as ``threshold``
101
+ ("malicious", "suspicious" or "never")."""
102
+ if threshold in ("never", "none"):
103
+ return False
104
+ if threshold not in _RANK:
105
+ raise VerdyxError(f'unknown threshold "{threshold}"')
106
+ return _RANK.get(verdict, 0) >= _RANK[threshold]
107
+
108
+
109
+ def _is_url(target: str) -> bool:
110
+ return re.match(r"^https?://", target, re.I) is not None
111
+
112
+
113
+ def _normalise_verdict(v: Any) -> str:
114
+ s = str(v or "unknown").lower()
115
+ if s == "benign":
116
+ return "clean"
117
+ return s if s in _RANK else "unknown"
118
+
119
+
120
+ class Verdyx:
121
+ """A client for the Verdyx API.
122
+
123
+ The API key defaults to the ``VERDYX_API_KEY`` environment variable and the
124
+ API to ``VERDYX_API_URL``, then https://api.verdyx.dev.
125
+ """
126
+
127
+ def __init__(self, api_key: Optional[str] = None, api_url: Optional[str] = None,
128
+ web_url: Optional[str] = None, timeout: float = 60.0, max_retries: int = 3,
129
+ user_agent: Optional[str] = None) -> None:
130
+ self.api_key = api_key if api_key is not None else os.environ.get("VERDYX_API_KEY")
131
+ self.api_url = (api_url or os.environ.get("VERDYX_API_URL") or DEFAULT_API_URL).rstrip("/")
132
+ self.web_url = (web_url or os.environ.get("VERDYX_WEB_URL") or DEFAULT_WEB_URL).rstrip("/")
133
+ self.timeout = timeout
134
+ self.max_retries = max_retries
135
+ self.user_agent = user_agent or f"verdyx-python/{__version__}"
136
+
137
+ def __repr__(self) -> str: # never show the key
138
+ return f"Verdyx(api_url={self.api_url!r}, api_key={'set' if self.api_key else 'unset'})"
139
+
140
+ def report_url(self, submission_id: str) -> str:
141
+ return f"{self.web_url}/analysis/{quote(submission_id, safe='')}"
142
+
143
+ # ── HTTP ─────────────────────────────────────────────────────────────
144
+
145
+ def request(self, method: str, path: str, body: Optional[bytes] = None,
146
+ content_type: Optional[str] = None, retry: bool = True) -> Any:
147
+ headers = {"Accept": "application/json", "User-Agent": self.user_agent}
148
+ if self.api_key:
149
+ headers["X-API-Key"] = self.api_key
150
+ if content_type:
151
+ headers["Content-Type"] = content_type
152
+ url = f"{self.api_url}/api/v1{path}"
153
+ attempt = 0
154
+ while True:
155
+ req = urlrequest.Request(url, data=body, method=method, headers=headers)
156
+ try:
157
+ with urlrequest.urlopen(req, timeout=self.timeout) as res:
158
+ return _parse(res.read())
159
+ except urlerror.HTTPError as e:
160
+ data = _parse(e.read())
161
+ retry_after = _float(e.headers.get("Retry-After"))
162
+ if retry and e.code in _RETRYABLE and attempt < self.max_retries:
163
+ time.sleep(min(retry_after, 60) if retry_after else _backoff(attempt))
164
+ attempt += 1
165
+ continue
166
+ raise VerdyxError(_message(e.code, data), status=e.code, body=data,
167
+ retry_after=retry_after) from None
168
+ except (urlerror.URLError, OSError) as e:
169
+ if retry and attempt < self.max_retries:
170
+ time.sleep(_backoff(attempt))
171
+ attempt += 1
172
+ continue
173
+ reason = getattr(e, "reason", e)
174
+ raise VerdyxError(f"could not reach {self.api_url}: {reason}") from None
175
+
176
+ # ── Submitting ───────────────────────────────────────────────────────
177
+
178
+ def submit_file(self, file: Union[str, os.PathLike, bytes], filename: Optional[str] = None,
179
+ description: Optional[str] = None, team_id: Optional[str] = None,
180
+ priority: bool = False) -> Submission:
181
+ """Upload a file: a path, or bytes with ``filename``."""
182
+ if isinstance(file, (bytes, bytearray)):
183
+ data = bytes(file)
184
+ name = filename or "upload.bin"
185
+ else:
186
+ p = Path(file)
187
+ data = p.read_bytes()
188
+ name = filename or p.name
189
+ if not data:
190
+ raise VerdyxError("the file is empty")
191
+ fields = _common(description, team_id, priority)
192
+ return self._submit(fields, ("file", name, data))
193
+
194
+ def submit_url(self, url: str, description: Optional[str] = None,
195
+ team_id: Optional[str] = None, priority: bool = False) -> Submission:
196
+ if not _is_url(url):
197
+ raise VerdyxError(f"not an http(s) URL: {url}")
198
+ fields = [("url", url)] + _common(description, team_id, priority)
199
+ return self._submit(fields, None)
200
+
201
+ def _submit(self, fields: List[tuple], file: Optional[tuple]) -> Submission:
202
+ body, ctype = _multipart(fields, file)
203
+ # Uploads aren't retried: a retry after a lost response could create a second scan.
204
+ raw = self.request("POST", "/submissions/file", body=body, content_type=ctype, retry=False)
205
+ if not isinstance(raw, dict) or not raw.get("id"):
206
+ raise VerdyxError("unexpected response from the submit endpoint", body=raw)
207
+ return Submission(
208
+ id=str(raw["id"]),
209
+ status=raw.get("analysis_status") or raw.get("analysisStatus") or "pending",
210
+ sha256=raw.get("file_hash") or raw.get("fileHash"),
211
+ filename=raw.get("original_filename") or raw.get("originalFilename"),
212
+ type=raw.get("submission_type") or raw.get("submissionType"),
213
+ )
214
+
215
+ # ── Reading ──────────────────────────────────────────────────────────
216
+
217
+ def get_submission(self, submission_id: str) -> Dict[str, Any]:
218
+ return self.request("GET", f"/submissions/{quote(submission_id, safe='')}")
219
+
220
+ def get_consensus(self, submission_id: str) -> Dict[str, Any]:
221
+ return self.request("GET", f"/submissions/{quote(submission_id, safe='')}/consensus")
222
+
223
+ def get_analyses(self, submission_id: str) -> List[Dict[str, Any]]:
224
+ data = self.request("GET", f"/submissions/{quote(submission_id, safe='')}/analyses")
225
+ return _as_list(data, "analyses")
226
+
227
+ def find_similar(self, submission_id: str) -> Dict[str, Any]:
228
+ """Files similar to an uploaded file, among the uploads this key may read.
229
+
230
+ Matches by fuzzy hash (TLSH, ssdeep) or a shared imphash, closest first.
231
+ The result has ``status`` (ready, pending, not_a_file or unavailable),
232
+ ``hashes``, ``similar`` and ``compared``. Needs an API key.
233
+ """
234
+ return self.request("GET", f"/submissions/{quote(submission_id, safe='')}/similar")
235
+
236
+ def list_engines(self) -> List[Dict[str, Any]]:
237
+ """The engines and whether each is online."""
238
+ return _as_list(self.request("GET", "/engines"), "engines")
239
+
240
+ def wait_for_result(self, submission_id: str, timeout: float = 300,
241
+ poll_interval: Optional[float] = None,
242
+ on_status: Optional[Callable[[str], None]] = None) -> ScanResult:
243
+ """Poll until the scan finishes. Raises ScanTimeoutError on timeout.
244
+
245
+ By default polling starts at 2 s and backs off to 10 s.
246
+ """
247
+ deadline = time.monotonic() + timeout
248
+ delay = poll_interval or 2.0
249
+ while True:
250
+ submission = self.get_submission(submission_id)
251
+ status = submission.get("analysisStatus") or submission.get("status") or "pending"
252
+ if on_status:
253
+ on_status(status)
254
+ if status in _FINISHED:
255
+ return self.result(submission_id, submission)
256
+ if time.monotonic() + delay > deadline:
257
+ raise ScanTimeoutError(submission_id, timeout)
258
+ time.sleep(delay)
259
+ if not poll_interval:
260
+ delay = min(delay * 1.5, 10.0)
261
+
262
+ def result(self, submission_id: str, submission: Optional[Dict[str, Any]] = None) -> ScanResult:
263
+ """The result of a scan as it stands now."""
264
+ submission = submission if submission is not None else self.get_submission(submission_id)
265
+ status = submission.get("analysisStatus") or submission.get("status") or "pending"
266
+ consensus: Optional[Dict[str, Any]] = None
267
+ analyses: List[Dict[str, Any]] = []
268
+ if status == "completed":
269
+ consensus = self.get_consensus(submission_id)
270
+ analyses = self.get_analyses(submission_id)
271
+ c = consensus or {}
272
+ return ScanResult(
273
+ id=submission_id,
274
+ status=status,
275
+ verdict=_normalise_verdict(c.get("finalVerdict")) if status == "completed" else "unknown",
276
+ report_url=self.report_url(submission_id),
277
+ target=submission.get("url") or submission.get("originalFilename") or submission.get("filename"),
278
+ sha256=submission.get("fileHash"),
279
+ failure_reason=submission.get("failureReason"),
280
+ explanation=c.get("explanation"),
281
+ votes={
282
+ "malicious": c.get("maliciousVotes") or 0,
283
+ "suspicious": c.get("suspiciousVotes") or 0,
284
+ "clean": c.get("cleanVotes") or 0,
285
+ "total": c.get("totalVotes") or 0,
286
+ },
287
+ engines=[_engine(a) for a in analyses],
288
+ submission=submission,
289
+ consensus=consensus,
290
+ )
291
+
292
+ def scan(self, target: Union[str, os.PathLike], timeout: float = 300,
293
+ poll_interval: Optional[float] = None, **submit_options: Any) -> ScanResult:
294
+ """Submit a file path or http(s) URL, then wait for the verdict."""
295
+ t = os.fspath(target)
296
+ sub = self.submit_url(t, **submit_options) if _is_url(t) else self.submit_file(t, **submit_options)
297
+ return self.wait_for_result(sub.id, timeout=timeout, poll_interval=poll_interval)
298
+
299
+
300
+ # ── Helpers ──────────────────────────────────────────────────────────────
301
+
302
+ def _common(description: Optional[str], team_id: Optional[str], priority: bool) -> List[tuple]:
303
+ out: List[tuple] = []
304
+ if description:
305
+ out.append(("description", description))
306
+ if team_id:
307
+ out.append(("organizationId", team_id))
308
+ if priority:
309
+ out.append(("priority", "true"))
310
+ return out
311
+
312
+
313
+ def _multipart(fields: List[tuple], file: Optional[tuple]) -> tuple:
314
+ boundary = f"----verdyx{uuid.uuid4().hex}"
315
+ parts: List[bytes] = []
316
+ for name, value in fields:
317
+ parts.append(
318
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode()
319
+ + str(value).encode() + b"\r\n"
320
+ )
321
+ if file:
322
+ name, filename, data = file
323
+ safe = filename.replace('"', "_").replace("\r", "_").replace("\n", "_")
324
+ parts.append(
325
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; filename="{safe}"\r\n'
326
+ f"Content-Type: application/octet-stream\r\n\r\n".encode()
327
+ + data + b"\r\n"
328
+ )
329
+ parts.append(f"--{boundary}--\r\n".encode())
330
+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"
331
+
332
+
333
+ def _parse(raw: bytes) -> Any:
334
+ if not raw:
335
+ return None
336
+ text = raw.decode("utf-8", "replace")
337
+ try:
338
+ return json.loads(text)
339
+ except ValueError:
340
+ return text
341
+
342
+
343
+ def _float(v: Optional[str]) -> Optional[float]:
344
+ try:
345
+ return float(v) if v else None
346
+ except ValueError:
347
+ return None
348
+
349
+
350
+ def _as_list(data: Any, key: str) -> List[Dict[str, Any]]:
351
+ if isinstance(data, list):
352
+ return data
353
+ if isinstance(data, dict):
354
+ return data.get(key) or data.get("data") or []
355
+ return []
356
+
357
+
358
+ def _engine(a: Dict[str, Any]) -> EngineResult:
359
+ eng = a.get("engine") or {}
360
+ # The API sends "unknown" for an engine that ran but didn't vote.
361
+ verdict = _normalise_verdict(a["verdict"]) if a.get("verdict") else "unknown"
362
+ probability = (a.get("metadata") or {}).get("probability")
363
+ return EngineResult(
364
+ name=eng.get("name") or a.get("engineName") or "engine",
365
+ type=eng.get("type") or a.get("engineType"),
366
+ verdict=None if verdict == "unknown" else verdict,
367
+ confidence=a.get("confidence"),
368
+ malware_chance=(
369
+ round(probability * 100)
370
+ if isinstance(probability, (int, float)) and not isinstance(probability, bool)
371
+ else None
372
+ ),
373
+ vote=a.get("vote"),
374
+ reason=a.get("reason"),
375
+ )
376
+
377
+
378
+ def _message(status: int, data: Any) -> str:
379
+ detail = ""
380
+ if isinstance(data, dict):
381
+ detail = data.get("message") or data.get("error") or data.get("detail") or ""
382
+ elif isinstance(data, str) and len(data) < 300:
383
+ detail = data
384
+ hints = {
385
+ 401: "the API key is missing, revoked or expired",
386
+ 403: "the API key isn't allowed to do this",
387
+ 404: "not found, or not visible to this API key",
388
+ 413: "the file is larger than the 100 MB limit",
389
+ 429: "rate limited",
390
+ }
391
+ detail = detail or hints.get(status, "")
392
+ return f"HTTP {status}: {detail}" if detail else f"HTTP {status}"
393
+
394
+
395
+ def _backoff(attempt: int) -> float:
396
+ return min(2 ** attempt, 15) + random.random() / 4
verdyx/py.typed ADDED
File without changes
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: verdyx
3
+ Version: 0.1.0
4
+ Summary: Verdyx malware and URL scanning: Python SDK
5
+ License: MIT
6
+ Project-URL: Homepage, https://verdyx.dev
7
+ Project-URL: Source, https://github.com/deep60/Verdyx/tree/main/sdk/python
8
+ Keywords: malware,scanner,security,threat-intelligence,yara
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Security
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # verdyx (Python)
16
+
17
+ A Python SDK for [Verdyx](https://verdyx.dev) malware and URL scanning. Python 3.10 or later, standard library only.
18
+
19
+ ## Install
20
+
21
+ The package isn't on PyPI yet. Until it is, install it from the repository:
22
+
23
+ ```bash
24
+ pip install "git+https://github.com/deep60/Verdyx.git#subdirectory=sdk/python"
25
+ ```
26
+
27
+ ## Use
28
+
29
+ Create an API key on your profile page at verdyx.dev (**API keys** tab), with the `read` and `scan` scopes, and set `VERDYX_API_KEY`.
30
+
31
+ ```python
32
+ from verdyx import Verdyx
33
+
34
+ client = Verdyx() # reads VERDYX_API_KEY
35
+
36
+ result = client.scan("suspicious.exe")
37
+ print(result.verdict) # "malicious" | "suspicious" | "clean" | "unknown"
38
+ print(result.votes) # {"malicious": 3, "suspicious": 0, "clean": 1, "total": 4}
39
+ print(result.report_url) # https://verdyx.dev/analysis/…
40
+ for e in result.engines:
41
+ print(e.name, e.verdict, e.vote, e.reason)
42
+
43
+ if result.meets("suspicious"):
44
+ raise SystemExit("blocked by Verdyx")
45
+ ```
46
+
47
+ The steps separately:
48
+
49
+ ```python
50
+ sub = client.submit_url("https://example.com/login", team_id="…")
51
+ result = client.wait_for_result(sub.id, timeout=120, on_status=print)
52
+ ```
53
+
54
+ Files can also be bytes: `client.submit_file(data, filename="invoice.pdf")`.
55
+
56
+ Variants of a file, by fuzzy hash (TLSH, ssdeep) or a shared imphash, among the uploads your key may read:
57
+
58
+ ```python
59
+ for f in client.find_similar(result.id)["similar"]:
60
+ print(f["match"]["closeness"], f["verdict"], f["filename"], f["reportUrl"])
61
+ ```
62
+
63
+ Errors are `VerdyxError`, with `status` (the HTTP status), `body` and `retry_after`. A scan that doesn't finish in time raises `ScanTimeoutError`; the scan keeps running on the server. Reads are retried on network errors, 429 and 502–504, honouring `Retry-After`. Uploads aren't retried, so a lost response can't create a second scan.
64
+
65
+ | Argument | Default |
66
+ |---|---|
67
+ | `api_key` | `VERDYX_API_KEY` |
68
+ | `api_url` | `VERDYX_API_URL`, then `https://api.verdyx.dev` |
69
+ | `web_url` (for report links) | `VERDYX_WEB_URL`, then `https://verdyx.dev` |
70
+ | `timeout` (per request) | 60 s |
71
+ | `max_retries` | 3 |
72
+
73
+ ## Tests
74
+
75
+ ```bash
76
+ python -m unittest discover -s tests
77
+ ```
78
+
79
+ The tests run against an in-process stand-in for the API.
@@ -0,0 +1,7 @@
1
+ verdyx/__init__.py,sha256=JhC9Px8epcZO4fGCXlwxf-vqKobuLWOyXlAxGrzM86A,668
2
+ verdyx/client.py,sha256=vZ08KCxEIbPqyoRVUFCO9uMBhS0t1VPGHkW__baHydY,16554
3
+ verdyx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ verdyx-0.1.0.dist-info/METADATA,sha256=NumbXyAqgjKT6Z3GGHPiM1h0zXcs2dkwbznZPRYcYNk,2650
5
+ verdyx-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ verdyx-0.1.0.dist-info/top_level.txt,sha256=bmeo6GAIpMosH9aacVYfPnnONfcxefPEYW3E1kMMhwc,7
7
+ verdyx-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ verdyx