verdyx 0.1.0__tar.gz
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-0.1.0/PKG-INFO +79 -0
- verdyx-0.1.0/README.md +65 -0
- verdyx-0.1.0/pyproject.toml +28 -0
- verdyx-0.1.0/setup.cfg +4 -0
- verdyx-0.1.0/tests/test_client.py +272 -0
- verdyx-0.1.0/verdyx/__init__.py +35 -0
- verdyx-0.1.0/verdyx/client.py +396 -0
- verdyx-0.1.0/verdyx/py.typed +0 -0
- verdyx-0.1.0/verdyx.egg-info/PKG-INFO +79 -0
- verdyx-0.1.0/verdyx.egg-info/SOURCES.txt +10 -0
- verdyx-0.1.0/verdyx.egg-info/dependency_links.txt +1 -0
- verdyx-0.1.0/verdyx.egg-info/top_level.txt +1 -0
verdyx-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
verdyx-0.1.0/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# verdyx (Python)
|
|
2
|
+
|
|
3
|
+
A Python SDK for [Verdyx](https://verdyx.dev) malware and URL scanning. Python 3.10 or later, standard library only.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
The package isn't on PyPI yet. Until it is, install it from the repository:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install "git+https://github.com/deep60/Verdyx.git#subdirectory=sdk/python"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Use
|
|
14
|
+
|
|
15
|
+
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`.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from verdyx import Verdyx
|
|
19
|
+
|
|
20
|
+
client = Verdyx() # reads VERDYX_API_KEY
|
|
21
|
+
|
|
22
|
+
result = client.scan("suspicious.exe")
|
|
23
|
+
print(result.verdict) # "malicious" | "suspicious" | "clean" | "unknown"
|
|
24
|
+
print(result.votes) # {"malicious": 3, "suspicious": 0, "clean": 1, "total": 4}
|
|
25
|
+
print(result.report_url) # https://verdyx.dev/analysis/…
|
|
26
|
+
for e in result.engines:
|
|
27
|
+
print(e.name, e.verdict, e.vote, e.reason)
|
|
28
|
+
|
|
29
|
+
if result.meets("suspicious"):
|
|
30
|
+
raise SystemExit("blocked by Verdyx")
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The steps separately:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
sub = client.submit_url("https://example.com/login", team_id="…")
|
|
37
|
+
result = client.wait_for_result(sub.id, timeout=120, on_status=print)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Files can also be bytes: `client.submit_file(data, filename="invoice.pdf")`.
|
|
41
|
+
|
|
42
|
+
Variants of a file, by fuzzy hash (TLSH, ssdeep) or a shared imphash, among the uploads your key may read:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
for f in client.find_similar(result.id)["similar"]:
|
|
46
|
+
print(f["match"]["closeness"], f["verdict"], f["filename"], f["reportUrl"])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
| Argument | Default |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `api_key` | `VERDYX_API_KEY` |
|
|
54
|
+
| `api_url` | `VERDYX_API_URL`, then `https://api.verdyx.dev` |
|
|
55
|
+
| `web_url` (for report links) | `VERDYX_WEB_URL`, then `https://verdyx.dev` |
|
|
56
|
+
| `timeout` (per request) | 60 s |
|
|
57
|
+
| `max_retries` | 3 |
|
|
58
|
+
|
|
59
|
+
## Tests
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
python -m unittest discover -s tests
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The tests run against an in-process stand-in for the API.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "verdyx"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Verdyx malware and URL scanning: Python SDK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["malware", "scanner", "security", "threat-intelligence", "yara"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Security",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://verdyx.dev"
|
|
22
|
+
Source = "https://github.com/deep60/Verdyx/tree/main/sdk/python"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
packages = ["verdyx"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
verdyx = ["py.typed"]
|
verdyx-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Tests against a small in-process stand-in for the Verdyx API.
|
|
2
|
+
|
|
3
|
+
Run with: python -m unittest discover -s tests
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import email.parser
|
|
7
|
+
import email.policy
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
import unittest
|
|
14
|
+
import uuid
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from verdyx import ScanTimeoutError, Verdyx, VerdyxError, meets_threshold
|
|
19
|
+
|
|
20
|
+
KEY = "vdx_" + "2" * 64
|
|
21
|
+
EICAR = "stand-in sample: the mock API treats any upload containing EICAR as malicious"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MockApi:
|
|
25
|
+
"""Answers the routes the client calls, with backend/api-gateway's shapes."""
|
|
26
|
+
|
|
27
|
+
def __init__(self):
|
|
28
|
+
self.scans = {}
|
|
29
|
+
self.requests = []
|
|
30
|
+
self.replies = [] # queued (status, body, headers) overrides
|
|
31
|
+
api = self
|
|
32
|
+
|
|
33
|
+
class Handler(BaseHTTPRequestHandler):
|
|
34
|
+
def log_message(self, *args):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
def _send(self, status, data, headers=None):
|
|
38
|
+
body = json.dumps(data).encode()
|
|
39
|
+
self.send_response(status)
|
|
40
|
+
self.send_header("Content-Type", "application/json")
|
|
41
|
+
for k, v in (headers or {}).items():
|
|
42
|
+
self.send_header(k, v)
|
|
43
|
+
self.send_header("Content-Length", str(len(body)))
|
|
44
|
+
self.end_headers()
|
|
45
|
+
self.wfile.write(body)
|
|
46
|
+
|
|
47
|
+
def _handle(self):
|
|
48
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
49
|
+
body = self.rfile.read(length) if length else b""
|
|
50
|
+
api.requests.append((self.command, self.path, dict(self.headers), body))
|
|
51
|
+
if api.replies:
|
|
52
|
+
return self._send(*api.replies.pop(0))
|
|
53
|
+
if self.headers.get("X-API-Key") != KEY:
|
|
54
|
+
return self._send(401, {"message": "invalid API key"})
|
|
55
|
+
path = self.path.split("?")[0].replace("/api/v1", "", 1)
|
|
56
|
+
if self.command == "GET" and path == "/engines":
|
|
57
|
+
return self._send(200, [{"name": "YARA Engine", "status": "online"}])
|
|
58
|
+
if self.command == "POST" and path == "/submissions/file":
|
|
59
|
+
form = _parse_form(self.headers["Content-Type"], body)
|
|
60
|
+
sid = str(uuid.uuid4())
|
|
61
|
+
if "file" in form:
|
|
62
|
+
name, data = form["file"]
|
|
63
|
+
content = data.decode("latin-1")
|
|
64
|
+
else:
|
|
65
|
+
name, data, content = form["url"], form["url"].encode(), form["url"]
|
|
66
|
+
verdict = "malicious" if "EICAR" in content else "suspicious" if "phish" in content else "clean"
|
|
67
|
+
api.scans[sid] = {"id": sid, "target": name, "url": "url" in form, "verdict": verdict,
|
|
68
|
+
"hash": hashlib.sha256(data).hexdigest(), "polls": 0,
|
|
69
|
+
"fail": "fail-me" in content, "form": form}
|
|
70
|
+
return self._send(200, {"id": sid, "analysis_status": "pending", "file_hash": api.scans[sid]["hash"],
|
|
71
|
+
"original_filename": name, "submission_type": "url" if "url" in form else "file"})
|
|
72
|
+
parts = path.strip("/").split("/")
|
|
73
|
+
if self.command == "GET" and parts[0] == "submissions" and len(parts) >= 2:
|
|
74
|
+
scan = api.scans.get(parts[1])
|
|
75
|
+
if not scan:
|
|
76
|
+
return self._send(404, {"message": "not found"})
|
|
77
|
+
if len(parts) == 2:
|
|
78
|
+
scan["polls"] += 1
|
|
79
|
+
status = "analyzing" if scan["polls"] < 2 else ("failed" if scan["fail"] else "completed")
|
|
80
|
+
return self._send(200, {"id": scan["id"], "analysisStatus": status, "status": status,
|
|
81
|
+
"originalFilename": scan["target"], "fileHash": scan["hash"],
|
|
82
|
+
"url": scan["target"] if scan["url"] else None,
|
|
83
|
+
**({"failureReason": "could not fetch"} if status == "failed" else {})})
|
|
84
|
+
if parts[2] == "similar":
|
|
85
|
+
others = [o for o in api.scans.values() if o["id"] != scan["id"] and not o["url"]]
|
|
86
|
+
return self._send(200, {
|
|
87
|
+
"submissionId": scan["id"], "status": "not_a_file" if scan["url"] else "ready",
|
|
88
|
+
"hashes": None, "compared": len(others),
|
|
89
|
+
"similar": [] if scan["url"] else [
|
|
90
|
+
{"submissionId": o["id"], "filename": o["target"], "verdict": o["verdict"],
|
|
91
|
+
"match": {"closeness": "similar", "tlshDistance": 40, "ssdeepScore": None,
|
|
92
|
+
"sameImphash": False}} for o in others]})
|
|
93
|
+
flagged = scan["verdict"] != "clean"
|
|
94
|
+
if parts[2] == "consensus":
|
|
95
|
+
return self._send(200, {"finalVerdict": scan["verdict"], "explanation": "x",
|
|
96
|
+
"maliciousVotes": int(scan["verdict"] == "malicious"),
|
|
97
|
+
"suspiciousVotes": int(scan["verdict"] == "suspicious"),
|
|
98
|
+
"cleanVotes": 1 if flagged else 2, "totalVotes": 2})
|
|
99
|
+
if parts[2] == "analyses":
|
|
100
|
+
return self._send(200, [
|
|
101
|
+
{"engine": {"name": "YARA", "type": "yara"},
|
|
102
|
+
"verdict": scan["verdict"] if flagged else "benign", "confidence": 90, "vote": "counted"},
|
|
103
|
+
{"engine": {"name": "MalwareBazaar"}, "verdict": None, "vote": "no_record",
|
|
104
|
+
"reason": "Not in MalwareBazaar"},
|
|
105
|
+
# Like the live API: "unknown" for an engine that didn't vote.
|
|
106
|
+
{"engine": {"name": "ClamAV"}, "verdict": "unknown",
|
|
107
|
+
"reason": "No known-bad pattern matched"},
|
|
108
|
+
{"engine": {"name": "Verdyx PE Model"}, "verdict": "clean", "confidence": 36,
|
|
109
|
+
"metadata": {"probability": 0.6421}},
|
|
110
|
+
])
|
|
111
|
+
return self._send(404, {"message": "no mock"})
|
|
112
|
+
|
|
113
|
+
do_GET = do_POST = _handle
|
|
114
|
+
|
|
115
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
116
|
+
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
|
117
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
118
|
+
|
|
119
|
+
def close(self):
|
|
120
|
+
self.server.shutdown()
|
|
121
|
+
self.server.server_close()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _parse_form(ctype, body):
|
|
125
|
+
msg = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes(
|
|
126
|
+
f"Content-Type: {ctype}\r\n\r\n".encode() + body)
|
|
127
|
+
out = {}
|
|
128
|
+
for part in msg.iter_parts():
|
|
129
|
+
name = part.get_param("name", header="content-disposition")
|
|
130
|
+
filename = part.get_filename()
|
|
131
|
+
payload = part.get_payload(decode=True)
|
|
132
|
+
out[name] = (filename, payload) if filename is not None else payload.decode()
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class ClientTest(unittest.TestCase):
|
|
137
|
+
@classmethod
|
|
138
|
+
def setUpClass(cls):
|
|
139
|
+
cls.api = MockApi()
|
|
140
|
+
cls.tmp = tempfile.TemporaryDirectory()
|
|
141
|
+
|
|
142
|
+
@classmethod
|
|
143
|
+
def tearDownClass(cls):
|
|
144
|
+
cls.api.close()
|
|
145
|
+
cls.tmp.cleanup()
|
|
146
|
+
|
|
147
|
+
def setUp(self):
|
|
148
|
+
self.api.replies.clear()
|
|
149
|
+
self.client = Verdyx(api_key=KEY, api_url=self.api.url + "/", web_url="https://verdyx.dev")
|
|
150
|
+
|
|
151
|
+
def test_scans_a_file_path(self):
|
|
152
|
+
p = Path(self.tmp.name) / "eicar.com"
|
|
153
|
+
p.write_text(EICAR)
|
|
154
|
+
r = self.client.scan(p, poll_interval=0.02)
|
|
155
|
+
self.assertEqual(r.status, "completed")
|
|
156
|
+
self.assertEqual(r.verdict, "malicious")
|
|
157
|
+
self.assertEqual(r.target, "eicar.com")
|
|
158
|
+
self.assertEqual(len(r.sha256), 64)
|
|
159
|
+
self.assertEqual(r.votes, {"malicious": 1, "suspicious": 0, "clean": 1, "total": 2})
|
|
160
|
+
self.assertEqual(r.report_url, f"https://verdyx.dev/analysis/{r.id}")
|
|
161
|
+
self.assertEqual([e.name for e in r.engines], ["YARA", "MalwareBazaar", "ClamAV", "Verdyx PE Model"])
|
|
162
|
+
self.assertEqual(r.engines[1].vote, "no_record")
|
|
163
|
+
self.assertTrue(r.meets("malicious"))
|
|
164
|
+
method, path, headers, _ = next(x for x in self.api.requests if x[0] == "POST")
|
|
165
|
+
headers = {k.lower(): v for k, v in headers.items()} # header names are case-insensitive
|
|
166
|
+
self.assertEqual(path, "/api/v1/submissions/file")
|
|
167
|
+
self.assertEqual(headers["x-api-key"], KEY)
|
|
168
|
+
self.assertTrue(headers["user-agent"].startswith("verdyx-python/"))
|
|
169
|
+
|
|
170
|
+
def test_scans_urls(self):
|
|
171
|
+
self.assertEqual(self.client.scan("https://example.com/", poll_interval=0.02).verdict, "clean")
|
|
172
|
+
r = self.client.scan("https://phish.test/login", poll_interval=0.02)
|
|
173
|
+
self.assertEqual(r.verdict, "suspicious")
|
|
174
|
+
self.assertEqual(r.target, "https://phish.test/login")
|
|
175
|
+
|
|
176
|
+
def test_engine_benign_is_reported_as_clean(self):
|
|
177
|
+
r = self.client.scan("https://example.org/", poll_interval=0.02)
|
|
178
|
+
self.assertEqual(r.engines[0].verdict, "clean")
|
|
179
|
+
self.assertIsNone(r.engines[1].verdict)
|
|
180
|
+
self.assertIsNone(r.engines[2].verdict, "unknown means the engine didn't vote")
|
|
181
|
+
self.assertIsNone(r.engines[2].malware_chance)
|
|
182
|
+
self.assertEqual(r.engines[3].malware_chance, 64)
|
|
183
|
+
|
|
184
|
+
def test_bytes_with_options(self):
|
|
185
|
+
sub = self.client.submit_file(b"hello", filename='odd"name.txt', description="note",
|
|
186
|
+
team_id="team-1", priority=True)
|
|
187
|
+
self.assertEqual(sub.status, "pending")
|
|
188
|
+
form = self.api.scans[sub.id]["form"]
|
|
189
|
+
self.assertEqual(form["file"], ('odd_name.txt', b"hello"))
|
|
190
|
+
self.assertEqual(form["description"], "note")
|
|
191
|
+
self.assertEqual(form["organizationId"], "team-1")
|
|
192
|
+
self.assertEqual(form["priority"], "true")
|
|
193
|
+
|
|
194
|
+
def test_failed_scan(self):
|
|
195
|
+
r = self.client.scan("https://fail-me.test/", poll_interval=0.02)
|
|
196
|
+
self.assertEqual(r.status, "failed")
|
|
197
|
+
self.assertEqual(r.verdict, "unknown")
|
|
198
|
+
self.assertEqual(r.failure_reason, "could not fetch")
|
|
199
|
+
self.assertEqual(r.engines, [])
|
|
200
|
+
|
|
201
|
+
def test_timeout(self):
|
|
202
|
+
sub = self.client.submit_url("https://slow.test/")
|
|
203
|
+
with self.assertRaises(ScanTimeoutError) as ctx:
|
|
204
|
+
self.client.wait_for_result(sub.id, timeout=0.01, poll_interval=1)
|
|
205
|
+
self.assertEqual(ctx.exception.submission_id, sub.id)
|
|
206
|
+
|
|
207
|
+
def test_on_status(self):
|
|
208
|
+
sub = self.client.submit_url("https://example.net/")
|
|
209
|
+
seen = []
|
|
210
|
+
self.client.wait_for_result(sub.id, poll_interval=0.02, on_status=seen.append)
|
|
211
|
+
self.assertEqual(seen, ["analyzing", "completed"])
|
|
212
|
+
|
|
213
|
+
def test_errors(self):
|
|
214
|
+
bad = Verdyx(api_key="vdx_bad", api_url=self.api.url)
|
|
215
|
+
with self.assertRaises(VerdyxError) as ctx:
|
|
216
|
+
bad.list_engines()
|
|
217
|
+
self.assertEqual(ctx.exception.status, 401)
|
|
218
|
+
self.assertEqual(str(ctx.exception), "HTTP 401: invalid API key")
|
|
219
|
+
with self.assertRaises(VerdyxError) as ctx:
|
|
220
|
+
self.client.get_submission("nope")
|
|
221
|
+
self.assertEqual(ctx.exception.status, 404)
|
|
222
|
+
with self.assertRaises(VerdyxError):
|
|
223
|
+
self.client.submit_file(b"")
|
|
224
|
+
with self.assertRaises(VerdyxError):
|
|
225
|
+
self.client.submit_url("ftp://example.com")
|
|
226
|
+
|
|
227
|
+
def test_reads_retry_on_429_and_5xx(self):
|
|
228
|
+
self.api.replies[:] = [(503, {}), (429, {"message": "slow"}, {"Retry-After": "1"})]
|
|
229
|
+
t0 = time.monotonic()
|
|
230
|
+
engines = self.client.list_engines()
|
|
231
|
+
self.assertEqual(engines[0]["name"], "YARA Engine")
|
|
232
|
+
self.assertGreaterEqual(time.monotonic() - t0, 1.0)
|
|
233
|
+
|
|
234
|
+
def test_uploads_are_not_retried(self):
|
|
235
|
+
self.api.replies[:] = [(429, {"message": "slow down"}, {"Retry-After": "7"})]
|
|
236
|
+
before = len(self.api.scans)
|
|
237
|
+
with self.assertRaises(VerdyxError) as ctx:
|
|
238
|
+
self.client.submit_url("https://example.com/")
|
|
239
|
+
self.assertEqual(ctx.exception.status, 429)
|
|
240
|
+
self.assertEqual(ctx.exception.retry_after, 7.0)
|
|
241
|
+
self.assertEqual(str(ctx.exception), "HTTP 429: slow down")
|
|
242
|
+
self.assertEqual(len(self.api.scans), before)
|
|
243
|
+
|
|
244
|
+
def test_unreachable(self):
|
|
245
|
+
c = Verdyx(api_url="http://127.0.0.1:9", max_retries=0)
|
|
246
|
+
with self.assertRaises(VerdyxError) as ctx:
|
|
247
|
+
c.list_engines()
|
|
248
|
+
self.assertIn("could not reach", str(ctx.exception))
|
|
249
|
+
|
|
250
|
+
def test_find_similar(self):
|
|
251
|
+
a = self.client.submit_file(b"first sample", filename="a.bin")
|
|
252
|
+
self.client.submit_file(b"second sample", filename="b.bin")
|
|
253
|
+
r = self.client.find_similar(a.id)
|
|
254
|
+
self.assertEqual(r["status"], "ready")
|
|
255
|
+
self.assertIn("b.bin", [f["filename"] for f in r["similar"]])
|
|
256
|
+
self.assertNotIn(a.id, [f["submissionId"] for f in r["similar"]])
|
|
257
|
+
self.assertEqual(self.api.requests[-1][1], f"/api/v1/submissions/{a.id}/similar")
|
|
258
|
+
|
|
259
|
+
def test_repr_hides_the_key(self):
|
|
260
|
+
self.assertNotIn(KEY, repr(self.client))
|
|
261
|
+
|
|
262
|
+
def test_meets_threshold(self):
|
|
263
|
+
self.assertTrue(meets_threshold("malicious", "suspicious"))
|
|
264
|
+
self.assertFalse(meets_threshold("suspicious", "malicious"))
|
|
265
|
+
self.assertFalse(meets_threshold("malicious", "never"))
|
|
266
|
+
self.assertFalse(meets_threshold("unknown", "suspicious"))
|
|
267
|
+
with self.assertRaises(VerdyxError):
|
|
268
|
+
meets_threshold("malicious", "high")
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
unittest.main()
|
|
@@ -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
|
+
]
|
|
@@ -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
|
|
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 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
verdyx
|