inspectra-cli 2.0.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.
@@ -0,0 +1,145 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Inspectra Report — {{ result.target.input }}</title>
7
+ <style>
8
+ :root {
9
+ --bg: #0f172a;
10
+ --panel: #1e293b;
11
+ --text: #e2e8f0;
12
+ --muted: #94a3b8;
13
+ --border: #334155;
14
+ --high: #ef4444;
15
+ --medium: #f59e0b;
16
+ --low: #eab308;
17
+ --info: #38bdf8;
18
+ --good: #22c55e;
19
+ --warn: #f59e0b;
20
+ --bad: #ef4444;
21
+ }
22
+ * { box-sizing: border-box; }
23
+ body {
24
+ margin: 0;
25
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
26
+ background: var(--bg);
27
+ color: var(--text);
28
+ line-height: 1.55;
29
+ }
30
+ .wrap { max-width: 860px; margin: 0 auto; padding: 2rem 1.25rem; }
31
+ header h1 { font-size: 1.6rem; margin: 0 0 .25rem; }
32
+ header h1 span { color: var(--muted); font-weight: 400; }
33
+ .meta { color: var(--muted); font-size: .9rem; margin: .25rem 0 1.5rem; }
34
+ .meta code { background: var(--panel); padding: .1rem .35rem; border-radius: 4px; }
35
+
36
+ .score-card {
37
+ display: flex; gap: 1.25rem; align-items: center;
38
+ background: var(--panel); border: 1px solid var(--border);
39
+ border-radius: 12px; padding: 1.25rem 1.5rem; margin-bottom: 1.5rem;
40
+ }
41
+ .score { font-size: 2.4rem; font-weight: 700; }
42
+ .score small { color: var(--muted); }
43
+ .grade {
44
+ font-size: 2rem; font-weight: 800; min-width: 3.5rem; text-align: center;
45
+ border: 2px solid; border-radius: 10px; padding: .15rem .6rem;
46
+ }
47
+ .grade.good { color: var(--good); border-color: var(--good); }
48
+ .grade.warn { color: var(--warn); border-color: var(--warn); }
49
+ .grade.bad { color: var(--bad); border-color: var(--bad); }
50
+ .summary { display: flex; gap: .75rem; flex-wrap: wrap; }
51
+ .summary .chip {
52
+ background: var(--panel); border: 1px solid var(--border);
53
+ border-radius: 999px; padding: .3rem .75rem; font-size: .85rem;
54
+ }
55
+ .sev-high { color: var(--high); }
56
+ .sev-medium { color: var(--medium); }
57
+ .sev-low { color: var(--low); }
58
+ .sev-info { color: var(--info); }
59
+
60
+ h2 { font-size: 1.15rem; margin: 1.75rem 0 .75rem; }
61
+ .finding {
62
+ background: var(--panel); border: 1px solid var(--border);
63
+ border-left: 4px solid var(--border);
64
+ border-radius: 10px; padding: 1rem 1.25rem; margin-bottom: 1rem;
65
+ }
66
+ .finding.sev-high { border-left-color: var(--high); }
67
+ .finding.sev-medium { border-left-color: var(--medium); }
68
+ .finding.sev-low { border-left-color: var(--low); }
69
+ .finding.sev-info { border-left-color: var(--info); }
70
+ .finding h3 { margin: 0 0 .6rem; font-size: 1rem; }
71
+ .badge {
72
+ display: inline-block; font-size: .7rem; font-weight: 700;
73
+ background: var(--panel); border: 1px solid currentColor;
74
+ border-radius: 6px; padding: .1rem .45rem; color: var(--text);
75
+ }
76
+ .finding.sev-high .badge { color: var(--high); }
77
+ .finding.sev-medium .badge { color: var(--medium); }
78
+ .finding.sev-low .badge { color: var(--low); }
79
+ .finding.sev-info .badge { color: var(--info); }
80
+ dl { display: grid; grid-template-columns: 10rem 1fr; gap: .35rem .75rem; margin: 0; }
81
+ dt { color: var(--muted); font-size: .85rem; }
82
+ dd { margin: 0; font-size: .9rem; }
83
+ details { margin-top: .6rem; }
84
+ summary { color: var(--muted); cursor: pointer; font-size: .85rem; }
85
+ pre {
86
+ background: #0b1220; color: #cbd5e1; border: 1px solid var(--border);
87
+ border-radius: 8px; padding: .75rem; overflow-x: auto; font-size: .8rem;
88
+ }
89
+ .empty { color: var(--muted); }
90
+ footer {
91
+ margin-top: 2rem; padding: 1rem 1.25rem; color: var(--muted);
92
+ background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
93
+ font-size: .85rem;
94
+ }
95
+ </style>
96
+ </head>
97
+ <body>
98
+ <div class="wrap">
99
+ <header>
100
+ <h1>Inspectra <span>Security Assessment Report</span></h1>
101
+ <p class="meta">
102
+ Target: <code>{{ result.target.input }}</code> ·
103
+ {{ started_display }} ·
104
+ {{ result.metadata.tool }} {{ result.metadata.version }}
105
+ </p>
106
+ </header>
107
+
108
+ <section class="score-card">
109
+ <div class="score">{{ "%.1f"|format(result.posture_score or 0) }}<small> / 100</small></div>
110
+ <div class="grade {{ grade_class }}">{{ result.grade }}</div>
111
+ <div class="summary">
112
+ <span class="chip sev-high">High {{ summary.high }}</span>
113
+ <span class="chip sev-medium">Medium {{ summary.medium }}</span>
114
+ <span class="chip sev-low">Low {{ summary.low }}</span>
115
+ <span class="chip sev-info">Info {{ summary.info }}</span>
116
+ </div>
117
+ </section>
118
+
119
+ <h2>Findings ({{ result.total_findings }})</h2>
120
+
121
+ {% for finding in findings %}
122
+ <article class="finding sev-{{ finding.severity.value }}">
123
+ <h3><span class="badge">{{ finding.severity.value|upper }}</span> {{ finding.rule_id }} — {{ finding.title }}</h3>
124
+ <dl>
125
+ <dt>What was observed</dt><dd>{{ finding.description }}</dd>
126
+ <dt>Why it matters</dt><dd>{{ finding.why_it_matters }}</dd>
127
+ <dt>Confidence</dt><dd>{{ finding.confidence.value|capitalize }}</dd>
128
+ <dt>Recommendation</dt><dd>{{ finding.recommendation }}</dd>
129
+ </dl>
130
+ {% if finding.evidence %}
131
+ <details><summary>Evidence ({{ finding.evidence|length }})</summary><pre>{{ finding.evidence|join('\n') }}</pre></details>
132
+ {% endif %}
133
+ </article>
134
+ {% else %}
135
+ <p class="empty">No findings were recorded during this scan.</p>
136
+ {% endfor %}
137
+
138
+ <footer>
139
+ Generated by <strong>Inspectra</strong> — a passive security assessment
140
+ framework. It observes, assesses, explains and reports; it never exploits.
141
+ Only scan systems you own or are authorized to test.
142
+ </footer>
143
+ </div>
144
+ </body>
145
+ </html>
inspectra/safety.py ADDED
@@ -0,0 +1,217 @@
1
+ """SSRF-safe target validation for Inspectra scans.
2
+
3
+ Validates target hostnames and IP addresses before any network I/O, pins the
4
+ connection to the validated IP (defence against DNS rebinding), and re-validates
5
+ after every HTTP redirect hop. Blocks access to private, loopback, link-local,
6
+ CGNAT, unique-local, unspecified, multicast, and metadata addresses unless
7
+ explicitly allowed.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ipaddress
13
+ import socket
14
+ import sys
15
+
16
+ #: Hard-rejected metadata endpoints (hostnames and IP addresses).
17
+ METADATA_ENDPOINTS = {
18
+ "169.254.169.254",
19
+ "metadata.google.internal",
20
+ "fd00:ec2::254",
21
+ }
22
+
23
+ #: Explicitly blocked networks (ipaddress.is_private is False for 100.64/10 on 3.11).
24
+ BLOCKED_NETWORKS = [
25
+ ipaddress.ip_network("10.0.0.0/8"),
26
+ ipaddress.ip_network("172.16.0.0/12"),
27
+ ipaddress.ip_network("192.168.0.0/16"),
28
+ ipaddress.ip_network("127.0.0.0/8"),
29
+ ipaddress.ip_network("169.254.0.0/16"),
30
+ ipaddress.ip_network("100.64.0.0/10"),
31
+ ipaddress.ip_network("0.0.0.0/8"),
32
+ ipaddress.ip_network("192.0.0.0/24"),
33
+ ipaddress.ip_network("198.18.0.0/15"),
34
+ ipaddress.ip_network("224.0.0.0/4"),
35
+ ipaddress.ip_network("::1/128"),
36
+ ipaddress.ip_network("fc00::/7"),
37
+ ipaddress.ip_network("fe80::/10"),
38
+ ipaddress.ip_network("::/128"),
39
+ ipaddress.ip_network("ff00::/8"),
40
+ ]
41
+
42
+
43
+ class SSRFError(Exception):
44
+ """Raised when a target fails SSRF safety validation."""
45
+
46
+
47
+ def _normalize_ip(
48
+ ip: ipaddress.IPv4Address | ipaddress.IPv6Address,
49
+ ) -> ipaddress.IPv4Address | ipaddress.IPv6Address:
50
+ """Normalise IPv4-mapped IPv6 to IPv4 before network checks."""
51
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
52
+ return ip.ipv4_mapped
53
+ return ip
54
+
55
+
56
+ def _is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
57
+ """True when the IP is in any blocked network."""
58
+ norm = _normalize_ip(ip)
59
+ return any(norm in net for net in BLOCKED_NETWORKS)
60
+
61
+
62
+ def resolve_host(host: str) -> str:
63
+ """Resolve a hostname to a single IP address string.
64
+
65
+ Resolves once and returns the first address. Raises SSRFError if the
66
+ hostname cannot be resolved. The caller must pass this IP back for every
67
+ subsequent request so DNS cannot flip between validation and connect.
68
+ """
69
+ try:
70
+ infos = socket.getaddrinfo(host, None)
71
+ for info in infos:
72
+ addr = str(info[4][0])
73
+ try:
74
+ ipaddress.ip_address(addr)
75
+ return addr
76
+ except ValueError:
77
+ continue
78
+ except OSError as exc:
79
+ raise SSRFError(f"Could not resolve hostname {host!r}: {exc}") from exc
80
+ raise SSRFError(f"Could not resolve hostname {host!r}: no usable address")
81
+
82
+
83
+ def validate_target(
84
+ host: str,
85
+ allow_private: bool = False,
86
+ authorized: bool = False,
87
+ ) -> str:
88
+ """Validate a target host for SSRF safety and return the pinned IP.
89
+
90
+ Resolves the hostname once and checks every resolved IP against blocked
91
+ networks. Returns the pinned IP address string that must be used for all
92
+ subsequent connections to this host (preventing DNS rebinding).
93
+
94
+ Raises SSRFError if any resolved IP is blocked and not explicitly allowed,
95
+ or if the host is a known metadata endpoint.
96
+
97
+ Parameters
98
+ ----------
99
+ host : str
100
+ The hostname to validate.
101
+ allow_private : bool
102
+ If True, allow private/loopback/link-local addresses. Requires
103
+ ``authorized`` to be True.
104
+ authorized : bool
105
+ If True, the user has explicitly authorized private-target scanning.
106
+
107
+ Returns
108
+ -------
109
+ str
110
+ The pinned IP address for subsequent connections.
111
+ """
112
+ # Hard-reject metadata endpoints by hostname.
113
+ if host.lower() in METADATA_ENDPOINTS:
114
+ raise SSRFError(f"Access to metadata endpoint {host!r} is prohibited (SSRF protection).")
115
+
116
+ ip_str = resolve_host(host)
117
+
118
+ try:
119
+ ip = ipaddress.ip_address(ip_str)
120
+ except ValueError:
121
+ raise SSRFError(f"Resolved address {ip_str!r} is not a valid IP") from None
122
+
123
+ if _is_blocked_ip(ip):
124
+ if not allow_private:
125
+ raise SSRFError(
126
+ f"Target {host!r} ({ip_str}) resolves to a blocked address. "
127
+ "Use --allow-private for home-lab testing only."
128
+ )
129
+ if not authorized:
130
+ print(
131
+ "Error: --allow-private requires --authorized.",
132
+ file=sys.stderr,
133
+ )
134
+ raise SSRFError(
135
+ f"Target {host!r} ({ip_str}) resolves to a private address. "
136
+ "--allow-private requires --authorized."
137
+ )
138
+ print(
139
+ f"Warning: scanning private target {host!r} ({ip_str}). Home-lab testing only.",
140
+ file=sys.stderr,
141
+ )
142
+
143
+ return ip_str
144
+
145
+
146
+ def validate_redirect(
147
+ url: str,
148
+ original_scheme: str,
149
+ allow_private: bool = False,
150
+ authorized: bool = False,
151
+ hop: int = 1,
152
+ max_hops: int = 5,
153
+ ) -> str:
154
+ """Validate an HTTP redirect target for SSRF safety.
155
+
156
+ Parses the redirect URL, validates its hostname, enforces max-redirects,
157
+ and enforces the scheme rule: the scheme may only upgrade (http -> https).
158
+ https -> http or any other change is rejected.
159
+
160
+ Parameters
161
+ ----------
162
+ url : str
163
+ The redirect target URL.
164
+ original_scheme : str
165
+ The scheme of the original request (used as the baseline for scheme
166
+ downgrade detection).
167
+ allow_private : bool
168
+ If True, allow private addresses.
169
+ authorized : bool
170
+ If True, the user has authorized private-target scanning.
171
+ hop : int
172
+ The current redirect hop number (1-based).
173
+ max_hops : int
174
+ The maximum number of redirects allowed.
175
+
176
+ Returns
177
+ -------
178
+ str
179
+ The validated URL.
180
+
181
+ Raises
182
+ ------
183
+ SSRFError
184
+ If the redirect target is blocked, exceeds max hops, or uses a
185
+ disallowed scheme change.
186
+ """
187
+ from urllib.parse import urlparse
188
+
189
+ if hop > max_hops:
190
+ raise SSRFError(f"Redirect chain exceeds {max_hops} hops (SSRF protection).")
191
+
192
+ parsed = urlparse(url)
193
+ scheme = parsed.scheme.lower()
194
+ if scheme not in {"http", "https"}:
195
+ raise SSRFError(f"Cross-scheme redirect to {scheme!r} is prohibited (SSRF protection).")
196
+
197
+ # Scheme downgrade rule: http -> https is allowed; https -> http is not.
198
+ # On subsequent hops, the "original" scheme is the scheme of the previous
199
+ # hop (the URL we just validated), so any downgrade from https to http
200
+ # anywhere in the chain is rejected.
201
+ if original_scheme == "https" and scheme == "http":
202
+ raise SSRFError(f"HTTPS-to-HTTP downgrade redirect is prohibited (SSRF protection): {url}")
203
+
204
+ # Validate the redirect target hostname.
205
+ validate_target(parsed.hostname or "", allow_private, authorized)
206
+ return url
207
+
208
+
209
+ def scope_metadata(allow_private: bool, authorized: bool) -> dict[str, str] | None:
210
+ """Return report metadata for the scan scope.
211
+
212
+ Returns ``{"scope": "private-allowed"}`` when private scanning is
213
+ explicitly allowed, otherwise ``None``.
214
+ """
215
+ if allow_private:
216
+ return {"scope": "private-allowed"}
217
+ return None
inspectra/utils.py ADDED
@@ -0,0 +1,116 @@
1
+ """Small shared helpers: target normalization, data loading, evidence truncation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import json
7
+ import re
8
+ from datetime import UTC, datetime, timedelta, timezone
9
+ from importlib.resources import files
10
+ from typing import Any
11
+
12
+ from inspectra.models import Target
13
+
14
+ #: Indian Standard Time (UTC+05:30, no DST) — the display timezone for reports.
15
+ IST_TIMEZONE = timezone(timedelta(hours=5, minutes=30), name="IST")
16
+ IST_LABEL = "Asia/Kolkata (UTC+05:30)"
17
+
18
+ _HOSTNAME_RE = re.compile(
19
+ r"^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$"
20
+ )
21
+
22
+
23
+ class TargetValidationError(ValueError):
24
+ """Raised when a target string cannot be interpreted safely."""
25
+
26
+
27
+ def normalize_target(raw: str) -> Target:
28
+ """Turn a user-supplied domain, IP or URL into a validated :class:`Target`.
29
+
30
+ Raises :class:`TargetValidationError` for anything ambiguous or unsafe.
31
+ """
32
+ value = raw.strip().rstrip("/")
33
+ if not value:
34
+ raise TargetValidationError("Target cannot be empty.")
35
+ if "://" in value:
36
+ return _from_url(value)
37
+ if " " in value or "@" in value:
38
+ raise TargetValidationError(f"Invalid target {raw!r}: unexpected characters.")
39
+ host, _, port_str = value.rpartition(":")
40
+ if port_str.isdigit() and host:
41
+ return _from_hostname(host, int(port_str))
42
+ return _from_hostname(value, None)
43
+
44
+
45
+ def _from_url(value: str) -> Target:
46
+ from urllib.parse import urlparse
47
+
48
+ parsed = urlparse(value)
49
+ scheme = parsed.scheme.lower()
50
+ if scheme not in {"http", "https"}:
51
+ raise TargetValidationError(f"Unsupported scheme {scheme!r}; use http or https.")
52
+ if not parsed.hostname:
53
+ raise TargetValidationError(f"Could not extract a hostname from {value!r}.")
54
+ if parsed.username or parsed.password:
55
+ raise TargetValidationError("URLs with embedded credentials are not supported.")
56
+ return _from_hostname(parsed.hostname, parsed.port, scheme=scheme, input_value=value)
57
+
58
+
59
+ def _from_hostname(
60
+ host: str, port: int | None, scheme: str = "https", input_value: str | None = None
61
+ ) -> Target:
62
+ host = host.lower().rstrip(".")
63
+ if not _HOSTNAME_RE.match(host):
64
+ raise TargetValidationError(f"Invalid hostname: {host!r}")
65
+ if port is not None and not (1 <= port <= 65535):
66
+ raise TargetValidationError(f"Invalid port: {port}")
67
+ target = Target(input=input_value or host, hostname=host, port=port, scheme=scheme)
68
+ try:
69
+ address = ipaddress.ip_address(host)
70
+ except ValueError:
71
+ pass
72
+ else:
73
+ target.is_private = not address.is_global
74
+ return target
75
+
76
+
77
+ def is_private_address(ip: str) -> bool:
78
+ """True when the given IP string is a private or reserved address."""
79
+ try:
80
+ return not ipaddress.ip_address(ip).is_global
81
+ except ValueError:
82
+ return False
83
+
84
+
85
+ def load_json(name: str) -> Any:
86
+ """Load a JSON knowledge-base file shipped inside the package."""
87
+ path = files("inspectra").joinpath("data", name)
88
+ with path.open("r", encoding="utf-8") as handle:
89
+ return json.load(handle)
90
+
91
+
92
+ def load_text_lines(name: str) -> list[str]:
93
+ """Load a newline-separated data file, skipping blank lines and comments."""
94
+ path = files("inspectra").joinpath("data", name)
95
+ with path.open("r", encoding="utf-8") as handle:
96
+ return [
97
+ line.strip() for line in handle if line.strip() and not line.lstrip().startswith("#")
98
+ ]
99
+
100
+
101
+ def format_ist(dt: datetime) -> str:
102
+ """Format a datetime for display in Indian Standard Time.
103
+
104
+ Naive datetimes are assumed to be UTC. Storage stays UTC (ISO-8601);
105
+ only human-facing output is converted.
106
+ """
107
+ if dt.tzinfo is None:
108
+ dt = dt.replace(tzinfo=UTC)
109
+ return dt.astimezone(IST_TIMEZONE).strftime("%Y-%m-%d %H:%M:%S IST")
110
+
111
+
112
+ def truncate(text: str, limit: int = 500) -> str:
113
+ """Truncate evidence strings so reports stay readable."""
114
+ if len(text) <= limit:
115
+ return text
116
+ return text[: limit - 1] + "…"