urlquery-api 0.8.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.
- urlquery_api/__init__.py +29 -0
- urlquery_api/_client.py +560 -0
- urlquery_api/_errors.py +50 -0
- urlquery_api/models.py +1911 -0
- urlquery_api/py.typed +0 -0
- urlquery_api-0.8.0.dist-info/METADATA +109 -0
- urlquery_api-0.8.0.dist-info/RECORD +9 -0
- urlquery_api-0.8.0.dist-info/WHEEL +4 -0
- urlquery_api-0.8.0.dist-info/licenses/LICENSE +21 -0
urlquery_api/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""The Python client for the urlquery v2 API (https://api.urlquery.net/public/v2).
|
|
2
|
+
|
|
3
|
+
Submit URLs for analysis, read and compare reports, search a year of reports,
|
|
4
|
+
look up reputation, explore Host Profile, and manage YARA rules, watchlists and
|
|
5
|
+
page monitors::
|
|
6
|
+
|
|
7
|
+
from urlquery_api import Client
|
|
8
|
+
|
|
9
|
+
with Client() as client: # the API key from URLQUERY_APIKEY
|
|
10
|
+
s = client.submit("https://example.com/login", access="restricted", wait=True)
|
|
11
|
+
report = client.report(s.report_id)
|
|
12
|
+
|
|
13
|
+
Results are pydantic models generated from the API's OpenAPI description, in
|
|
14
|
+
``urlquery_api.models``. Documentation: https://docs.urlquery.net/docs/libraries/python
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from . import models
|
|
18
|
+
from ._client import DEFAULT_BASE_URL, Client
|
|
19
|
+
from ._errors import APIError, InvalidResponseError, URLQueryError, WaitTimeoutError
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DEFAULT_BASE_URL",
|
|
23
|
+
"APIError",
|
|
24
|
+
"Client",
|
|
25
|
+
"InvalidResponseError",
|
|
26
|
+
"URLQueryError",
|
|
27
|
+
"WaitTimeoutError",
|
|
28
|
+
"models",
|
|
29
|
+
]
|
urlquery_api/_client.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
from typing import IO, Any, Literal, TypeVar
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from pydantic import BaseModel
|
|
13
|
+
|
|
14
|
+
from . import models as m
|
|
15
|
+
from ._errors import APIError, InvalidResponseError, WaitTimeoutError
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://api.urlquery.net"
|
|
18
|
+
_PREFIX = "/public/v2"
|
|
19
|
+
_MAX_INDICATORS = 500 # the most indicators the API takes at once
|
|
20
|
+
_MAX_SEARCH_WINDOW = 10_000 # the most results a search can reach
|
|
21
|
+
|
|
22
|
+
T = TypeVar("T", bound=BaseModel)
|
|
23
|
+
|
|
24
|
+
Scope = Literal["all", "user", "team", "alerted"]
|
|
25
|
+
RelatedScope = Literal["ip", "asn", "domain"]
|
|
26
|
+
Access = Literal["public", "restricted", "private"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _library_version() -> str:
|
|
30
|
+
try:
|
|
31
|
+
return version("urlquery-api")
|
|
32
|
+
except PackageNotFoundError:
|
|
33
|
+
return "dev"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _clean(params: dict[str, Any]) -> dict[str, Any]:
|
|
37
|
+
"""Drops unset query parameters and spells booleans and times for the API."""
|
|
38
|
+
out: dict[str, Any] = {}
|
|
39
|
+
for key, value in params.items():
|
|
40
|
+
if value is None or value == "" or value == []:
|
|
41
|
+
continue
|
|
42
|
+
if isinstance(value, bool):
|
|
43
|
+
value = "true" if value else "false"
|
|
44
|
+
elif isinstance(value, datetime):
|
|
45
|
+
value = value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
46
|
+
out[key] = value
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _body(model: BaseModel) -> dict[str, Any]:
|
|
51
|
+
return model.model_dump(mode="json", by_alias=True, exclude_unset=True)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _request(model: type[T], **fields: Any) -> T:
|
|
55
|
+
"""Builds a request model from the arguments that were given: optional
|
|
56
|
+
request fields may be left out, but not set to None."""
|
|
57
|
+
return model(**{k: v for k, v in fields.items() if v is not None})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Client:
|
|
61
|
+
"""A client for the urlquery v2 API with one API key.
|
|
62
|
+
|
|
63
|
+
Get a key from your urlquery.net account. Without ``api_key``, the
|
|
64
|
+
``URLQUERY_APIKEY`` environment variable is used.
|
|
65
|
+
|
|
66
|
+
The client waits out rate limits for their Retry-After, at most
|
|
67
|
+
``max_retry_wait`` seconds in all, and retries GET requests after server
|
|
68
|
+
errors and network failures. Use it as a context manager, or call
|
|
69
|
+
``close()``, to release its connections.
|
|
70
|
+
|
|
71
|
+
Report content comes from the analyzed sites, which are often hostile:
|
|
72
|
+
treat titles, scripts and downloads as untrusted data.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
api_key: str | None = None,
|
|
78
|
+
*,
|
|
79
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
80
|
+
user_agent: str | None = None,
|
|
81
|
+
max_retry_wait: float = 120.0,
|
|
82
|
+
timeout: float = 120.0,
|
|
83
|
+
http_client: httpx.Client | None = None,
|
|
84
|
+
):
|
|
85
|
+
key = api_key or os.environ.get("URLQUERY_APIKEY", "")
|
|
86
|
+
if not key:
|
|
87
|
+
raise ValueError("an API key is required: pass api_key or set URLQUERY_APIKEY")
|
|
88
|
+
agent = f"urlquery-api-python/{_library_version()} (+https://urlquery.net)"
|
|
89
|
+
if user_agent:
|
|
90
|
+
agent = f"{user_agent} {agent}"
|
|
91
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
92
|
+
self._base = base_url.rstrip("/") + _PREFIX
|
|
93
|
+
self._headers = {"x-apikey": key, "User-Agent": agent}
|
|
94
|
+
self._max_retry_wait = max_retry_wait
|
|
95
|
+
self._poll_interval = 5.0
|
|
96
|
+
|
|
97
|
+
def close(self) -> None:
|
|
98
|
+
self._http.close()
|
|
99
|
+
|
|
100
|
+
def __enter__(self) -> Client:
|
|
101
|
+
return self
|
|
102
|
+
|
|
103
|
+
def __exit__(self, *exc: object) -> None:
|
|
104
|
+
self.close()
|
|
105
|
+
|
|
106
|
+
# Transport
|
|
107
|
+
|
|
108
|
+
def _send(self, method: str, path: str, params: dict[str, Any] | None = None, body: Any = None,
|
|
109
|
+
accept: str = "application/json", stream: bool = False) -> httpx.Response:
|
|
110
|
+
waited = 0.0
|
|
111
|
+
attempt = 0
|
|
112
|
+
while True:
|
|
113
|
+
attempt += 1
|
|
114
|
+
headers = {**self._headers, "Accept": accept}
|
|
115
|
+
error: Exception
|
|
116
|
+
try:
|
|
117
|
+
request = self._http.build_request(method, self._base + path, params=params,
|
|
118
|
+
json=body, headers=headers)
|
|
119
|
+
response = self._http.send(request, stream=stream)
|
|
120
|
+
if response.is_success:
|
|
121
|
+
return response
|
|
122
|
+
response.read()
|
|
123
|
+
error = _api_error(response)
|
|
124
|
+
response.close()
|
|
125
|
+
except httpx.TransportError as e:
|
|
126
|
+
error = e
|
|
127
|
+
delay = self._retry_delay(method, error, attempt)
|
|
128
|
+
if delay is None or waited + delay > self._max_retry_wait:
|
|
129
|
+
raise error
|
|
130
|
+
waited += delay
|
|
131
|
+
time.sleep(delay)
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def _retry_delay(method: str, error: Exception, attempt: int) -> float | None:
|
|
135
|
+
"""How long to wait before repeating a failed request, or None."""
|
|
136
|
+
if isinstance(error, APIError):
|
|
137
|
+
# A rate limit is answered before the request is processed, so
|
|
138
|
+
# any request can be repeated.
|
|
139
|
+
if error.status_code == 429 or (error.status_code == 503 and error.code == "RATE_LIMIT_UNAVAILABLE"):
|
|
140
|
+
return error.retry_after or 10.0
|
|
141
|
+
if error.status_code < 500:
|
|
142
|
+
return None
|
|
143
|
+
# Server errors and network failures: GET only, after 1, 2 and 4 s.
|
|
144
|
+
if method != "GET" or attempt >= 4:
|
|
145
|
+
return None
|
|
146
|
+
return float(2 ** (attempt - 1))
|
|
147
|
+
|
|
148
|
+
def _call(self, method: str, path: str, model: type[T] | None = None, *,
|
|
149
|
+
params: dict[str, Any] | None = None, body: Any = None) -> Any:
|
|
150
|
+
response = self._send(method, path, _clean(params or {}), body)
|
|
151
|
+
try:
|
|
152
|
+
reply = response.json()
|
|
153
|
+
except json.JSONDecodeError as e:
|
|
154
|
+
raise InvalidResponseError("the answer is not JSON") from e
|
|
155
|
+
if not isinstance(reply, dict) or not reply.get("success") or "data" not in reply:
|
|
156
|
+
raise InvalidResponseError("no success envelope")
|
|
157
|
+
if model is None:
|
|
158
|
+
return None
|
|
159
|
+
return model.model_validate(reply["data"])
|
|
160
|
+
|
|
161
|
+
def _download(self, path: str, params: dict[str, Any] | None, out: IO[bytes] | None) -> bytes | None:
|
|
162
|
+
response = self._send("GET", path, _clean(params or {}), accept="*/*", stream=True)
|
|
163
|
+
try:
|
|
164
|
+
if out is None:
|
|
165
|
+
return response.read()
|
|
166
|
+
for chunk in response.iter_bytes():
|
|
167
|
+
out.write(chunk)
|
|
168
|
+
return None
|
|
169
|
+
finally:
|
|
170
|
+
response.close()
|
|
171
|
+
|
|
172
|
+
def _pages(self, fetch: Callable[[str | None], Any]) -> Iterator[Any]:
|
|
173
|
+
"""Yields every item of a cursor-paged list."""
|
|
174
|
+
cursor: str | None = None
|
|
175
|
+
while True:
|
|
176
|
+
page = fetch(cursor)
|
|
177
|
+
yield from page.items
|
|
178
|
+
nxt = page.page.next_cursor
|
|
179
|
+
if not page.page.has_more or not nxt or nxt == cursor:
|
|
180
|
+
return
|
|
181
|
+
cursor = nxt
|
|
182
|
+
|
|
183
|
+
# Reports
|
|
184
|
+
|
|
185
|
+
def report(self, report_id: str) -> m.Report:
|
|
186
|
+
"""The full report: the overview's fields plus every HTTP transaction,
|
|
187
|
+
script and artifact. Captured content is downloaded with
|
|
188
|
+
``resource_content``."""
|
|
189
|
+
return self._call("GET", f"/reports/{report_id}", m.Report)
|
|
190
|
+
|
|
191
|
+
def report_overview(self, report_id: str) -> m.ReportOverview:
|
|
192
|
+
"""A report's overview: URLs, IP, title, tags, settings, alerts and hosts."""
|
|
193
|
+
return self._call("GET", f"/reports/{report_id}/overview", m.ReportOverview)
|
|
194
|
+
|
|
195
|
+
def compare_reports(self, a: str, b: str) -> m.ReportComparison:
|
|
196
|
+
"""What changed from report ``a``, the earlier or baseline, to ``b``.
|
|
197
|
+
It counts as two report lookups."""
|
|
198
|
+
return self._call("GET", f"/reports/{a}/compare/{b}", m.ReportComparison)
|
|
199
|
+
|
|
200
|
+
def delete_report(self, report_id: str) -> None:
|
|
201
|
+
"""Deletes a report you own."""
|
|
202
|
+
self._call("DELETE", f"/reports/{report_id}")
|
|
203
|
+
|
|
204
|
+
def screenshot(self, report_id: str, out: IO[bytes] | None = None) -> bytes | None:
|
|
205
|
+
"""A report's screenshot (PNG): returned, or written to ``out``."""
|
|
206
|
+
return self._download(f"/reports/{report_id}/screenshot", None, out)
|
|
207
|
+
|
|
208
|
+
def resource_content(self, report_id: str, sha256: str, out: IO[bytes] | None = None) -> bytes | None:
|
|
209
|
+
"""Content the report captured, by its SHA-256: returned, or written to
|
|
210
|
+
``out``. It comes from the analyzed site and may be malicious: don't
|
|
211
|
+
open or run it outside an isolated environment."""
|
|
212
|
+
return self._download(f"/reports/{report_id}/resources/{sha256}/content", None, out)
|
|
213
|
+
|
|
214
|
+
def recent_reports(self, scope: Scope = "all", *, limit: int | None = None,
|
|
215
|
+
cursor: str | None = None) -> m.ReportPage:
|
|
216
|
+
"""A page of recent reports, newest first: yours and the others your key
|
|
217
|
+
may see (``all``), yours, your team's, or those your YARA rules matched
|
|
218
|
+
in the last year (``alerted``)."""
|
|
219
|
+
return self._call("GET", "/reports/recent", m.ReportPage,
|
|
220
|
+
params={"scope": scope, "limit": limit, "cursor": cursor})
|
|
221
|
+
|
|
222
|
+
def iter_recent_reports(self, scope: Scope = "all", *, limit: int | None = None) -> Iterator[m.ReportOverview]:
|
|
223
|
+
"""Every recent report, across pages. Stop when you have enough."""
|
|
224
|
+
return self._pages(lambda cursor: self.recent_reports(scope, limit=limit, cursor=cursor))
|
|
225
|
+
|
|
226
|
+
def related_reports(self, scope: RelatedScope, value: str, *, limit: int | None = None,
|
|
227
|
+
cursor: str | None = None) -> m.ReportPage:
|
|
228
|
+
"""A page of recent reports for the same target IP address, ASN or
|
|
229
|
+
domain: public reports, plus restricted ones for ``ip`` when your
|
|
230
|
+
account has restricted access."""
|
|
231
|
+
return self._call("GET", "/reports/related", m.ReportPage,
|
|
232
|
+
params={"scope": scope, "value": value, "limit": limit, "cursor": cursor})
|
|
233
|
+
|
|
234
|
+
def iter_related_reports(self, scope: RelatedScope, value: str, *,
|
|
235
|
+
limit: int | None = None) -> Iterator[m.ReportOverview]:
|
|
236
|
+
"""Every related report, across pages."""
|
|
237
|
+
return self._pages(lambda cursor: self.related_reports(scope, value, limit=limit, cursor=cursor))
|
|
238
|
+
|
|
239
|
+
def search_reports(self, query: str, *, limit: int | None = None, offset: int | None = None) -> m.ReportSearchResult:
|
|
240
|
+
"""Searches the last year of reports your key can see, in the search
|
|
241
|
+
syntax: https://docs.urlquery.net/docs/concepts/search-syntax.
|
|
242
|
+
``offset`` plus ``limit`` is at most 10,000."""
|
|
243
|
+
return self._call("GET", "/reports/search", m.ReportSearchResult,
|
|
244
|
+
params={"query": query, "limit": limit, "offset": offset})
|
|
245
|
+
|
|
246
|
+
def iter_search_results(self, query: str, *, limit: int = 100) -> Iterator[m.ReportOverview]:
|
|
247
|
+
"""Every search result, across pages, up to the first 10,000."""
|
|
248
|
+
offset = 0
|
|
249
|
+
while offset < _MAX_SEARCH_WINDOW:
|
|
250
|
+
page = self.search_reports(query, limit=min(limit, _MAX_SEARCH_WINDOW - offset), offset=offset)
|
|
251
|
+
yield from page.items
|
|
252
|
+
offset += limit
|
|
253
|
+
if offset >= page.page.total_hits:
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
# Submissions
|
|
257
|
+
|
|
258
|
+
def submit(self, url: str, *, access: Access | None = None, tags: list[str] | None = None,
|
|
259
|
+
meta: dict[str, str] | None = None, device_type: str | None = None,
|
|
260
|
+
useragent: str | None = None, run_time: int | None = None, sanitize_url: bool | None = None,
|
|
261
|
+
wait: bool = False, wait_timeout: float = 300.0) -> m.Submission:
|
|
262
|
+
"""Queues a URL for analysis. Choose ``access`` deliberately: without it
|
|
263
|
+
the report is public, visible to every account.
|
|
264
|
+
|
|
265
|
+
The answer holds the ``queue_id`` and the ``report_id`` the report
|
|
266
|
+
will have. With ``wait``, it returns when the analysis is done or has
|
|
267
|
+
failed; check ``status``. A submission is never retried once it may
|
|
268
|
+
have been queued.
|
|
269
|
+
"""
|
|
270
|
+
request = _request(m.SubmissionRequest, url=url, access=access, tags=tags, meta=meta, device_type=device_type,
|
|
271
|
+
useragent=useragent, run_time=run_time, sanitize_url=sanitize_url)
|
|
272
|
+
submission = self._call("POST", "/submissions", m.Submission, body=_body(request))
|
|
273
|
+
if wait:
|
|
274
|
+
return self.wait_for_submission(submission.queue_id, timeout=wait_timeout)
|
|
275
|
+
return submission
|
|
276
|
+
|
|
277
|
+
def submission(self, queue_id: str) -> m.Submission:
|
|
278
|
+
"""A submission's progress."""
|
|
279
|
+
return self._call("GET", f"/submissions/{queue_id}", m.Submission)
|
|
280
|
+
|
|
281
|
+
def wait_for_submission(self, queue_id: str, *, timeout: float = 300.0) -> m.Submission:
|
|
282
|
+
"""Polls a submission until its analysis is done or has failed; check
|
|
283
|
+
``status``. Raises ``WaitTimeoutError``, with the last state it saw,
|
|
284
|
+
when ``timeout`` seconds pass first."""
|
|
285
|
+
deadline = time.monotonic() + timeout
|
|
286
|
+
last: m.Submission | None = None
|
|
287
|
+
while True:
|
|
288
|
+
last = self.submission(queue_id)
|
|
289
|
+
if last.status in ("done", "failed"):
|
|
290
|
+
return last
|
|
291
|
+
if time.monotonic() + self._poll_interval > deadline:
|
|
292
|
+
raise WaitTimeoutError(last)
|
|
293
|
+
time.sleep(self._poll_interval)
|
|
294
|
+
|
|
295
|
+
# Reputation
|
|
296
|
+
|
|
297
|
+
def lookup_reputation(self, url: str) -> m.ReputationLookup:
|
|
298
|
+
"""urlquery's verdict for a URL over the last 30 days: malicious,
|
|
299
|
+
suspicious, benign or unknown. ``applied_to`` says whether it comes
|
|
300
|
+
from the exact URL or its host name."""
|
|
301
|
+
return self._call("POST", "/reputation/lookup", m.ReputationLookup, body={"url": url})
|
|
302
|
+
|
|
303
|
+
def export_reputation(self, out: IO[bytes], *, timeframe: str | None = None,
|
|
304
|
+
as_of: datetime | None = None, types: list[str] | None = None) -> None:
|
|
305
|
+
"""Writes urlquery's reputation indicators to ``out`` as NDJSON: a
|
|
306
|
+
``meta`` record, one ``indicator`` record each, and a ``complete``
|
|
307
|
+
record last. Without the complete record the export is incomplete;
|
|
308
|
+
discard it. It needs the reputation_export capability."""
|
|
309
|
+
self._download("/reputation/export", {"timeframe": timeframe, "as_of": as_of, "type": types}, out)
|
|
310
|
+
|
|
311
|
+
# Host Profile
|
|
312
|
+
|
|
313
|
+
def host(self, host: str, *, fact_limit: int | None = None) -> m.HostDetails:
|
|
314
|
+
"""What urlquery has observed about a host name, or an IP address
|
|
315
|
+
pages were loaded from directly."""
|
|
316
|
+
return self._call("GET", f"/hosts/{host}", m.HostDetails, params={"limit": fact_limit})
|
|
317
|
+
|
|
318
|
+
def list_hosts(self, *, limit: int | None = None, cursor: str | None = None, sort: str | None = None,
|
|
319
|
+
order: str | None = None, **pivot: Any) -> m.HostPage:
|
|
320
|
+
"""A page of the hosts that share one fact. Give exactly one pivot:
|
|
321
|
+
``domain``, ``ip``, ``asn``, ``country``, ``technology``,
|
|
322
|
+
``certificate``, ``cookie``, ``header`` or ``mime``. ``include_apex``
|
|
323
|
+
goes with ``domain``; ``secure``, ``http_only``, ``partitioned``,
|
|
324
|
+
``host_only``, ``persistent``, ``same_site`` and ``path`` with
|
|
325
|
+
``cookie``."""
|
|
326
|
+
return self._call("GET", "/hosts", m.HostPage,
|
|
327
|
+
params={**pivot, "limit": limit, "cursor": cursor, "sort": sort, "order": order})
|
|
328
|
+
|
|
329
|
+
def iter_hosts(self, *, limit: int | None = None, sort: str | None = None, order: str | None = None,
|
|
330
|
+
**pivot: Any) -> Iterator[m.HostListItem]:
|
|
331
|
+
"""Every host that shares one fact, across pages."""
|
|
332
|
+
return self._pages(lambda cursor: self.list_hosts(limit=limit, cursor=cursor, sort=sort, order=order, **pivot))
|
|
333
|
+
|
|
334
|
+
def search_hosts(self, *, limit: int | None = None, cursor: str | None = None, sort: str | None = None,
|
|
335
|
+
order: str | None = None, **filters: Any) -> m.HostSearchPage:
|
|
336
|
+
"""A page of hosts by when they were seen and by their relations, with
|
|
337
|
+
the API's filters as keyword arguments, such as
|
|
338
|
+
``first_seen_after=datetime(...)``, ``incoming_relation_type="redirects_to"``
|
|
339
|
+
and ``min_incoming_relation_count=10``."""
|
|
340
|
+
return self._call("GET", "/hosts/search", m.HostSearchPage,
|
|
341
|
+
params={**filters, "limit": limit, "cursor": cursor, "sort": sort, "order": order})
|
|
342
|
+
|
|
343
|
+
def iter_search_hosts(self, *, limit: int | None = None, sort: str | None = None, order: str | None = None,
|
|
344
|
+
**filters: Any) -> Iterator[m.HostSearchItem]:
|
|
345
|
+
"""Every host matching the filters, across pages."""
|
|
346
|
+
return self._pages(lambda cursor: self.search_hosts(limit=limit, cursor=cursor, sort=sort, order=order, **filters))
|
|
347
|
+
|
|
348
|
+
def relations(self, host: str | None = None, *, type: str | None = None, direction: str | None = None,
|
|
349
|
+
source: str | None = None, target: str | None = None, limit: int | None = None,
|
|
350
|
+
cursor: str | None = None, sort: str | None = None, order: str | None = None) -> m.RelationPage:
|
|
351
|
+
"""A page of relations: ``redirects_to``, ``loads_from``, ``calls`` or
|
|
352
|
+
``embeds``. With ``host``, that host's relations, in a ``direction``;
|
|
353
|
+
without, relations across hosts, narrowed by ``source`` and ``target``."""
|
|
354
|
+
params = {"type": type, "limit": limit, "cursor": cursor, "sort": sort, "order": order}
|
|
355
|
+
if host:
|
|
356
|
+
return self._call("GET", f"/hosts/{host}/relations", m.RelationPage,
|
|
357
|
+
params={**params, "direction": direction})
|
|
358
|
+
return self._call("GET", "/hosts/relations", m.RelationPage,
|
|
359
|
+
params={**params, "source": source, "target": target})
|
|
360
|
+
|
|
361
|
+
def iter_relations(self, host: str | None = None, **kwargs: Any) -> Iterator[m.Relation]:
|
|
362
|
+
"""Every relation, across pages; the arguments of ``relations``."""
|
|
363
|
+
return self._pages(lambda cursor: self.relations(host, cursor=cursor, **kwargs))
|
|
364
|
+
|
|
365
|
+
# YARA
|
|
366
|
+
|
|
367
|
+
def yara_sets(self) -> list[m.YARASet]:
|
|
368
|
+
"""The rule sets you can see."""
|
|
369
|
+
return self._call("GET", "/detection/yara/sets", m.YARASetList).items
|
|
370
|
+
|
|
371
|
+
def yara_set(self, set_id: str) -> m.YARASet:
|
|
372
|
+
return self._call("GET", f"/detection/yara/sets/{set_id}", m.YARASet)
|
|
373
|
+
|
|
374
|
+
def create_yara_set(self, name: str, *, description: str | None = None,
|
|
375
|
+
visibility: Literal["private", "team"] | None = None) -> m.YARASet:
|
|
376
|
+
request = _request(m.YARASetRequest, name=name, description=description, visibility=visibility)
|
|
377
|
+
return self._call("POST", "/detection/yara/sets", m.YARASet, body=_body(request))
|
|
378
|
+
|
|
379
|
+
def update_yara_set(self, set_id: str, name: str, *, description: str | None = None,
|
|
380
|
+
visibility: Literal["private", "team"] | None = None) -> m.YARASet:
|
|
381
|
+
"""Replaces a set's name, description and visibility."""
|
|
382
|
+
request = _request(m.YARASetUpdateRequest, name=name, description=description, visibility=visibility)
|
|
383
|
+
return self._call("PUT", f"/detection/yara/sets/{set_id}", m.YARASet, body=_body(request))
|
|
384
|
+
|
|
385
|
+
def delete_yara_set(self, set_id: str) -> None:
|
|
386
|
+
"""Deletes a set and its rules."""
|
|
387
|
+
self._call("DELETE", f"/detection/yara/sets/{set_id}")
|
|
388
|
+
|
|
389
|
+
def yara_rules(self, set_id: str) -> list[m.YARARule]:
|
|
390
|
+
return self._call("GET", f"/detection/yara/sets/{set_id}/rules", m.YARARuleList).items
|
|
391
|
+
|
|
392
|
+
def yara_rule(self, rule_id: str) -> m.YARARule:
|
|
393
|
+
return self._call("GET", f"/detection/yara/rules/{rule_id}", m.YARARule)
|
|
394
|
+
|
|
395
|
+
def create_yara_rule(self, set_id: str, name: str, source: str, *, description: str | None = None,
|
|
396
|
+
visibility: Literal["private", "team"] | None = None,
|
|
397
|
+
alert_visibility: Literal["private", "team"] | None = None,
|
|
398
|
+
can_team_edit: bool | None = None) -> m.YARARule:
|
|
399
|
+
"""Compiles and saves a rule. New rules are enabled and scan new
|
|
400
|
+
analyses within a few minutes; try a source with ``test_yara`` first."""
|
|
401
|
+
request = _request(m.YARARuleRequest, name=name, content=source, description=description, visibility=visibility,
|
|
402
|
+
alert_visibility=alert_visibility, can_team_edit=can_team_edit)
|
|
403
|
+
return self._call("POST", f"/detection/yara/sets/{set_id}/rules", m.YARARule, body=_body(request))
|
|
404
|
+
|
|
405
|
+
def update_yara_rule(self, rule_id: str, name: str, source: str, *, description: str | None = None,
|
|
406
|
+
visibility: Literal["private", "team"] | None = None,
|
|
407
|
+
alert_visibility: Literal["private", "team"] | None = None,
|
|
408
|
+
can_team_edit: bool | None = None, enabled: bool | None = None) -> m.YARARule:
|
|
409
|
+
"""Replaces a rule; ``enabled=False`` switches it off, None keeps its state."""
|
|
410
|
+
request = _request(m.YARARuleRequest, name=name, content=source, description=description, visibility=visibility,
|
|
411
|
+
alert_visibility=alert_visibility, can_team_edit=can_team_edit,
|
|
412
|
+
enabled=enabled)
|
|
413
|
+
return self._call("PUT", f"/detection/yara/rules/{rule_id}", m.YARARule, body=_body(request))
|
|
414
|
+
|
|
415
|
+
def delete_yara_rule(self, rule_id: str) -> None:
|
|
416
|
+
self._call("DELETE", f"/detection/yara/rules/{rule_id}")
|
|
417
|
+
|
|
418
|
+
def yara_rule_stats(self, rule_id: str, *, days: int | None = None) -> m.YARARuleStats:
|
|
419
|
+
"""A rule's matches over the last ``days``, 1-90 (default 30)."""
|
|
420
|
+
return self._call("GET", f"/detection/yara/rules/{rule_id}/stats", m.YARARuleStats, params={"days": days})
|
|
421
|
+
|
|
422
|
+
def yara_rule_matches(self, rule_id: str, *, days: int | None = None, limit: int | None = None,
|
|
423
|
+
cursor: str | None = None) -> m.YARARuleMatchList:
|
|
424
|
+
"""A page of the reports a rule matched, newest first; ``hidden``
|
|
425
|
+
counts matches in reports you can't see."""
|
|
426
|
+
return self._call("GET", f"/detection/yara/rules/{rule_id}/matches", m.YARARuleMatchList,
|
|
427
|
+
params={"days": days, "limit": limit, "cursor": cursor})
|
|
428
|
+
|
|
429
|
+
def iter_yara_rule_matches(self, rule_id: str, *, days: int | None = None,
|
|
430
|
+
limit: int | None = None) -> Iterator[m.YARARuleMatch]:
|
|
431
|
+
return self._pages(lambda cursor: self.yara_rule_matches(rule_id, days=days, limit=limit, cursor=cursor))
|
|
432
|
+
|
|
433
|
+
def validate_yara(self, source: str) -> m.YARAValidation:
|
|
434
|
+
"""Compiles a source without saving it. A source that doesn't compile is
|
|
435
|
+
not an error: ``valid`` is False and ``diagnostics`` say why."""
|
|
436
|
+
return self._call("POST", "/detection/yara/validate", m.YARAValidation, body={"content": source})
|
|
437
|
+
|
|
438
|
+
def test_yara(self, source: str, report_id: str) -> m.YARAReportTest:
|
|
439
|
+
"""Runs a source against a report's final DOM, scripts and stored
|
|
440
|
+
response bodies, without saving it."""
|
|
441
|
+
return self._call("POST", "/detection/yara/test", m.YARAReportTest,
|
|
442
|
+
body={"content": source, "report_id": report_id})
|
|
443
|
+
|
|
444
|
+
# Monitoring
|
|
445
|
+
|
|
446
|
+
def page_monitors(self) -> list[m.PageMonitor]:
|
|
447
|
+
return self._call("GET", "/monitoring/pages", m.PageMonitorList).items
|
|
448
|
+
|
|
449
|
+
def page_monitor(self, monitor_id: str) -> m.PageMonitor:
|
|
450
|
+
return self._call("GET", f"/monitoring/pages/{monitor_id}", m.PageMonitor)
|
|
451
|
+
|
|
452
|
+
def create_page_monitor(self, request: m.PageMonitorCreateRequest) -> m.PageMonitor:
|
|
453
|
+
"""Rescans a report's URL on a schedule and compares each scan with the
|
|
454
|
+
report. Every scan is a submission on your account; the first runs
|
|
455
|
+
within a minute."""
|
|
456
|
+
return self._call("POST", "/monitoring/pages", m.PageMonitor, body=_body(request))
|
|
457
|
+
|
|
458
|
+
def update_page_monitor(self, monitor_id: str, request: m.PageMonitorUpdateRequest) -> m.PageMonitor:
|
|
459
|
+
"""Changes, pauses (``enabled=False``) or resumes a monitor; unset
|
|
460
|
+
fields keep their values."""
|
|
461
|
+
return self._call("PATCH", f"/monitoring/pages/{monitor_id}", m.PageMonitor, body=_body(request))
|
|
462
|
+
|
|
463
|
+
def delete_page_monitor(self, monitor_id: str) -> None:
|
|
464
|
+
"""Deletes a monitor and its runs; the reports stay."""
|
|
465
|
+
self._call("DELETE", f"/monitoring/pages/{monitor_id}")
|
|
466
|
+
|
|
467
|
+
def page_monitor_runs(self, monitor_id: str, *, limit: int | None = None) -> list[m.PageMonitorRun]:
|
|
468
|
+
"""A monitor's latest runs, newest first (at most 100, default 25)."""
|
|
469
|
+
return self._call("GET", f"/monitoring/pages/{monitor_id}/runs", m.PageMonitorRunList,
|
|
470
|
+
params={"limit": limit}).items
|
|
471
|
+
|
|
472
|
+
def set_page_monitor_baseline(self, monitor_id: str, report_id: str) -> m.PageMonitor:
|
|
473
|
+
"""Makes another report of the monitor's URL its baseline."""
|
|
474
|
+
return self._call("POST", f"/monitoring/pages/{monitor_id}/baseline", m.PageMonitor,
|
|
475
|
+
body={"report_id": report_id})
|
|
476
|
+
|
|
477
|
+
def watchlists(self) -> list[m.Watchlist]:
|
|
478
|
+
return self._call("GET", "/monitoring/watchlists", m.WatchlistList).items
|
|
479
|
+
|
|
480
|
+
def watchlist(self, watchlist_id: str) -> m.Watchlist:
|
|
481
|
+
return self._call("GET", f"/monitoring/watchlists/{watchlist_id}", m.Watchlist)
|
|
482
|
+
|
|
483
|
+
def create_watchlist(self, name: str, indicators: Iterable[str] = ()) -> m.CreatedWatchlist:
|
|
484
|
+
"""Creates a watchlist with indicators: SHA256 hashes, IPs, domains,
|
|
485
|
+
FQDNs, URLs, or URL patterns with ``*``; defanged values are accepted.
|
|
486
|
+
More than 500 are sent 500 at a time; values not added are in
|
|
487
|
+
``skipped``, with why."""
|
|
488
|
+
values = list(indicators)
|
|
489
|
+
first = values[:_MAX_INDICATORS]
|
|
490
|
+
body: dict[str, Any] = {"name": name}
|
|
491
|
+
if first:
|
|
492
|
+
body["indicators"] = first
|
|
493
|
+
created = self._call("POST", "/monitoring/watchlists", m.CreatedWatchlist, body=body)
|
|
494
|
+
if len(values) > len(first):
|
|
495
|
+
rest = self.add_watchlist_indicators(created.watchlist.id, values[len(first):])
|
|
496
|
+
created.added.extend(rest.added)
|
|
497
|
+
created.skipped.extend(rest.skipped)
|
|
498
|
+
created.watchlist = self.watchlist(created.watchlist.id)
|
|
499
|
+
return created
|
|
500
|
+
|
|
501
|
+
def update_watchlist(self, watchlist_id: str, *, name: str | None = None,
|
|
502
|
+
enabled: bool | None = None) -> m.Watchlist:
|
|
503
|
+
"""Renames, pauses (``enabled=False``) or resumes a watchlist."""
|
|
504
|
+
return self._call("PATCH", f"/monitoring/watchlists/{watchlist_id}", m.Watchlist,
|
|
505
|
+
body=_body(_request(m.WatchlistUpdateRequest, name=name, enabled=enabled)))
|
|
506
|
+
|
|
507
|
+
def delete_watchlist(self, watchlist_id: str) -> None:
|
|
508
|
+
"""Deletes a watchlist, its indicators and its reports list."""
|
|
509
|
+
self._call("DELETE", f"/monitoring/watchlists/{watchlist_id}")
|
|
510
|
+
|
|
511
|
+
def watchlist_indicators(self, watchlist_id: str) -> list[m.Indicator]:
|
|
512
|
+
return self._call("GET", f"/monitoring/watchlists/{watchlist_id}/indicators", m.IndicatorList).items
|
|
513
|
+
|
|
514
|
+
def add_watchlist_indicators(self, watchlist_id: str, indicators: Iterable[str]) -> m.IndicatorBatch:
|
|
515
|
+
"""Adds indicators, 500 at a time, and combines the answers."""
|
|
516
|
+
values = list(indicators)
|
|
517
|
+
out = m.IndicatorBatch(added=[], skipped=[])
|
|
518
|
+
for start in range(0, len(values), _MAX_INDICATORS):
|
|
519
|
+
part = self._call("POST", f"/monitoring/watchlists/{watchlist_id}/indicators", m.IndicatorBatch,
|
|
520
|
+
body={"indicators": values[start:start + _MAX_INDICATORS]})
|
|
521
|
+
out.added.extend(part.added)
|
|
522
|
+
out.skipped.extend(part.skipped)
|
|
523
|
+
return out
|
|
524
|
+
|
|
525
|
+
def remove_watchlist_indicator(self, watchlist_id: str, kind: str, value: str) -> None:
|
|
526
|
+
"""Removes an indicator; the reports it matched stay listed. ``kind`` is
|
|
527
|
+
sha256, ip, domain, fqdn, url or url_pattern."""
|
|
528
|
+
self._call("DELETE", f"/monitoring/watchlists/{watchlist_id}/indicators",
|
|
529
|
+
params={"kind": kind, "value": value})
|
|
530
|
+
|
|
531
|
+
def watchlist_reports(self, watchlist_id: str, *, limit: int | None = None,
|
|
532
|
+
cursor: str | None = None) -> m.WatchlistReportList:
|
|
533
|
+
"""A page of the reports a watchlist matched, newest first; ``hidden``
|
|
534
|
+
counts matches in reports you can't see."""
|
|
535
|
+
return self._call("GET", f"/monitoring/watchlists/{watchlist_id}/reports", m.WatchlistReportList,
|
|
536
|
+
params={"limit": limit, "cursor": cursor})
|
|
537
|
+
|
|
538
|
+
def iter_watchlist_reports(self, watchlist_id: str, *, limit: int | None = None) -> Iterator[m.WatchlistReport]:
|
|
539
|
+
return self._pages(lambda cursor: self.watchlist_reports(watchlist_id, limit=limit, cursor=cursor))
|
|
540
|
+
|
|
541
|
+
def watchlist_stats(self, watchlist_id: str, *, days: int | None = None) -> m.WatchlistStats:
|
|
542
|
+
"""A watchlist's activity over the last 7, 30 or 90 days (default 30)."""
|
|
543
|
+
return self._call("GET", f"/monitoring/watchlists/{watchlist_id}/stats", m.WatchlistStats,
|
|
544
|
+
params={"days": days})
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _api_error(response: httpx.Response) -> APIError:
|
|
548
|
+
retry_after: float | None = None
|
|
549
|
+
try:
|
|
550
|
+
retry_after = max(float(response.headers.get("Retry-After", "")), 1.0)
|
|
551
|
+
except ValueError:
|
|
552
|
+
pass
|
|
553
|
+
code = message = ""
|
|
554
|
+
try:
|
|
555
|
+
error = response.json().get("error") or {}
|
|
556
|
+
code = str(error.get("error", ""))
|
|
557
|
+
message = " ".join(str(error.get("message", "")).split())
|
|
558
|
+
except (json.JSONDecodeError, AttributeError):
|
|
559
|
+
pass
|
|
560
|
+
return APIError(response.status_code, code, message, retry_after)
|
urlquery_api/_errors.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from .models import Submission
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class URLQueryError(Exception):
|
|
10
|
+
"""Base class of this library's errors."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class APIError(URLQueryError):
|
|
14
|
+
"""An error answer from the API.
|
|
15
|
+
|
|
16
|
+
``code`` is the stable error code, such as ``NOT_FOUND`` or
|
|
17
|
+
``RATE_LIMIT_EXCEEDED``; see https://docs.urlquery.net/docs/api/overview#errors.
|
|
18
|
+
It is empty when the answer was not the API's error envelope, for example
|
|
19
|
+
from a proxy.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, status_code: int, code: str = "", message: str = "", retry_after: float | None = None):
|
|
23
|
+
self.status_code = status_code
|
|
24
|
+
self.code = code
|
|
25
|
+
self.message = message
|
|
26
|
+
#: Seconds to wait before retrying, from a 429's Retry-After header.
|
|
27
|
+
self.retry_after = retry_after
|
|
28
|
+
text = f"{status_code} {code}".strip()
|
|
29
|
+
super().__init__(f"{text}: {message}" if message else text)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def is_not_found(self) -> bool:
|
|
33
|
+
"""Whether the resource doesn't exist, or the API key can't see it."""
|
|
34
|
+
return self.status_code == 404
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InvalidResponseError(URLQueryError):
|
|
38
|
+
"""An answer that is not a valid v2 response."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class WaitTimeoutError(URLQueryError):
|
|
42
|
+
"""The analysis did not end before the wait's timeout.
|
|
43
|
+
|
|
44
|
+
The submission is still queued; ``submission`` is the last state the wait
|
|
45
|
+
saw, with its queue and report IDs.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, submission: Submission | None):
|
|
49
|
+
self.submission = submission
|
|
50
|
+
super().__init__("the analysis did not end before the timeout")
|