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.
- inspectra/__init__.py +6 -0
- inspectra/__main__.py +6 -0
- inspectra/analysis/__init__.py +1 -0
- inspectra/analysis/recommendations.py +40 -0
- inspectra/analysis/risk.py +61 -0
- inspectra/baseline.py +94 -0
- inspectra/checks/__init__.py +79 -0
- inspectra/checks/context.py +29 -0
- inspectra/checks/directories.py +126 -0
- inspectra/checks/dns.py +141 -0
- inspectra/checks/fingerprint.py +102 -0
- inspectra/checks/headers.py +90 -0
- inspectra/checks/http.py +301 -0
- inspectra/checks/ports.py +179 -0
- inspectra/checks/robots.py +120 -0
- inspectra/checks/tls.py +212 -0
- inspectra/cli.py +413 -0
- inspectra/data/directory_wordlist.txt +170 -0
- inspectra/data/fingerprints.json +156 -0
- inspectra/data/header_rules.json +77 -0
- inspectra/models.py +138 -0
- inspectra/network.py +113 -0
- inspectra/orchestrator.py +145 -0
- inspectra/py.typed +0 -0
- inspectra/redact.py +92 -0
- inspectra/replay.py +195 -0
- inspectra/report/__init__.py +1 -0
- inspectra/report/html_report.py +69 -0
- inspectra/report/json_report.py +75 -0
- inspectra/report/markdown_report.py +86 -0
- inspectra/report/sarif_report.py +136 -0
- inspectra/report/templates/report.html.j2 +145 -0
- inspectra/safety.py +217 -0
- inspectra/utils.py +116 -0
- inspectra_cli-2.0.0.dist-info/METADATA +468 -0
- inspectra_cli-2.0.0.dist-info/RECORD +39 -0
- inspectra_cli-2.0.0.dist-info/WHEEL +4 -0
- inspectra_cli-2.0.0.dist-info/entry_points.txt +3 -0
- inspectra_cli-2.0.0.dist-info/licenses/LICENSE +21 -0
inspectra/__init__.py
ADDED
inspectra/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analysis package: risk scoring and recommendation helpers."""
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Recommendation helpers used by checks to build actionable advice.
|
|
2
|
+
|
|
3
|
+
Keeping recommendation text in one place means the wording stays consistent
|
|
4
|
+
across reports and is easy to review.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def remove_header(name: str) -> str:
|
|
11
|
+
"""Advice for a header that should not be present."""
|
|
12
|
+
return (
|
|
13
|
+
f"Remove the {name!r} response header (or disable the framework option "
|
|
14
|
+
"that adds it) to reduce information disclosure."
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def renew_certificate(days: int) -> str:
|
|
19
|
+
"""Advice for an expiring TLS certificate."""
|
|
20
|
+
return (
|
|
21
|
+
f"Renew the TLS certificate within {days} day(s). Consider automating "
|
|
22
|
+
"renewal with ACME (e.g. Let's Encrypt)."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def review_exposed_path(path: str) -> str:
|
|
27
|
+
"""Advice for an accessible path found by the directory check."""
|
|
28
|
+
return (
|
|
29
|
+
f"Review {path!r}: remove it if it is not needed, or protect it with "
|
|
30
|
+
"authentication and access controls."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def restrict_service(service: str, port: int) -> str:
|
|
35
|
+
"""Advice for a sensitive service exposed on the network."""
|
|
36
|
+
return (
|
|
37
|
+
f"Restrict {service} (port {port}) to trusted networks via firewall or "
|
|
38
|
+
"VPN rules, or replace it with a secure alternative (SFTP instead of "
|
|
39
|
+
"FTP, SSH instead of Telnet)."
|
|
40
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Risk engine: severity/confidence rubric and the posture score.
|
|
2
|
+
|
|
3
|
+
The rubric is deliberately conservative: findings carry a severity and a
|
|
4
|
+
confidence, and the posture score is a weighted penalty model where a single
|
|
5
|
+
high-confidence HIGH finding costs 36 points (see :data:`POINTS_PER_HIGH`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from inspectra.models import Confidence, Finding, ScanResult, Severity
|
|
11
|
+
|
|
12
|
+
SEVERITY_WEIGHTS: dict[Severity, int] = {
|
|
13
|
+
Severity.INFO: 0,
|
|
14
|
+
Severity.LOW: 1,
|
|
15
|
+
Severity.MEDIUM: 2,
|
|
16
|
+
Severity.HIGH: 3,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
CONFIDENCE_FACTORS: dict[Confidence, float] = {
|
|
20
|
+
Confidence.LOW: 0.3,
|
|
21
|
+
Confidence.MEDIUM: 0.6,
|
|
22
|
+
Confidence.HIGH: 1.0,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
#: Points deducted from 100 for a single HIGH/HIGH-confidence finding.
|
|
26
|
+
POINTS_PER_HIGH = 12.0
|
|
27
|
+
|
|
28
|
+
GRADE_BANDS: list[tuple[float, str]] = [
|
|
29
|
+
(95.0, "A+"),
|
|
30
|
+
(90.0, "A"),
|
|
31
|
+
(80.0, "B"),
|
|
32
|
+
(70.0, "C"),
|
|
33
|
+
(60.0, "D"),
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def finding_penalty(finding: Finding) -> float:
|
|
38
|
+
"""The posture-score penalty contributed by a single finding."""
|
|
39
|
+
weight = SEVERITY_WEIGHTS[finding.severity]
|
|
40
|
+
factor = CONFIDENCE_FACTORS[finding.confidence]
|
|
41
|
+
return weight * factor * POINTS_PER_HIGH
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def grade_for(score: float) -> str:
|
|
45
|
+
"""Map a 0-100 score to a letter grade."""
|
|
46
|
+
for threshold, grade in GRADE_BANDS:
|
|
47
|
+
if score >= threshold:
|
|
48
|
+
return grade
|
|
49
|
+
return "F"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def compute_posture_score(findings: list[Finding]) -> tuple[float, str]:
|
|
53
|
+
"""Return ``(score, grade)`` for a list of findings."""
|
|
54
|
+
penalty = sum(finding_penalty(finding) for finding in findings)
|
|
55
|
+
score = max(0.0, round(100.0 - penalty, 1))
|
|
56
|
+
return score, grade_for(score)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def apply(result: ScanResult) -> None:
|
|
60
|
+
"""Attach the posture score and grade to a scan result (in place)."""
|
|
61
|
+
result.posture_score, result.grade = compute_posture_score(result.findings)
|
inspectra/baseline.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Baseline diff support for Inspectra scans.
|
|
2
|
+
|
|
3
|
+
A baseline is a snapshot of findings from a previous scan. On a subsequent
|
|
4
|
+
scan, each finding is classified as ``new`` (not in baseline) or ``existing``
|
|
5
|
+
(in baseline). ``--fail-on`` applies only to new findings, so a CI gate can
|
|
6
|
+
regress on newly introduced issues without failing on pre-existing ones.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, cast
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def fingerprint_for(rule_id: str, location: str | None, evidence: str | None) -> str:
|
|
19
|
+
"""Stable fingerprint for a finding.
|
|
20
|
+
|
|
21
|
+
sha256 over the check id plus normalized location and evidence, so the
|
|
22
|
+
same finding produces the same fingerprint across runs even if the
|
|
23
|
+
timestamp or ordering changes.
|
|
24
|
+
"""
|
|
25
|
+
parts = [rule_id]
|
|
26
|
+
parts.append(_normalize(location) if location else "")
|
|
27
|
+
parts.append(_normalize(evidence) if evidence else "")
|
|
28
|
+
return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _normalize(value: str) -> str:
|
|
32
|
+
"""Normalize a string for stable fingerprinting."""
|
|
33
|
+
return " ".join(value.lower().split())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def save_baseline(target_input: str, findings: list[dict], path: Path) -> None:
|
|
37
|
+
"""Write a baseline file from a list of finding dictionaries."""
|
|
38
|
+
baseline = {
|
|
39
|
+
"target": target_input,
|
|
40
|
+
"generated_at": datetime.now(UTC).isoformat(),
|
|
41
|
+
"findings": findings,
|
|
42
|
+
}
|
|
43
|
+
path.write_text(json.dumps(baseline, indent=2) + "\n", encoding="utf-8")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_baseline(path: Path) -> dict[str, Any]:
|
|
47
|
+
"""Load a baseline file, returning its parsed contents."""
|
|
48
|
+
return cast(dict[str, Any], json.loads(path.read_text(encoding="utf-8")))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def classify_findings(findings: list[dict], baseline: dict[str, Any] | None) -> dict[str, int]:
|
|
52
|
+
"""Mark each finding as ``new`` or ``existing`` against a baseline.
|
|
53
|
+
|
|
54
|
+
Returns summary counts: ``{"new": n, "existing": n, "resolved": n}``.
|
|
55
|
+
Each finding dict gains a ``"_baseline_status"`` key.
|
|
56
|
+
"""
|
|
57
|
+
baseline_fingerprints: set[str] = set()
|
|
58
|
+
if baseline:
|
|
59
|
+
for bf in baseline.get("findings", []):
|
|
60
|
+
fp = bf.get("fingerprint")
|
|
61
|
+
if fp:
|
|
62
|
+
baseline_fingerprints.add(fp)
|
|
63
|
+
|
|
64
|
+
new_count = 0
|
|
65
|
+
existing_count = 0
|
|
66
|
+
for finding in findings:
|
|
67
|
+
fp = finding.get("fingerprint")
|
|
68
|
+
if fp and fp in baseline_fingerprints:
|
|
69
|
+
finding["_baseline_status"] = "existing"
|
|
70
|
+
existing_count += 1
|
|
71
|
+
else:
|
|
72
|
+
finding["_baseline_status"] = "new"
|
|
73
|
+
new_count += 1
|
|
74
|
+
|
|
75
|
+
resolved_count = 0
|
|
76
|
+
if baseline:
|
|
77
|
+
current_fingerprints: set[str] = set()
|
|
78
|
+
for finding in findings:
|
|
79
|
+
fp = finding.get("fingerprint")
|
|
80
|
+
if fp:
|
|
81
|
+
current_fingerprints.add(fp)
|
|
82
|
+
for bf in baseline.get("findings", []):
|
|
83
|
+
if bf.get("fingerprint") not in current_fingerprints:
|
|
84
|
+
resolved_count += 1
|
|
85
|
+
|
|
86
|
+
return {"new": new_count, "existing": existing_count, "resolved": resolved_count}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def failing_severity(fail_on: str, severity: str) -> bool:
|
|
90
|
+
"""True when ``severity`` is at or above ``fail_on`` threshold."""
|
|
91
|
+
order = {"none": -1, "low": 0, "medium": 1, "high": 2}
|
|
92
|
+
threshold = order.get(fail_on, 2)
|
|
93
|
+
level = order.get(severity, 0)
|
|
94
|
+
return level >= threshold
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Check registry and shared check exceptions.
|
|
2
|
+
|
|
3
|
+
Each check is a module exposing ``run(target, context) -> list[Finding]``.
|
|
4
|
+
Adding a new assessment area means: create the module, add its ``run``
|
|
5
|
+
function to :data:`ALL_CHECKS`, and document it (see CONTRIBUTING.md).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
from inspectra.checks.context import ScanContext
|
|
13
|
+
from inspectra.models import Finding, Target
|
|
14
|
+
|
|
15
|
+
Check = Callable[[Target, ScanContext], list[Finding]]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CheckError(Exception):
|
|
19
|
+
"""A check failed non-fatally; the scan continues without it."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class FatalCheckError(CheckError):
|
|
23
|
+
"""A check failed in a way that must abort the whole scan."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _load_checks() -> dict[str, Check]:
|
|
27
|
+
"""Import and index every check module.
|
|
28
|
+
|
|
29
|
+
Imported lazily so check modules can safely import ``CheckError`` from
|
|
30
|
+
this package without creating a circular import.
|
|
31
|
+
"""
|
|
32
|
+
from inspectra.checks import directories, dns, fingerprint, headers, http, ports, robots, tls
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
"dns": dns.run,
|
|
36
|
+
"ports": ports.run,
|
|
37
|
+
"http": http.run,
|
|
38
|
+
"tls": tls.run,
|
|
39
|
+
"headers": headers.run,
|
|
40
|
+
"fingerprint": fingerprint.run,
|
|
41
|
+
"robots": robots.run,
|
|
42
|
+
"directories": directories.run,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ALL_CHECKS: dict[str, Check] = _load_checks()
|
|
47
|
+
|
|
48
|
+
DEFAULT_CHECK_ORDER = [
|
|
49
|
+
"dns",
|
|
50
|
+
"ports",
|
|
51
|
+
"http",
|
|
52
|
+
"tls",
|
|
53
|
+
"headers",
|
|
54
|
+
"fingerprint",
|
|
55
|
+
"robots",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def ordered_checks(include_directories: bool = False) -> list[tuple[str, Check]]:
|
|
60
|
+
"""Return the checks in execution order.
|
|
61
|
+
|
|
62
|
+
Order matters: HTTP must run before the checks that consume its cached
|
|
63
|
+
response (headers, fingerprint, robots), and DNS runs first so later
|
|
64
|
+
checks can rely on resolved addresses.
|
|
65
|
+
"""
|
|
66
|
+
names = [*DEFAULT_CHECK_ORDER]
|
|
67
|
+
if include_directories:
|
|
68
|
+
names.append("directories")
|
|
69
|
+
return [(name, ALL_CHECKS[name]) for name in names]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"ALL_CHECKS",
|
|
74
|
+
"Check",
|
|
75
|
+
"CheckError",
|
|
76
|
+
"FatalCheckError",
|
|
77
|
+
"ScanContext",
|
|
78
|
+
"ordered_checks",
|
|
79
|
+
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Shared state passed between checks during a scan."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from inspectra.models import ScanOptions
|
|
11
|
+
from inspectra.network import TlsInfo
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(slots=True)
|
|
15
|
+
class ScanContext:
|
|
16
|
+
"""Carries shared resources and intermediate results between checks.
|
|
17
|
+
|
|
18
|
+
Checks run in a fixed order; later checks consume values that earlier
|
|
19
|
+
checks stored here (for example, the HTTP check stores the primary
|
|
20
|
+
response so the headers and fingerprint checks do not re-fetch).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
client: Any = None
|
|
24
|
+
options: ScanOptions | None = None
|
|
25
|
+
http_response: httpx.Response | None = None
|
|
26
|
+
robots_response: httpx.Response | None = None
|
|
27
|
+
dns_records: dict[str, list[str]] = field(default_factory=dict)
|
|
28
|
+
dns_elapsed: float = 0.0
|
|
29
|
+
tls: TlsInfo | None = None
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Opt-in directory observation check.
|
|
2
|
+
|
|
3
|
+
Deliberately conservative: GET-only, one request every
|
|
4
|
+
:data:`REQUEST_DELAY_SECONDS`, single-threaded, and only 2xx/3xx responses
|
|
5
|
+
are reported. It never follows up, never sends payloads, and never tries to
|
|
6
|
+
exploit anything it finds.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from inspectra.analysis.recommendations import review_exposed_path
|
|
15
|
+
from inspectra.checks.context import ScanContext
|
|
16
|
+
from inspectra.models import Confidence, Finding, Severity, Target
|
|
17
|
+
from inspectra.utils import load_text_lines
|
|
18
|
+
|
|
19
|
+
REQUEST_DELAY_SECONDS = 0.5
|
|
20
|
+
FOUND_STATUSES = {200, 201, 202, 204, 301, 302, 303, 307, 308}
|
|
21
|
+
MAX_PATH_EVIDENCE = 20
|
|
22
|
+
|
|
23
|
+
#: Paths whose exposure is more serious than a generic 2xx response.
|
|
24
|
+
SENSITIVE_PATHS: dict[str, Severity] = {
|
|
25
|
+
"/.git/": Severity.HIGH,
|
|
26
|
+
"/.git/config": Severity.HIGH,
|
|
27
|
+
"/.git/HEAD": Severity.HIGH,
|
|
28
|
+
"/.env": Severity.HIGH,
|
|
29
|
+
"/.env.local": Severity.HIGH,
|
|
30
|
+
"/.aws/": Severity.HIGH,
|
|
31
|
+
"/.ssh/": Severity.HIGH,
|
|
32
|
+
"/.htpasswd": Severity.HIGH,
|
|
33
|
+
"/dump.sql": Severity.HIGH,
|
|
34
|
+
"/server.crt": Severity.HIGH,
|
|
35
|
+
"/server.key": Severity.HIGH,
|
|
36
|
+
"/id_rsa": Severity.HIGH,
|
|
37
|
+
"/key.pem": Severity.HIGH,
|
|
38
|
+
"/credentials": Severity.HIGH,
|
|
39
|
+
"/actuator/env": Severity.HIGH,
|
|
40
|
+
"/proc/self/environ": Severity.HIGH,
|
|
41
|
+
"/etc/passwd": Severity.HIGH,
|
|
42
|
+
"/backup": Severity.MEDIUM,
|
|
43
|
+
"/backups": Severity.MEDIUM,
|
|
44
|
+
"/config.php": Severity.MEDIUM,
|
|
45
|
+
"/config.json": Severity.MEDIUM,
|
|
46
|
+
"/server-status": Severity.MEDIUM,
|
|
47
|
+
"/server-info": Severity.MEDIUM,
|
|
48
|
+
"/phpinfo.php": Severity.MEDIUM,
|
|
49
|
+
"/admin": Severity.MEDIUM,
|
|
50
|
+
"/administrator": Severity.MEDIUM,
|
|
51
|
+
"/phpmyadmin": Severity.MEDIUM,
|
|
52
|
+
"/web.config": Severity.MEDIUM,
|
|
53
|
+
"/actuator/beans": Severity.MEDIUM,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run(target: Target, context: ScanContext) -> list[Finding]:
|
|
58
|
+
"""Probe the wordlist and report accessible paths (opt-in)."""
|
|
59
|
+
if context.http_response is None or context.client is None:
|
|
60
|
+
return []
|
|
61
|
+
client = context.client
|
|
62
|
+
base = target.base_url
|
|
63
|
+
found: list[tuple[str, int]] = []
|
|
64
|
+
for path in _wordlist(context):
|
|
65
|
+
try:
|
|
66
|
+
response = client.get(f"{base}{path}")
|
|
67
|
+
except Exception:
|
|
68
|
+
continue
|
|
69
|
+
if response.status_code in FOUND_STATUSES:
|
|
70
|
+
found.append((path, response.status_code))
|
|
71
|
+
time.sleep(REQUEST_DELAY_SECONDS)
|
|
72
|
+
|
|
73
|
+
if not found:
|
|
74
|
+
return []
|
|
75
|
+
findings = [_summary(target, found)]
|
|
76
|
+
for path, status in found:
|
|
77
|
+
if path in SENSITIVE_PATHS:
|
|
78
|
+
findings.append(_sensitive(path, status))
|
|
79
|
+
return findings
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _wordlist(context: ScanContext) -> list[str]:
|
|
83
|
+
if context.options is not None and context.options.directory_wordlist:
|
|
84
|
+
text = Path(context.options.directory_wordlist).read_text(encoding="utf-8")
|
|
85
|
+
return [
|
|
86
|
+
line.strip()
|
|
87
|
+
for line in text.splitlines()
|
|
88
|
+
if line.strip() and not line.lstrip().startswith("#")
|
|
89
|
+
]
|
|
90
|
+
return load_text_lines("directory_wordlist.txt")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _summary(target: Target, found: list[tuple[str, int]]) -> Finding:
|
|
94
|
+
return Finding(
|
|
95
|
+
rule_id="DIR-001",
|
|
96
|
+
title=f"{len(found)} accessible path(s) discovered",
|
|
97
|
+
category="directories",
|
|
98
|
+
severity=Severity.INFO,
|
|
99
|
+
confidence=Confidence.HIGH,
|
|
100
|
+
description=(
|
|
101
|
+
f"{len(found)} of the probed paths on {target.hostname} returned a successful response."
|
|
102
|
+
),
|
|
103
|
+
why_it_matters=(
|
|
104
|
+
"Accessible paths reveal the application's structure and may expose "
|
|
105
|
+
"dashboards, backups or configuration files."
|
|
106
|
+
),
|
|
107
|
+
recommendation="Review each discovered path and restrict or remove anything unintended.",
|
|
108
|
+
evidence=[f"{status} {path}" for path, status in found[:MAX_PATH_EVIDENCE]],
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _sensitive(path: str, status: int) -> Finding:
|
|
113
|
+
return Finding(
|
|
114
|
+
rule_id="DIR-002",
|
|
115
|
+
title=f"Sensitive path accessible: {path}",
|
|
116
|
+
category="directories",
|
|
117
|
+
severity=SENSITIVE_PATHS[path],
|
|
118
|
+
confidence=Confidence.MEDIUM,
|
|
119
|
+
description=f"The sensitive path {path!r} returned HTTP {status}.",
|
|
120
|
+
why_it_matters=(
|
|
121
|
+
"This path frequently contains secrets, source code or administrative "
|
|
122
|
+
"interfaces; its exposure is a serious risk."
|
|
123
|
+
),
|
|
124
|
+
recommendation=review_exposed_path(path),
|
|
125
|
+
evidence=[f"{status} {path}"],
|
|
126
|
+
)
|
inspectra/checks/dns.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""DNS resolution check: resolves the target and inspects DNS records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
import dns.exception
|
|
9
|
+
import dns.resolver
|
|
10
|
+
|
|
11
|
+
from inspectra.checks import FatalCheckError
|
|
12
|
+
from inspectra.checks.context import ScanContext
|
|
13
|
+
from inspectra.models import Confidence, Finding, Severity, Target
|
|
14
|
+
from inspectra.utils import is_private_address
|
|
15
|
+
|
|
16
|
+
RECORD_TYPES = ("A", "AAAA", "CNAME", "MX", "NS", "TXT")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run(target: Target, context: ScanContext) -> list[Finding]:
|
|
20
|
+
"""Resolve the target and report DNS observations."""
|
|
21
|
+
if _is_ip_literal(target.hostname):
|
|
22
|
+
_apply_ip_literal(target, context)
|
|
23
|
+
return []
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
records, elapsed = _resolve(target.hostname)
|
|
27
|
+
except dns.exception.Timeout as exc:
|
|
28
|
+
raise FatalCheckError(f"DNS resolution timed out for {target.hostname}.") from exc
|
|
29
|
+
except dns.resolver.NoNameservers as exc:
|
|
30
|
+
raise FatalCheckError(
|
|
31
|
+
f"Could not reach any configured DNS nameserver for {target.hostname}."
|
|
32
|
+
) from exc
|
|
33
|
+
except dns.resolver.NXDOMAIN as exc:
|
|
34
|
+
raise FatalCheckError(f"Domain {target.hostname} does not exist (NXDOMAIN).") from exc
|
|
35
|
+
|
|
36
|
+
context.dns_records = records
|
|
37
|
+
context.dns_elapsed = elapsed
|
|
38
|
+
target.ip_addresses = [*records["A"], *records["AAAA"]]
|
|
39
|
+
target.is_private = any(is_private_address(ip) for ip in target.ip_addresses)
|
|
40
|
+
|
|
41
|
+
findings: list[Finding] = []
|
|
42
|
+
if not target.ip_addresses:
|
|
43
|
+
raise FatalCheckError(f"Could not resolve any A/AAAA record for {target.hostname}.")
|
|
44
|
+
if len(target.ip_addresses) > 1:
|
|
45
|
+
findings.append(_multiple_addresses(target))
|
|
46
|
+
if not records["MX"]:
|
|
47
|
+
findings.append(_missing_record("MX"))
|
|
48
|
+
if not records["TXT"]:
|
|
49
|
+
findings.append(_missing_record("TXT"))
|
|
50
|
+
return findings
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_ip_literal(hostname: str) -> bool:
|
|
54
|
+
try:
|
|
55
|
+
ipaddress.ip_address(hostname)
|
|
56
|
+
except ValueError:
|
|
57
|
+
return False
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _apply_ip_literal(target: Target, context: ScanContext) -> None:
|
|
62
|
+
"""Targets given as IP addresses need no DNS resolution."""
|
|
63
|
+
address = ipaddress.ip_address(target.hostname)
|
|
64
|
+
target.ip_addresses = [target.hostname]
|
|
65
|
+
target.is_private = not address.is_global
|
|
66
|
+
context.dns_records = {rtype: [] for rtype in RECORD_TYPES}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _resolve(hostname: str) -> tuple[dict[str, list[str]], float]:
|
|
70
|
+
resolver = dns.resolver.Resolver(configure=True)
|
|
71
|
+
resolver.lifetime = 5.0
|
|
72
|
+
started = time.monotonic()
|
|
73
|
+
records: dict[str, list[str]] = {rtype: [] for rtype in RECORD_TYPES}
|
|
74
|
+
for rtype in RECORD_TYPES:
|
|
75
|
+
try:
|
|
76
|
+
answers = resolver.resolve(hostname, rtype)
|
|
77
|
+
except dns.resolver.NXDOMAIN:
|
|
78
|
+
if rtype == "A":
|
|
79
|
+
raise
|
|
80
|
+
continue
|
|
81
|
+
except dns.resolver.NoAnswer:
|
|
82
|
+
continue
|
|
83
|
+
for answer in answers:
|
|
84
|
+
records[rtype].append(str(answer).rstrip("."))
|
|
85
|
+
return records, time.monotonic() - started
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _multiple_addresses(target: Target) -> Finding:
|
|
89
|
+
return Finding(
|
|
90
|
+
rule_id="DNS-002",
|
|
91
|
+
title="Multiple A/AAAA records (load balancing)",
|
|
92
|
+
category="dns",
|
|
93
|
+
severity=Severity.INFO,
|
|
94
|
+
confidence=Confidence.MEDIUM,
|
|
95
|
+
description=f"The hostname {target.hostname} resolves to multiple addresses.",
|
|
96
|
+
why_it_matters=(
|
|
97
|
+
"Multiple addresses usually indicate load balancing or failover. "
|
|
98
|
+
"Verify that every address belongs to the organization."
|
|
99
|
+
),
|
|
100
|
+
recommendation=(
|
|
101
|
+
"Confirm every resolved address is expected and under the organization's control."
|
|
102
|
+
),
|
|
103
|
+
evidence=[f"{target.hostname} -> {', '.join(target.ip_addresses)}"],
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _missing_record(rtype: str) -> Finding:
|
|
108
|
+
if rtype == "MX":
|
|
109
|
+
return Finding(
|
|
110
|
+
rule_id="DNS-003",
|
|
111
|
+
title="No MX records found",
|
|
112
|
+
category="dns",
|
|
113
|
+
severity=Severity.INFO,
|
|
114
|
+
confidence=Confidence.LOW,
|
|
115
|
+
description="No MX records were found for this domain.",
|
|
116
|
+
why_it_matters=(
|
|
117
|
+
"MX records announce where a domain receives email. Their absence "
|
|
118
|
+
"may be intentional for non-mail domains, but if email is expected "
|
|
119
|
+
"it is a misconfiguration."
|
|
120
|
+
),
|
|
121
|
+
recommendation=(
|
|
122
|
+
"If this domain should receive email, add MX records pointing to your mail servers."
|
|
123
|
+
),
|
|
124
|
+
evidence=["MX query returned no records"],
|
|
125
|
+
)
|
|
126
|
+
return Finding(
|
|
127
|
+
rule_id="DNS-004",
|
|
128
|
+
title="No TXT records found",
|
|
129
|
+
category="dns",
|
|
130
|
+
severity=Severity.INFO,
|
|
131
|
+
confidence=Confidence.LOW,
|
|
132
|
+
description="No TXT records were found for this domain.",
|
|
133
|
+
why_it_matters=(
|
|
134
|
+
"TXT records carry SPF and DMARC policies that help prevent email "
|
|
135
|
+
"spoofing; their absence leaves the domain easier to impersonate."
|
|
136
|
+
),
|
|
137
|
+
recommendation=(
|
|
138
|
+
"Add SPF, DMARC (and DKIM where applicable) TXT records if the domain sends email."
|
|
139
|
+
),
|
|
140
|
+
evidence=["TXT query returned no records"],
|
|
141
|
+
)
|