ransomlive-cli 0.0.1__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.
ransomlive/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Command-line client for the Ransomware.live Pro REST API."""
ransomlive/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from ransomlive.cli import main
2
+
3
+ raise SystemExit(main())
ransomlive/api.py ADDED
@@ -0,0 +1,89 @@
1
+ import os
2
+ import ssl
3
+ from pathlib import Path
4
+ from typing import TypeAlias
5
+
6
+ import httpx
7
+ from dotenv import dotenv_values
8
+
9
+ API_URL = "https://api-pro.ransomware.live"
10
+ AUTH_ENV_VAR = "RANSOMWARE_LIVE_TOKEN"
11
+
12
+ JSONValue: TypeAlias = "dict[str, JSONValue] | list[JSONValue] | str | int | float | bool | None"
13
+
14
+
15
+ class APIError(Exception):
16
+ def __init__(self, message: str, *, exit_code: int = 1) -> None:
17
+ super().__init__(message)
18
+ self.exit_code = exit_code
19
+
20
+
21
+ def api_key(env_file: Path = Path(".env")) -> str:
22
+ value = os.environ.get(AUTH_ENV_VAR)
23
+ if value is None:
24
+ try:
25
+ with env_file.open(encoding="utf-8-sig") as stream:
26
+ value = dotenv_values(stream=stream, interpolate=False).get(AUTH_ENV_VAR)
27
+ except FileNotFoundError:
28
+ pass
29
+ except (OSError, UnicodeError):
30
+ raise APIError("Could not read the environment file.", exit_code=2) from None
31
+ key = (value or "").strip()
32
+ if not key or key == "your_token_here":
33
+ raise APIError(f"Set {AUTH_ENV_VAR} in your environment or .env file.", exit_code=2)
34
+ if not all("!" <= char <= "~" for char in key):
35
+ raise APIError(f"{AUTH_ENV_VAR} contains invalid characters.", exit_code=2)
36
+ return key
37
+
38
+
39
+ def make_client(key: str, *, verify: bool = True) -> httpx.Client:
40
+ return httpx.Client(
41
+ base_url=API_URL,
42
+ headers={"X-API-KEY": key, "Accept": "application/json"},
43
+ timeout=httpx.Timeout(30.0, connect=10.0),
44
+ verify=verify,
45
+ follow_redirects=False,
46
+ trust_env=False,
47
+ )
48
+
49
+
50
+ def get_json(client: httpx.Client, path: str, params: dict[str, str]) -> JSONValue:
51
+ try:
52
+ response = client.get(path, params=params)
53
+ except httpx.TimeoutException:
54
+ raise APIError("Request to Ransomware.live timed out.") from None
55
+ except httpx.ConnectError as error:
56
+ pending: list[BaseException] = [error]
57
+ seen: set[int] = set()
58
+ while pending:
59
+ cause = pending.pop()
60
+ if id(cause) in seen:
61
+ continue
62
+ seen.add(id(cause))
63
+ if isinstance(cause, ssl.SSLCertVerificationError):
64
+ raise APIError(
65
+ "TLS certificate verification failed for Ransomware.live; "
66
+ "check your network's certificate configuration."
67
+ ) from None
68
+ pending.extend(
69
+ nested for nested in (cause.__cause__, cause.__context__) if nested is not None
70
+ )
71
+ raise APIError("Could not connect to Ransomware.live.") from None
72
+ except httpx.RequestError:
73
+ raise APIError("Could not complete the request to Ransomware.live.") from None
74
+
75
+ status = response.status_code
76
+ if status in (401, 403):
77
+ raise APIError(f"API refused access (HTTP {status}); check the key and its access.")
78
+ if status == 404:
79
+ raise APIError("Resource not found (HTTP 404).")
80
+ if status == 429:
81
+ retry = response.headers.get("Retry-After", "")
82
+ hint = f" Wait at least {retry} seconds." if retry.isascii() and retry.isdigit() else ""
83
+ raise APIError(f"API quota or rate limit reached (HTTP 429).{hint}", exit_code=3)
84
+ if not response.is_success:
85
+ raise APIError(f"Unexpected API response (HTTP {status}).")
86
+ try:
87
+ return response.json()
88
+ except ValueError:
89
+ raise APIError("API did not return valid JSON.") from None
ransomlive/cli.py ADDED
@@ -0,0 +1,46 @@
1
+ import sys
2
+ from importlib.metadata import version
3
+ from pathlib import Path
4
+
5
+ from ransomlive.api import APIError, api_key, get_json, make_client
6
+ from ransomlive.commands import build_parser, request_for
7
+ from ransomlive.lookups import execute_lookup, reverse_lookup
8
+ from ransomlive.output import render
9
+
10
+ _LEAK_SITE_COMMANDS = {"leak-sites", "lookup-leak-site"}
11
+ _ONLINE_LOOKUPS = {"lookup-domain", "lookup-name", "leak-sites", "search-groups"}
12
+
13
+
14
+ def main(argv: list[str] | None = None) -> int:
15
+ parser = build_parser(version("ransomlive-cli"))
16
+ args = parser.parse_args(argv)
17
+ try:
18
+ if args.command == "lookup-leak-site":
19
+ data = reverse_lookup(args.hostname, args.profiles)
20
+ else:
21
+ is_lookup = args.command in _ONLINE_LOOKUPS
22
+ path, params = ("", {}) if is_lookup else request_for(parser, args)
23
+ key = api_key(getattr(args, "env_file", Path(".env")))
24
+ insecure = getattr(args, "insecure", False)
25
+ if insecure:
26
+ print(
27
+ "ransomlive: WARNING: TLS certificate verification is disabled; "
28
+ "your API key and data could be intercepted.",
29
+ file=sys.stderr,
30
+ )
31
+ with make_client(key, verify=not insecure) as client:
32
+ data = execute_lookup(client, args) if is_lookup else get_json(client, path, params)
33
+ render(
34
+ data,
35
+ sys.stdout,
36
+ getattr(args, "format", "auto"),
37
+ defanged=getattr(args, "defang", args.command in _LEAK_SITE_COMMANDS),
38
+ )
39
+ except APIError as error:
40
+ print(f"ransomlive: {error}", file=sys.stderr)
41
+ return error.exit_code
42
+ except KeyboardInterrupt:
43
+ return 130
44
+ except BrokenPipeError:
45
+ return 1
46
+ return 0
ransomlive/commands.py ADDED
@@ -0,0 +1,216 @@
1
+ import argparse
2
+ import re
3
+ from pathlib import Path
4
+ from urllib.parse import quote
5
+
6
+ from ransomlive.lookups import hostname, organization
7
+
8
+ FORMATS = ("auto", "table", "json", "markdown")
9
+ DATE_FIELDS = ("discovered", "attacked")
10
+
11
+
12
+ def _validate(pattern: str, message: str, value: str) -> str:
13
+ if not re.fullmatch(pattern, value):
14
+ raise argparse.ArgumentTypeError(message)
15
+ return value
16
+
17
+
18
+ def _country(value: str) -> str:
19
+ return _validate(r"[A-Za-z]{2}", "expected a two-letter ISO country code", value).upper()
20
+
21
+
22
+ def _csirt_country(value: str) -> str:
23
+ return _validate(r"[A-Za-z]{2,3}", "expected a two- or three-letter ISO code", value).upper()
24
+
25
+
26
+ def _year(value: str) -> str:
27
+ return _validate(r"[0-9]{4}", "expected a four-digit year", value)
28
+
29
+
30
+ def _month(value: str) -> str:
31
+ return _validate(r"0[1-9]|1[0-2]", "expected a two-digit month (01-12)", value)
32
+
33
+
34
+ def _segment(value: str) -> str:
35
+ if (
36
+ not value.strip()
37
+ or value in {".", ".."}
38
+ or any(char in "/\\" or not char.isprintable() for char in value)
39
+ ):
40
+ raise argparse.ArgumentTypeError("expected a single non-empty identifier")
41
+ return value
42
+
43
+
44
+ def _victim_id(value: str) -> str:
45
+ return _validate(r"[a-zA-Z0-9+/_-]+={0,2}", "expected a Base64 victim ID", value)
46
+
47
+
48
+ def build_parser(version: str) -> argparse.ArgumentParser:
49
+ shared = argparse.ArgumentParser(add_help=False, argument_default=argparse.SUPPRESS)
50
+ shared.add_argument("--format", choices=FORMATS, help="auto: table on a TTY, otherwise JSON")
51
+ shared.add_argument("--defang", action="store_true", help="defang URL and domain values")
52
+ shared.add_argument("--env-file", type=Path, help="dotenv path (default: .env)")
53
+ shared.add_argument(
54
+ "--insecure",
55
+ action="store_true",
56
+ help="disable TLS certificate verification (exposes your API key to interception)",
57
+ )
58
+
59
+ parser = argparse.ArgumentParser(
60
+ prog="ransomlive",
61
+ description="Read-only Ransomware.live Pro REST threat intelligence.",
62
+ parents=[shared],
63
+ )
64
+ parser.add_argument("--version", action="version", version=f"%(prog)s {version}")
65
+ commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
66
+
67
+ def command(
68
+ name: str,
69
+ path: str,
70
+ help_text: str,
71
+ query: tuple[str, ...] = (),
72
+ segments: tuple[str, ...] = (),
73
+ ) -> argparse.ArgumentParser:
74
+ sub = commands.add_parser(name, parents=[shared], help=help_text, description=help_text)
75
+ sub.set_defaults(path=path, query=query, segments=segments)
76
+ return sub
77
+
78
+ command("validate", "/validate", "Check API key status")
79
+ command("stats", "/stats", "Show API statistics")
80
+ command("sectors", "/listsectors", "List victim industry filters")
81
+ command(
82
+ "csirt", "/csirt", "Find CSIRT contacts by country", segments=("country",)
83
+ ).add_argument("country", type=_csirt_country)
84
+ command("group", "/group", "Show one group (singular route)", segments=("name",)).add_argument(
85
+ "name", type=_segment
86
+ )
87
+ command(
88
+ "groups", "/groups", "List groups or show one by name", segments=("group",)
89
+ ).add_argument("group", nargs="?", type=_segment)
90
+ command("victim", "/victim", "Show one victim by Base64 ID", segments=("id",)).add_argument(
91
+ "id", type=_victim_id
92
+ )
93
+ command(
94
+ "recent-victims", "/victims/recent", "List the 100 latest victims", ("order",)
95
+ ).add_argument("--order", choices=DATE_FIELDS)
96
+
97
+ filters = ("group", "sector", "country")
98
+ victims = command(
99
+ "victims",
100
+ "/victims/",
101
+ "List victims matching at least one filter",
102
+ (*filters, "year", "month", "date"),
103
+ )
104
+ search = command(
105
+ "search", "/victims/search", "Search victim names and websites", ("q", *filters, "order")
106
+ )
107
+ search.add_argument("q", help="case-insensitive substring")
108
+ search.add_argument("--order", choices=DATE_FIELDS)
109
+ for sub in (victims, search):
110
+ sub.add_argument("--group", help="exact ransomware group")
111
+ sub.add_argument("--sector", help="exact industry (see sectors)")
112
+ sub.add_argument("--country", type=_country)
113
+ victims.add_argument("--date", choices=DATE_FIELDS, help="which date to filter on")
114
+
115
+ recent_press = command(
116
+ "recent-press", "/press/recent", "List the 100 latest stories", ("country",)
117
+ )
118
+ press = command(
119
+ "press", "/press/all", "List tracked press coverage", ("year", "month", "country")
120
+ )
121
+ for sub in (recent_press, press):
122
+ sub.add_argument("--country", type=_country)
123
+
124
+ filings = command(
125
+ "8k",
126
+ "/8k",
127
+ "List SEC cybersecurity filings",
128
+ ("ticker", "cik", "year", "month", "item105", "item801"),
129
+ )
130
+ filings.add_argument("--ticker", type=str.upper, help="stock ticker")
131
+ filings.add_argument("--cik", help="SEC CIK (leading zeros are preserved)")
132
+ for flag in ("item105", "item801"):
133
+ filings.add_argument(f"--{flag}", action=argparse.BooleanOptionalAction, default=None)
134
+ for sub in (victims, press, filings):
135
+ sub.add_argument("--year", type=_year, help="four-digit year")
136
+ sub.add_argument("--month", type=_month, help="two-digit month; requires --year")
137
+
138
+ iocs = command(
139
+ "iocs", "/iocs", "List IOC groups or a group's indicators", ("type",), ("group",)
140
+ )
141
+ iocs.add_argument("group", nargs="?", type=_segment)
142
+ iocs.add_argument("--type", help="IOC type, e.g. ip, domain, sha256")
143
+ for name, description, item in (
144
+ ("yara", "List groups or retrieve a group's YARA rules", None),
145
+ ("negotiations", "List negotiation groups, chats, or one transcript", "chat_id"),
146
+ ("ransomnotes", "List ransom note groups, names, or one note", "note_name"),
147
+ ):
148
+ segments = ("group", item) if item else ("group",)
149
+ sub = command(name, f"/{name}", description, segments=segments)
150
+ sub.add_argument("group", nargs="?", type=_segment)
151
+ if item:
152
+ sub.add_argument(
153
+ item, nargs="?", type=_segment, help="identifier returned by group listing"
154
+ )
155
+
156
+ def lookup(name: str, help_text: str) -> argparse.ArgumentParser:
157
+ return commands.add_parser(name, parents=[shared], help=help_text, description=help_text)
158
+
159
+ domain = lookup("lookup-domain", "Find victims by hostname or pasted web URL")
160
+ domain.add_argument("hostname", type=hostname)
161
+ domain.add_argument(
162
+ "--match", choices=("exact", "include"), default="exact", help="default: exact hostname"
163
+ )
164
+ org = lookup("lookup-name", "Find exact and close victim name matches")
165
+ org.add_argument("organization", type=organization)
166
+ org.add_argument("--candidate-query", type=organization, help="override the API search term")
167
+ group_search = lookup("search-groups", "Search group names and aliases")
168
+ group_search.add_argument(
169
+ "query", type=organization, help="full or partial group name or alias"
170
+ )
171
+ for sub in (domain, org):
172
+ sub.add_argument("--country", type=_country)
173
+ sub.add_argument("--group", type=_segment)
174
+ sites = lookup("leak-sites", "Show a group's known leak sites by name or alias")
175
+ sites.add_argument("group", type=_segment)
176
+ reverse = lookup("lookup-leak-site", "Find a leak-site hostname in saved group profiles")
177
+ reverse.add_argument("hostname", type=hostname)
178
+ reverse.add_argument(
179
+ "profiles", type=Path, nargs="+", help="local JSON profiles from leak-sites"
180
+ )
181
+ for sub in (sites, reverse):
182
+ sub.add_argument(
183
+ "--no-defang",
184
+ action="store_false",
185
+ dest="defang",
186
+ default=argparse.SUPPRESS,
187
+ help="show original URL values",
188
+ )
189
+ return parser
190
+
191
+
192
+ def request_for(
193
+ parser: argparse.ArgumentParser, args: argparse.Namespace
194
+ ) -> tuple[str, dict[str, str]]:
195
+ params = {}
196
+ for key in args.query:
197
+ value = getattr(args, key)
198
+ if isinstance(value, bool):
199
+ params[key] = "true" if value else "false"
200
+ elif value is not None:
201
+ if not value.strip():
202
+ parser.error(f"{key} must not be empty")
203
+ params[key] = value
204
+ if "month" in params and "year" not in params:
205
+ parser.error("--month requires --year")
206
+ if args.command == "victims":
207
+ if "year" in params and "month" not in params:
208
+ parser.error("victims requires --month when --year is given")
209
+ if not params.keys() & {"group", "sector", "country", "month"}:
210
+ parser.error("victims requires --group, --sector, --country, or --year with --month")
211
+ path = args.path
212
+ for name in args.segments:
213
+ value = getattr(args, name)
214
+ if value is not None:
215
+ path += "/" + quote(value, safe="")
216
+ return path, params
ransomlive/lookups.py ADDED
@@ -0,0 +1,279 @@
1
+ import argparse
2
+ import json
3
+ import re
4
+ from difflib import SequenceMatcher
5
+ from ipaddress import ip_address
6
+ from pathlib import Path
7
+ from urllib.parse import quote, urlsplit
8
+
9
+ import httpx
10
+ import idna
11
+ from tldextract import TLDExtract
12
+
13
+ from ransomlive.api import APIError, JSONValue, get_json
14
+
15
+ _suffixes = TLDExtract(cache_dir=None, suffix_list_urls=(), include_psl_private_domains=True)
16
+
17
+
18
+ def _host(value: str) -> str:
19
+ value = value.strip().replace("[.]", ".")
20
+ value = re.sub(r"^hxxp(s?)://", r"http\1://", value, flags=re.IGNORECASE)
21
+ if "\\" in value or any(char.isspace() or not char.isprintable() for char in value):
22
+ raise ValueError("invalid hostname")
23
+ parts = urlsplit(value if "://" in value else "//" + value)
24
+ if (
25
+ parts.scheme not in ("", "http", "https")
26
+ or not parts.hostname
27
+ or parts.username is not None
28
+ ):
29
+ raise ValueError("invalid hostname")
30
+ raw = parts.hostname.removesuffix(".")
31
+ try:
32
+ return str(ip_address(raw))
33
+ except ValueError:
34
+ if "." not in raw:
35
+ raise ValueError("expected a fully qualified hostname") from None
36
+ return idna.encode(raw, uts46=True, std3_rules=True).decode("ascii")
37
+
38
+
39
+ def hostname(value: str) -> str:
40
+ try:
41
+ return _host(value)
42
+ except ValueError:
43
+ raise argparse.ArgumentTypeError("expected a hostname or HTTP(S) URL") from None
44
+
45
+
46
+ def words(value: str) -> str:
47
+ return " ".join(re.findall(r"[^\W_]+", value.casefold()))
48
+
49
+
50
+ def organization(value: str) -> str:
51
+ if not words(value):
52
+ raise argparse.ArgumentTypeError("expected a name with letters or digits")
53
+ return value.strip()
54
+
55
+
56
+ def _records(data: JSONValue, collection: str) -> list[dict[str, JSONValue]]:
57
+ if isinstance(data, dict):
58
+ data = data.get(collection, data.get("results"))
59
+ if not isinstance(data, list) or not all(isinstance(row, dict) for row in data):
60
+ raise APIError(f"Unexpected API response: expected a list of {collection}.")
61
+ return [row for row in data if isinstance(row, dict)]
62
+
63
+
64
+ def _text(row: dict[str, JSONValue], *keys: str) -> str | None:
65
+ for key in keys:
66
+ if isinstance(value := row.get(key), str) and value.strip():
67
+ return value.strip()
68
+ return None
69
+
70
+
71
+ def _victim(row: dict[str, JSONValue], match: str) -> dict[str, JSONValue]:
72
+ return {
73
+ "match": match,
74
+ "victim": _text(row, "victim"),
75
+ "group": _text(row, "group"),
76
+ "website": _text(row, "website", "domain"),
77
+ "discovered": _text(row, "discovered"),
78
+ "permalink": _text(row, "permalink"),
79
+ "post_url": _text(row, "claim_url", "post_url"),
80
+ "id": _text(row, "id"),
81
+ }
82
+
83
+
84
+ def _domain_lookup(
85
+ client: httpx.Client, host: str, mode: str, filters: dict[str, str]
86
+ ) -> JSONValue:
87
+ root = _suffixes(host).top_domain_under_public_suffix
88
+ keyword = root if mode == "include" and root else host
89
+ rows = _records(get_json(client, "/victims/search", {"q": keyword, **filters}), "victims")
90
+ matches = []
91
+ for row in rows:
92
+ website = _text(row, "website", "domain")
93
+ if not website:
94
+ continue
95
+ try:
96
+ candidate = _host(website)
97
+ except ValueError:
98
+ continue
99
+ if candidate == host:
100
+ match = "exact"
101
+ elif (
102
+ mode == "include"
103
+ and root
104
+ and _suffixes(candidate).top_domain_under_public_suffix == root
105
+ ):
106
+ if host.endswith("." + candidate):
107
+ match = "parent"
108
+ elif candidate.endswith("." + host):
109
+ match = "subdomain"
110
+ else:
111
+ match = "same-root"
112
+ else:
113
+ continue
114
+ matches.append(_victim(row, match))
115
+ rank = {"exact": 0, "parent": 1, "subdomain": 2, "same-root": 3}
116
+ matches.sort(key=lambda row: rank[str(row["match"])])
117
+ return {"hostname": host, "match_mode": mode, "candidate_query": keyword, "matches": matches}
118
+
119
+
120
+ def _name_lookup(
121
+ client: httpx.Client, name: str, keyword: str | None, filters: dict[str, str]
122
+ ) -> JSONValue:
123
+ normalized = words(name)
124
+ keyword = keyword or max(normalized.split(), key=len)[:5]
125
+ rows = _records(get_json(client, "/victims/search", {"q": keyword, **filters}), "victims")
126
+ matches = []
127
+ for row in rows:
128
+ candidate = words(_text(row, "victim") or "")
129
+ score = SequenceMatcher(None, normalized, candidate, autojunk=False).ratio()
130
+ if candidate and (score >= 0.75 or f" {normalized} " in f" {candidate} "):
131
+ matches.append((score, _victim(row, "exact" if candidate == normalized else "close")))
132
+ matches.sort(key=lambda item: item[0], reverse=True)
133
+ return {
134
+ "organization": name,
135
+ "candidate_query": keyword,
136
+ "matches": [row for _, row in matches],
137
+ }
138
+
139
+
140
+ def _aliases(row: dict[str, JSONValue]) -> list[str]:
141
+ aliases = row.get("altname")
142
+ if isinstance(aliases, str):
143
+ aliases = [aliases, *re.split(r"[,;|]", aliases)]
144
+ if not isinstance(aliases, list):
145
+ return []
146
+ return [alias.strip() for alias in aliases if isinstance(alias, str) and alias.strip()]
147
+
148
+
149
+ def _search_groups(client: httpx.Client, query: str) -> JSONValue:
150
+ rows = _records(get_json(client, "/groups", {}), "groups")
151
+ search = query.casefold()
152
+ matches = []
153
+ for row in rows:
154
+ name = _text(row, "group")
155
+ if not name:
156
+ continue
157
+ candidates = [name, *_aliases(row)]
158
+ scored = []
159
+ for candidate in candidates:
160
+ normalized = candidate.casefold()
161
+ score = SequenceMatcher(None, search, normalized, autojunk=False).ratio()
162
+ if normalized == search:
163
+ kind = "exact"
164
+ elif search in normalized:
165
+ kind = "partial"
166
+ elif len(search) >= 4 and score >= 0.75:
167
+ kind = "close"
168
+ else:
169
+ continue
170
+ scored.append(({"exact": 0, "partial": 1, "close": 2}[kind], -score, candidate, kind))
171
+ if scored:
172
+ rank, score, matched_name, kind = min(scored)
173
+ matches.append(
174
+ (
175
+ rank,
176
+ score,
177
+ name.casefold(),
178
+ {
179
+ "group": name,
180
+ "altname": row.get("altname"),
181
+ "victims": row.get("victims"),
182
+ "match": kind,
183
+ "matched_name": matched_name,
184
+ },
185
+ )
186
+ )
187
+ matches.sort(key=lambda item: item[:3])
188
+ return {"query": query, "matches": [row for _, _, _, row in matches]}
189
+
190
+
191
+ def _group_name(client: httpx.Client, query: str) -> str:
192
+ rows = _records(get_json(client, "/groups", {}), "groups")
193
+ names = {name.casefold(): name for row in rows if (name := _text(row, "group"))}
194
+ if query.casefold() in names:
195
+ return names[query.casefold()]
196
+ matches = set()
197
+ for row in rows:
198
+ if (name := _text(row, "group")) and any(
199
+ alias.casefold() == query.casefold() for alias in _aliases(row)
200
+ ):
201
+ matches.add(name)
202
+ if len(matches) > 1:
203
+ raise APIError("Group alias is ambiguous; use a canonical name from `ransomlive groups`.")
204
+ if not matches:
205
+ raise APIError("No matching group name or alias.")
206
+ return matches.pop()
207
+
208
+
209
+ def _profile(data: JSONValue, fallback: str | None = None) -> tuple[str, list[JSONValue]]:
210
+ if isinstance(data, dict) and isinstance(data.get("group"), dict):
211
+ data = data["group"]
212
+ if isinstance(data, dict) and isinstance(locations := data.get("locations"), list):
213
+ name = fallback or _text(data, "group", "name")
214
+ if name:
215
+ return name, locations
216
+ raise APIError("Expected group profile data with a name and a locations list.")
217
+
218
+
219
+ def _location_url(location: JSONValue) -> str | None:
220
+ values = (
221
+ [_text(location, key) for key in ("url", "slug", "fqdn")]
222
+ if isinstance(location, dict)
223
+ else [location]
224
+ )
225
+ for value in values:
226
+ if isinstance(value, str):
227
+ try:
228
+ _host(value)
229
+ except ValueError:
230
+ continue
231
+ return value
232
+ return None
233
+
234
+
235
+ def reverse_lookup(host: str, profiles: list[Path]) -> JSONValue:
236
+ matches: list[JSONValue] = []
237
+ seen = set()
238
+ for path in profiles:
239
+ try:
240
+ document = json.loads(path.read_text(encoding="utf-8-sig"))
241
+ except (OSError, UnicodeError, ValueError):
242
+ raise APIError(f"Could not read group profile: {str(path)!r}.", exit_code=2) from None
243
+ try:
244
+ name, locations = _profile(document.get("data") if isinstance(document, dict) else None)
245
+ except APIError as error:
246
+ raise APIError(f"{str(path)!r}: {error}", exit_code=2) from None
247
+ for location in locations:
248
+ url = _location_url(location)
249
+ if not url:
250
+ continue
251
+ try:
252
+ matches_host = _host(url) == host
253
+ except ValueError:
254
+ continue
255
+ key = (name.casefold(), url)
256
+ if matches_host and key not in seen:
257
+ seen.add(key)
258
+ matches.append({"group": name, "url": url})
259
+ return {"hostname": host, "profiles_checked": len(profiles), "matches": matches}
260
+
261
+
262
+ def execute_lookup(client: httpx.Client, args: argparse.Namespace) -> JSONValue:
263
+ if args.command == "search-groups":
264
+ return _search_groups(client, args.query)
265
+ if args.command == "leak-sites":
266
+ name = _group_name(client, args.group)
267
+ if name in {".", ".."} or any(char in "/\\" or not char.isprintable() for char in name):
268
+ raise APIError("The API returned an invalid group identifier.")
269
+ name, locations = _profile(get_json(client, "/groups/" + quote(name, safe=""), {}), name)
270
+ sites: list[JSONValue] = []
271
+ for location in locations:
272
+ if url := _location_url(location):
273
+ attributes = location if isinstance(location, dict) else {}
274
+ sites.append({**attributes, "url": url})
275
+ return {"group": name, "locations": sites}
276
+ filters = {name: value for name in ("country", "group") if (value := getattr(args, name))}
277
+ if args.command == "lookup-domain":
278
+ return _domain_lookup(client, args.hostname, args.match, filters)
279
+ return _name_lookup(client, args.organization, args.candidate_query, filters)
ransomlive/output.py ADDED
@@ -0,0 +1,146 @@
1
+ import html
2
+ import json
3
+ import re
4
+ from collections.abc import Iterator
5
+ from itertools import islice
6
+ from typing import TextIO
7
+
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+ from rich.text import Text
11
+
12
+ from ransomlive.api import JSONValue
13
+
14
+ SOURCE = "https://ransomware.live"
15
+ _URL = re.compile(r"(?i)\b(https?|ftp|wss?)://([^\s/<>\"'?#]+)")
16
+ _DOMAIN = re.compile(r"(?i)\b(?:[a-z0-9-]+\.)+[a-z0-9-]+\b")
17
+ _AUTOLINK = re.compile(
18
+ r"(?i)(?:\b[a-z][a-z0-9+.-]*://|"
19
+ r"\b(?:[\w-]+\.)+(?:[^\W\d_][\w-]+|xn--[\w-]+)\b|"
20
+ r"[\w.+-]+@[\w.-]+)"
21
+ )
22
+ _MARKDOWN = re.compile(r"([\\`*_{}\[\]!~|])")
23
+ _SCHEME = {"http": "hxxp", "https": "hxxps", "ftp": "fxp", "ws": "wxs", "wss": "wxss"}
24
+ _DOMAIN_FIELDS = {
25
+ "domain",
26
+ "domains",
27
+ "website",
28
+ "host",
29
+ "hostname",
30
+ "url",
31
+ "urls",
32
+ "onion",
33
+ "locations",
34
+ "fqdn",
35
+ "slug",
36
+ "post_url",
37
+ }
38
+ _MAX_ROWS = 100
39
+ _MAX_CELL = 180
40
+ _PREFERRED = ("victim", "group", "name", "country", "activity", "date", "discovered", "title", "id")
41
+
42
+
43
+ def defang(data: JSONValue, field: str = "") -> JSONValue:
44
+ if isinstance(data, dict):
45
+ return {key: defang(value, key.lower()) for key, value in data.items()}
46
+ if isinstance(data, list):
47
+ return [defang(value, field) for value in data]
48
+ if isinstance(data, str):
49
+ text = _URL.sub(
50
+ lambda match: _SCHEME[match[1].lower()] + "://" + match[2].replace(".", "[.]"),
51
+ data,
52
+ )
53
+ return (
54
+ _DOMAIN.sub(lambda match: match[0].replace(".", "[.]"), text)
55
+ if (field in _DOMAIN_FIELDS)
56
+ else text
57
+ )
58
+ return data
59
+
60
+
61
+ def _cell(value: JSONValue) -> str:
62
+ if not isinstance(value, str):
63
+ value = json.dumps(value, ensure_ascii=False, separators=(", ", ": "))
64
+ value = "".join(
65
+ char if char.isprintable() else ascii(char)[1:-1] for char in value[: _MAX_CELL + 1]
66
+ )
67
+ return value if len(value) <= _MAX_CELL else value[:_MAX_CELL] + "..."
68
+
69
+
70
+ def _preview(
71
+ data: JSONValue,
72
+ ) -> tuple[list[str], Iterator[list[JSONValue]], str]:
73
+ if isinstance(data, dict):
74
+ collections = [(key, value) for key, value in data.items() if isinstance(value, list)]
75
+ if len(collections) == 1:
76
+ key, value = collections[0]
77
+ columns, rows, _ = _preview(value)
78
+ title = f"{_cell(key)} ({len(value)} entries)"
79
+ if key == "matches" and isinstance(count := data.get("profiles_checked"), int):
80
+ title += f" across {count} local profiles"
81
+ if key == "locations" and isinstance(group := data.get("group"), str):
82
+ title = f"{_cell(group)}: {title}"
83
+ return columns, rows, title
84
+ return ["Field", "Value"], ([key, value] for key, value in data.items()), "Response"
85
+ if isinstance(data, list):
86
+ records = [row for row in data if isinstance(row, dict)]
87
+ if data and len(records) == len(data):
88
+ keys = dict.fromkeys(key for row in records for key in row)
89
+ if keys:
90
+ order = (
91
+ ("match", "victim", "group", "website", "discovered", "permalink", "post_url")
92
+ if "match" in keys and "permalink" in keys
93
+ else ("group", "match", "matched_name", "altname", "victims")
94
+ if "matched_name" in keys
95
+ else (*_PREFERRED, "url", "title", "available", "enabled", "type")
96
+ )
97
+ preferred = [key for key in order if key in keys]
98
+ columns = (preferred + [key for key in keys if key not in preferred])[:7]
99
+ return columns, ([row.get(key) for key in columns] for row in records), "Results"
100
+ return ["Value"], ([item] for item in data), "Results"
101
+ return ["Value"], iter([[data]]), "Response"
102
+
103
+
104
+ def _markdown_cell(text: str) -> str:
105
+ escaped = html.escape(text, quote=False)
106
+ if _AUTOLINK.search(text):
107
+ escaped = escaped.translate({ord(char): f"&#{ord(char)};" for char in "\\`*_[]!~|:."})
108
+ return f"<code>{escaped}</code>"
109
+ escaped = _MARKDOWN.sub(r"\\\1", escaped)
110
+ escaped = re.sub(r"^(\s*)(#{1,6}|[-+])(?=\s)", r"\1\\\2", escaped)
111
+ return re.sub(r"^(\s*\d+)([.)])(?=\s)", r"\1\\\2", escaped)
112
+
113
+
114
+ def render(data: JSONValue, output: TextIO, fmt: str, *, defanged: bool = False) -> None:
115
+ if defanged:
116
+ data = defang(data)
117
+ if fmt == "auto":
118
+ fmt = "table" if output.isatty() else "json"
119
+ if fmt == "json":
120
+ print(
121
+ json.dumps({"source": SOURCE, "data": data}, ensure_ascii=True, indent=2), file=output
122
+ )
123
+ return
124
+ columns, rows, title = _preview(data)
125
+ labels = [_cell(column) for column in columns]
126
+ cells = [[_cell(value) for value in row] for row in islice(rows, _MAX_ROWS)]
127
+ limit_hint = "Preview: up to 100 rows; use --format json for all fields and rows."
128
+ if fmt == "markdown":
129
+ print(f"Source: [Ransomware.live]({SOURCE})\n\n{limit_hint}\n", file=output)
130
+ if isinstance(data, dict) and any(
131
+ isinstance(data.get(key), list) for key in ("matches", "locations")
132
+ ):
133
+ print(f"{_markdown_cell(title)}\n", file=output)
134
+ print("| " + " | ".join(map(_markdown_cell, labels)) + " |", file=output)
135
+ print("| " + " | ".join("---" for _ in labels) + " |", file=output)
136
+ for row in cells:
137
+ print("| " + " | ".join(map(_markdown_cell, row)) + " |", file=output)
138
+ else:
139
+ console = Console(file=output, markup=False, highlight=False)
140
+ table = Table(title=Text(title), show_lines=True)
141
+ for label in labels:
142
+ table.add_column(Text(label))
143
+ for row in cells:
144
+ table.add_row(*(Text(value) for value in row))
145
+ console.print(table)
146
+ console.print(f"Source: Ransomware.live ({SOURCE})\n{limit_hint}")
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.5
2
+ Name: ransomlive-cli
3
+ Version: 0.0.1
4
+ Summary: A human- and machine-friendly CLI for the Ransomware.live Pro REST API
5
+ Project-URL: Repository, https://github.com/stanfrbd/ransomlive-cli
6
+ Project-URL: Documentation, https://api-pro.ransomware.live/docs
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.11
10
+ Requires-Dist: httpx<1,>=0.28
11
+ Requires-Dist: idna<4,>=3
12
+ Requires-Dist: python-dotenv<2,>=1.1
13
+ Requires-Dist: rich<16,>=14
14
+ Requires-Dist: tldextract<6,>=5.1
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ransomlive-cli
18
+
19
+ A Python 3.11+ CLI for the [Ransomware.Live Pro REST API](https://api-pro.ransomware.live/docs).
20
+ Source: [Ransomware.Live](https://ransomware.live), created by [**Julien MOUSQUETON**](https://github.com/JMousqueton).
21
+ Victim listings are intelligence leads, not confirmation of incidents.
22
+
23
+ ## Install
24
+
25
+ Install from PyPI in an activated Python virtual environment:
26
+
27
+ ```sh
28
+ pip install ransomlive-cli
29
+ ```
30
+
31
+ Or install the `ransomlive` command with [uv](https://docs.astral.sh/uv/):
32
+
33
+ ```sh
34
+ uv tool install ransomlive-cli
35
+ ```
36
+
37
+ To run without installing globally:
38
+
39
+ ```sh
40
+ uvx --from ransomlive-cli ransomlive --help
41
+ ```
42
+
43
+ To install from GitHub or a local checkout instead:
44
+
45
+ ```sh
46
+ uv tool install git+https://github.com/stanfrbd/ransomlive-cli
47
+ pip install git+https://github.com/stanfrbd/ransomlive-cli
48
+ # From a local checkout:
49
+ pip install -e .
50
+ ```
51
+
52
+ ## Authentication
53
+
54
+ Get a personal Pro API key at [my.ransomware.live](https://my.ransomware.live/).
55
+ Set `RANSOMWARE_LIVE_TOKEN` in your environment or copy [.env.example](.env.example) to
56
+ `.env` in the directory where you run the CLI. The environment takes precedence.
57
+ `--env-file PATH` selects a different dotenv file. Keep the key out of Git and shell history.
58
+
59
+ ```sh
60
+ ransomlive validate
61
+ ransomlive --help
62
+ ransomlive victims --help
63
+ ```
64
+
65
+ The client sends `X-API-KEY` only to `https://api-pro.ransomware.live`, verifies TLS
66
+ by default, and does not use environment proxies or follow redirects. It never fetches artifacts,
67
+ screenshots, actor infrastructure, or other links returned in a response.
68
+ If a TLS-inspecting proxy prevents certificate verification, run from a network where
69
+ the Pro API's public certificate validates directly.
70
+
71
+ As an explicit, per-command last resort, `ransomlive --insecure validate` disables TLS
72
+ certificate verification and prints a warning to stderr. **This allows an attacker or
73
+ intermediary to impersonate the API and read or change your API key and data.** Do not
74
+ use it on untrusted networks. It does not configure a proxy or bypass network restrictions.
75
+
76
+ ## Commands
77
+
78
+ | What you need | Command |
79
+ | --- | --- |
80
+ | Key status and statistics | `validate`, `stats` |
81
+ | Victim filters | `sectors`, `victims --country FR --year 2025 --month 06` |
82
+ | Victim search and recent activity | `search hospital --country US`, `recent-victims --order attacked` |
83
+ | One victim | `victim ID` (use an `id` from a listing) |
84
+ | Groups and profiles | `search-groups lock`, `groups`, `groups lockbit3` |
85
+ | Detection data | `iocs [GROUP] --type ip`, `yara [GROUP]` |
86
+ | Negotiations and ransom notes | `negotiations [GROUP [CHAT_ID]]`, `ransomnotes [GROUP [NOTE_NAME]]` |
87
+ | Press and SEC filings | `recent-press --country FR`, `press --year 2025`, `8k --year 2025 --no-item801` |
88
+ | CSIRT contacts | `csirt FR` or `csirt FRA` |
89
+
90
+ This covers the GET routes listed in the [Pro REST Swagger reference](https://api-pro.ransomware.live/swagger.json).
91
+ TAXII/STIX is a separate API and is not included.
92
+
93
+ ## Analyst workflows
94
+
95
+ **Is this domain linked to a victim?** Paste a hostname or web URL. The CLI normalizes
96
+ the hostname and does not send the URL path, query, or fragment to the API.
97
+
98
+ ```sh
99
+ ransomlive lookup-domain 'https://login.example.org/account' --match exact
100
+ ransomlive lookup-domain login.example.org --match include --country US --format json
101
+ ```
102
+
103
+ `exact` (the default) matches only the normalized hostname. `include` searches the
104
+ registrable domain and labels exact, parent, subdomain, and same-root sibling matches.
105
+ It uses a bundled public suffix list (including private suffixes), without a network
106
+ fetch. Both modes filter the candidates returned by Pro substring search; no match
107
+ does not prove a domain was never listed. Use `--defang` to show the values as text.
108
+
109
+ **Find a victim by organization name.**
110
+
111
+ ```sh
112
+ ransomlive lookup-name 'Example Health' --country US
113
+ ransomlive lookup-name 'Exampel Health' --candidate-query health --format json
114
+ ```
115
+
116
+ Exact matches ignore case and punctuation. Close matches are ranked only among
117
+ candidates from a Pro substring query. By default the query uses the first five
118
+ characters of the longest word; change it with `--candidate-query` if needed.
119
+ Domain and name results show the Ransomware.live `permalink` and a separate `post_url`
120
+ when the API supplies an explicit claim or post link. A `null` link means unavailable;
121
+ the CLI does not guess. Use a returned `id` with `ransomlive victim ID --format json`
122
+ for the full victim record.
123
+
124
+ **Find a group's leak sites or check a known site.**
125
+
126
+ ```sh
127
+ ransomlive search-groups lock
128
+ ransomlive leak-sites lockbit3 --format table
129
+ mkdir -p .ransomlive
130
+ ransomlive leak-sites lockbit3 --format json > .ransomlive/group.json
131
+ ransomlive lookup-leak-site 'hxxp://example[.]onion/path' .ransomlive/group.json
132
+ ```
133
+
134
+ `search-groups` searches the group list by case-insensitive name or alias, including
135
+ partial names and close spelling matches (for queries of at least four characters).
136
+ Results are labeled `exact`, `partial`, or `close`, and show the canonical group name
137
+ and matched name. Close matches are suggestions, not confirmed identities. Use the
138
+ canonical group name from the results with `leak-sites`, which also recognizes exact
139
+ alternative names exposed by `/groups`.
140
+ Both leak-site commands defang by default; `--no-defang` displays the original values.
141
+ Reverse lookup compares exact hostnames in the supplied local profile files and
142
+ reports how many were checked. It does not use a key, call the API, or contact the
143
+ sites. Pass more files to broaden coverage. Keep the saved JSON private; `.ransomlive/`
144
+ is ignored by Git.
145
+
146
+ ## Output
147
+
148
+ ```sh
149
+ ransomlive recent-victims
150
+ ransomlive groups lockbit3 --format markdown --defang
151
+ ransomlive search hospital --format json --defang
152
+ ```
153
+
154
+ - **Auto (default):** rich table on a terminal; JSON when redirected or piped.
155
+ - **Table and Markdown:** previews, with at most 100 rows and shortened long cells.
156
+ Markdown escapes untrusted content; cells containing links use inline code to prevent
157
+ automatic clickable links.
158
+ - **JSON:** one document on stdout, shaped as `{"source":"https://ransomware.live","data":...}`.
159
+ REST commands return the complete API payload; analyst workflow commands return
160
+ their selected matches or locations, without a display row limit.
161
+ - **`--defang`:** converts recognized URL schemes such as `https` to `hxxps` and dots in
162
+ their hosts to `[.]`; it also defangs bare domains in recognized domain fields.
163
+ This changes string values, not keys. Treat all API data as untrusted even when defanged.
164
+
165
+ Errors go to stderr. Exit status: `0` success, `1` request/output failure,
166
+ `2` usage or configuration error, `3` rate limit, `130` interrupted.
167
+
168
+ ## Responsible use
169
+
170
+ Follow the [Ransomware.live terms](https://www.ransomware.live/t&c). Output is for local
171
+ analysis: do not publish raw data, re-serve it, or use it commercially without written
172
+ approval. Cite [Ransomware.live](https://ransomware.live) when using its intelligence.
173
+ The Pro API documents 60 requests per minute and 500,000 per month per key, with a
174
+ fair-use exception for IOC endpoints. Do not poll more often than the service's
175
+ 30-minute cache interval. REST, group search, and victim lookup commands issue one request each;
176
+ `leak-sites` issues at most two and `lookup-leak-site` is offline. The CLI does not
177
+ retry on HTTP 429; respect any displayed `Retry-After` delay.
178
+
179
+ ## Development
180
+
181
+ ```sh
182
+ uv sync --locked --python 3.11
183
+ uv run pre-commit install
184
+ uv run pytest
185
+ uv run ransomlive --help
186
+ ```
187
+
188
+ Push and pull request CI runs on Ubuntu, with Ruff and the shared Cyberbro pre-commit
189
+ configuration (including Bandit), offline HTTP mocks, and a wheel installation check.
190
+ With your own key, run the opt-in live smoke suite sparingly:
191
+
192
+ ```sh
193
+ uv run python scripts/smoke_live.py
194
+ ```
195
+
196
+ It attempts each documented GET route once, uses returned identifiers for dependent
197
+ checks, prints only pass/fail/skip labels, and stops on rate limiting. It is not run in CI.
198
+
199
+ A huge thank you to [**Julien MOUSQUETON**](https://github.com/JMousqueton) for developing Ransomware.Live for free.
200
+
201
+ The CLI code is [MIT licensed](LICENSE); that license does not apply to third-party API data.
@@ -0,0 +1,12 @@
1
+ ransomlive/__init__.py,sha256=iHLr-sLKLK5TZP1rvNhuZnA39QGa09Lm9pdMehdYTF4,64
2
+ ransomlive/__main__.py,sha256=aCKkHu7N5Agln04aC_FOM-3G7Y2ErB1gGe2vNYWv8pI,58
3
+ ransomlive/api.py,sha256=e8rDr4r1jBtDzN3O-AxyrKMvhqb3soFC9zfiWaA-50Q,3435
4
+ ransomlive/cli.py,sha256=3t2m6h1gHtcGP5WWXMZlsWzBm4MqXxgSArg2pEJRPRY,1814
5
+ ransomlive/commands.py,sha256=SL0XOJO-8nb8tDHA3GIzFiusPaeM6Huh-4lMvgd7XJg,8873
6
+ ransomlive/lookups.py,sha256=f9AtklM6WHV-63_eWLHwghsILtbj3O0q10OY6DpLn0E,10532
7
+ ransomlive/output.py,sha256=-kr8E3PyEh06CFDA693ZA-EUEdx343OGb82pcHZf8YI,5850
8
+ ransomlive_cli-0.0.1.dist-info/METADATA,sha256=hsp-QzkRjoA77DYS7zl9MPpaAmjlIIeolJELy1yxQK4,8697
9
+ ransomlive_cli-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ ransomlive_cli-0.0.1.dist-info/entry_points.txt,sha256=e88apFOks5lun7whxKm-6V_9hOCdNAm1bVSipMkOwEU,51
11
+ ransomlive_cli-0.0.1.dist-info/licenses/LICENSE,sha256=VIAZzfkZH4n4m3lU4sz_rYRersJe-RJsDY3H-FEagpU,1086
12
+ ransomlive_cli-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ransomlive = ransomlive.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 stanfrbd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included
13
+ in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.