rangus 0.5.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.
rangus/core/keys.py ADDED
@@ -0,0 +1,182 @@
1
+ """
2
+ Optional API keys for paid / registered sources.
3
+
4
+ A key is looked up, in order, from:
5
+ 1. the environment variable RANGUS_<SERVICE>_KEY (e.g. RANGUS_VIRUSTOTAL_KEY)
6
+ 2. the `[keys]` table of a monitor config (while that config is running)
7
+ 3. the OS credential store via `keyring` (Windows Credential Manager,
8
+ macOS Keychain, Secret Service on Linux), set with `rangus keys set`
9
+
10
+ Keys are never accepted as command-line arguments (they'd end up in shell
11
+ history and process listings) and are never printed except masked.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from collections.abc import Iterator, Mapping
18
+ from contextlib import contextmanager
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+ KEYRING_SERVICE = "rangus"
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Service:
27
+ name: str
28
+ label: str
29
+ used_for: str
30
+ signup_url: str
31
+
32
+ @property
33
+ def env_var(self) -> str:
34
+ return f"RANGUS_{self.name.upper()}_KEY"
35
+
36
+
37
+ SERVICES: dict[str, Service] = {
38
+ s.name: s
39
+ for s in (
40
+ Service("virustotal", "VirusTotal", "subdomains", "https://www.virustotal.com/gui/my-apikey"),
41
+ Service("securitytrails", "SecurityTrails", "subdomains", "https://securitytrails.com/app/account/credentials"),
42
+ Service("chaos", "ProjectDiscovery Chaos", "subdomains", "https://cloud.projectdiscovery.io/"),
43
+ Service("otx", "AlienVault OTX", "subdomains", "https://otx.alienvault.com/api"),
44
+ Service("urlscan", "urlscan.io", "subdomains (higher rate limits)", "https://urlscan.io/user/profile/"),
45
+ Service("hunter", "Hunter.io", "emails", "https://hunter.io/api-keys"),
46
+ )
47
+ }
48
+
49
+
50
+ class KeyStoreError(RuntimeError):
51
+ """The OS credential store is unavailable or refused the operation."""
52
+
53
+
54
+ # Keys from a monitor config's [keys] table, active only while it runs.
55
+ _config_keys: dict[str, str] = {}
56
+
57
+ # Keyring answers (hits and misses) for this process. Each OS credential store
58
+ # read can take tens of milliseconds and a run asks for the same keys several
59
+ # times, so read each service once; set_key/delete_key refresh the entry.
60
+ _keyring_cache: dict[str, str | None] = {}
61
+
62
+
63
+ def clear_cache() -> None:
64
+ """Forget cached keyring answers (e.g. after the store changed outside rangus)."""
65
+ _keyring_cache.clear()
66
+
67
+
68
+ def _service(name: str) -> Service:
69
+ try:
70
+ return SERVICES[name]
71
+ except KeyError:
72
+ raise ValueError(
73
+ f"unknown service {name!r} (choose from {', '.join(SERVICES)})"
74
+ ) from None
75
+
76
+
77
+ def _keyring() -> Any:
78
+ """The keyring module, imported lazily (it's slow to import)."""
79
+ try:
80
+ import keyring
81
+ except ImportError as exc: # pragma: no cover - keyring is a dependency
82
+ raise KeyStoreError("the 'keyring' package is not installed") from exc
83
+ return keyring
84
+
85
+
86
+ def _from_keyring(name: str) -> str | None:
87
+ if name in _keyring_cache:
88
+ return _keyring_cache[name]
89
+ try:
90
+ value = _keyring().get_password(KEYRING_SERVICE, name) or None
91
+ except Exception: # no backend (e.g. headless Linux), locked store, ...
92
+ value = None
93
+ _keyring_cache[name] = value
94
+ return value
95
+
96
+
97
+ def lookup(name: str) -> tuple[str | None, str]:
98
+ """(key, where it came from) – where is "env", "config", "keyring" or ""."""
99
+ service = _service(name)
100
+ if env_value := os.environ.get(service.env_var, "").strip():
101
+ return env_value, "env"
102
+ if config_value := _config_keys.get(name, ""):
103
+ return config_value, "config"
104
+ if stored := _from_keyring(name):
105
+ return stored, "keyring"
106
+ return None, ""
107
+
108
+
109
+ def get_key(name: str) -> str | None:
110
+ """The API key for `name`, or None if it isn't configured anywhere."""
111
+ return lookup(name)[0]
112
+
113
+
114
+ def set_key(name: str, value: str) -> None:
115
+ """Store a key in the OS credential store."""
116
+ _service(name)
117
+ value = value.strip()
118
+ if not value:
119
+ raise ValueError("empty key")
120
+ _keyring_cache.pop(name, None)
121
+ try:
122
+ _keyring().set_password(KEYRING_SERVICE, name, value)
123
+ except KeyStoreError:
124
+ raise
125
+ except Exception as exc:
126
+ raise KeyStoreError(f"could not save to the OS credential store: {exc}") from exc
127
+ _keyring_cache[name] = value
128
+
129
+
130
+ def delete_key(name: str) -> bool:
131
+ """Remove a key from the OS credential store. Returns False if none was stored."""
132
+ _service(name)
133
+ if _from_keyring(name) is None:
134
+ return False
135
+ _keyring_cache.pop(name, None)
136
+ try:
137
+ _keyring().delete_password(KEYRING_SERVICE, name)
138
+ except Exception as exc:
139
+ raise KeyStoreError(f"could not delete from the OS credential store: {exc}") from exc
140
+ _keyring_cache[name] = None
141
+ return True
142
+
143
+
144
+ def mask(value: str) -> str:
145
+ """Show only enough of a key to tell keys apart."""
146
+ return "••••" + value[-4:] if len(value) > 8 else "••••"
147
+
148
+
149
+ def resolve_config_keys(table: Mapping[str, Any]) -> dict[str, str]:
150
+ """
151
+ Validate a config [keys] table. A value is either "env:VARIABLE" (read
152
+ from that environment variable when the config is loaded) or the key
153
+ itself (plain text in the file – prefer `rangus keys set`).
154
+ Raises ValueError for unknown services or bad values.
155
+ """
156
+ resolved: dict[str, str] = {}
157
+ for name, raw in table.items():
158
+ _service(name)
159
+ if not isinstance(raw, str) or not raw.strip():
160
+ raise ValueError(f"key for {name} must be a non-empty string")
161
+ raw = raw.strip()
162
+ if raw.startswith("env:"):
163
+ var = raw[4:].strip()
164
+ value = os.environ.get(var, "").strip()
165
+ if not value:
166
+ raise ValueError(f"key for {name}: environment variable {var} is not set")
167
+ resolved[name] = value
168
+ else:
169
+ resolved[name] = raw
170
+ return resolved
171
+
172
+
173
+ @contextmanager
174
+ def config_keys(keys: Mapping[str, str]) -> Iterator[None]:
175
+ """Make a config's keys available to sources for the duration of a run."""
176
+ saved = dict(_config_keys)
177
+ _config_keys.update(keys)
178
+ try:
179
+ yield
180
+ finally:
181
+ _config_keys.clear()
182
+ _config_keys.update(saved)
rangus/core/models.py ADDED
@@ -0,0 +1,32 @@
1
+ """Shared data models for rangus results."""
2
+
3
+ from datetime import UTC, datetime
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ def _utcnow() -> datetime:
9
+ return datetime.now(UTC)
10
+
11
+
12
+ class EmailResult(BaseModel):
13
+ email: str
14
+ source: str = Field(..., description="Where this email was found (e.g. google_dork)")
15
+ dork: str | None = None
16
+ url: str | None = None
17
+ first_seen: datetime = Field(default_factory=_utcnow)
18
+
19
+
20
+ class SubdomainResult(BaseModel):
21
+ subdomain: str
22
+ source: str = Field(..., description="Data source (e.g. crt.sh)")
23
+ first_seen: datetime | None = None
24
+ last_seen: datetime | None = None
25
+
26
+
27
+ class ReconReport(BaseModel):
28
+ target: str
29
+ generated_at: datetime = Field(default_factory=_utcnow)
30
+ emails: list[EmailResult] = []
31
+ subdomains: list[SubdomainResult] = []
32
+ notes: list[str] = []
@@ -0,0 +1,3 @@
1
+ from . import emails, recon, subdomains
2
+
3
+ __all__ = ["emails", "recon", "subdomains"]