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
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"name": "Nginx",
|
|
4
|
+
"category": "web_server",
|
|
5
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "nginx" }]
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
"name": "Apache",
|
|
9
|
+
"category": "web_server",
|
|
10
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "apache" }]
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
"name": "Microsoft IIS",
|
|
14
|
+
"category": "web_server",
|
|
15
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "microsoft-iis" }]
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"name": "Cloudflare",
|
|
19
|
+
"category": "cdn",
|
|
20
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "cloudflare" }]
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"name": "GitHub Pages",
|
|
24
|
+
"category": "hosting",
|
|
25
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "github\\.com" }]
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"name": "Netlify",
|
|
29
|
+
"category": "hosting",
|
|
30
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "netlify" }]
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"name": "Vercel",
|
|
34
|
+
"category": "hosting",
|
|
35
|
+
"patterns": [{ "type": "header", "name": "Server", "pattern": "vercel" }]
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"name": "WordPress",
|
|
39
|
+
"category": "cms",
|
|
40
|
+
"patterns": [
|
|
41
|
+
{ "type": "generator", "pattern": "wordpress" },
|
|
42
|
+
{ "type": "body", "pattern": "wp-content|wp-includes" }
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"name": "Drupal",
|
|
47
|
+
"category": "cms",
|
|
48
|
+
"patterns": [
|
|
49
|
+
{ "type": "generator", "pattern": "drupal" },
|
|
50
|
+
{ "type": "body", "pattern": "/sites/default/files" }
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"name": "Joomla",
|
|
55
|
+
"category": "cms",
|
|
56
|
+
"patterns": [
|
|
57
|
+
{ "type": "generator", "pattern": "joomla" },
|
|
58
|
+
{ "type": "body", "pattern": "/media/system/js/" }
|
|
59
|
+
]
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"name": "Django",
|
|
63
|
+
"category": "framework",
|
|
64
|
+
"patterns": [
|
|
65
|
+
{ "type": "header", "name": "Server", "pattern": "wsgiserver|django" },
|
|
66
|
+
{ "type": "cookie", "pattern": "csrftoken" },
|
|
67
|
+
{ "type": "body", "pattern": "csrfmiddlewaretoken" }
|
|
68
|
+
]
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"name": "Flask",
|
|
72
|
+
"category": "framework",
|
|
73
|
+
"patterns": [
|
|
74
|
+
{ "type": "cookie", "pattern": "^session$" },
|
|
75
|
+
{ "type": "body", "pattern": "flask" }
|
|
76
|
+
]
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"name": "Express",
|
|
80
|
+
"category": "framework",
|
|
81
|
+
"patterns": [{ "type": "header", "name": "X-Powered-By", "pattern": "express" }]
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"name": "Laravel",
|
|
85
|
+
"category": "framework",
|
|
86
|
+
"patterns": [{ "type": "cookie", "pattern": "laravel_session" }]
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"name": "Ruby on Rails",
|
|
90
|
+
"category": "framework",
|
|
91
|
+
"patterns": [
|
|
92
|
+
{ "type": "header", "name": "X-Powered-By", "pattern": "phusion|ruby" },
|
|
93
|
+
{ "type": "cookie", "pattern": "_session" }
|
|
94
|
+
]
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"name": "PHP",
|
|
98
|
+
"category": "language",
|
|
99
|
+
"patterns": [
|
|
100
|
+
{ "type": "header", "name": "X-Powered-By", "pattern": "php" },
|
|
101
|
+
{ "type": "generator", "pattern": "php" }
|
|
102
|
+
]
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"name": "ASP.NET",
|
|
106
|
+
"category": "framework",
|
|
107
|
+
"patterns": [
|
|
108
|
+
{ "type": "header", "name": "X-Powered-By", "pattern": "asp\\.net" },
|
|
109
|
+
{ "type": "cookie", "pattern": "aspsession" }
|
|
110
|
+
]
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"name": "Java (JSESSIONID)",
|
|
114
|
+
"category": "language",
|
|
115
|
+
"patterns": [{ "type": "cookie", "pattern": "jsessionid" }]
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"name": "Spring Boot",
|
|
119
|
+
"category": "framework",
|
|
120
|
+
"patterns": [
|
|
121
|
+
{ "type": "body", "pattern": "whitelabel error page" },
|
|
122
|
+
{ "type": "cookie", "pattern": "jsessionid" }
|
|
123
|
+
]
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
"name": "Apache Tomcat",
|
|
127
|
+
"category": "application_server",
|
|
128
|
+
"patterns": [
|
|
129
|
+
{ "type": "header", "name": "Server", "pattern": "tomcat" },
|
|
130
|
+
{ "type": "body", "pattern": "apache tomcat" }
|
|
131
|
+
]
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
"name": "Jenkins",
|
|
135
|
+
"category": "ci_cd",
|
|
136
|
+
"patterns": [{ "type": "header", "name": "X-Jenkins", "pattern": "." }]
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"name": "Jupyter",
|
|
140
|
+
"category": "application",
|
|
141
|
+
"patterns": [
|
|
142
|
+
{ "type": "header", "name": "Server", "pattern": "tornadoserver" },
|
|
143
|
+
{ "type": "body", "pattern": "jupyter" }
|
|
144
|
+
]
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
"name": "phpMyAdmin",
|
|
148
|
+
"category": "application",
|
|
149
|
+
"patterns": [{ "type": "body", "pattern": "phpmyadmin" }]
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
"name": "Grafana",
|
|
153
|
+
"category": "application",
|
|
154
|
+
"patterns": [{ "type": "body", "pattern": "grafana" }]
|
|
155
|
+
}
|
|
156
|
+
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "HDR-001",
|
|
4
|
+
"name": "Strict-Transport-Security",
|
|
5
|
+
"severity_when_missing": "medium",
|
|
6
|
+
"severity_when_weak": "low",
|
|
7
|
+
"pattern": "max-age\\s*=\\s*[1-9]",
|
|
8
|
+
"explanation": "HSTS tells browsers to only connect over HTTPS for a set period, protecting users from protocol-downgrade and cookie-hijacking attacks.",
|
|
9
|
+
"recommendation": "Set Strict-Transport-Security: max-age=31536000; includeSubDomains on every HTTPS response."
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"id": "HDR-002",
|
|
13
|
+
"name": "Content-Security-Policy",
|
|
14
|
+
"severity_when_missing": "medium",
|
|
15
|
+
"severity_when_weak": "low",
|
|
16
|
+
"pattern": "default-src|script-src|object-src",
|
|
17
|
+
"explanation": "CSP restricts which resources a page may load, sharply reducing the impact of cross-site scripting (XSS) and injection attacks.",
|
|
18
|
+
"recommendation": "Add a Content-Security-Policy header with explicit source allowlists (start with default-src 'self' and tighten over time)."
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "HDR-003",
|
|
22
|
+
"name": "X-Frame-Options",
|
|
23
|
+
"severity_when_missing": "medium",
|
|
24
|
+
"severity_when_weak": "low",
|
|
25
|
+
"pattern": "DENY|SAMEORIGIN",
|
|
26
|
+
"explanation": "Without clickjacking protection an attacker can embed the page in a transparent iframe and trick users into unintended actions.",
|
|
27
|
+
"recommendation": "Set X-Frame-Options: DENY (or SAMEORIGIN if framing by same-origin pages is required)."
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"id": "HDR-004",
|
|
31
|
+
"name": "X-Content-Type-Options",
|
|
32
|
+
"severity_when_missing": "low",
|
|
33
|
+
"severity_when_weak": "low",
|
|
34
|
+
"pattern": "nosniff",
|
|
35
|
+
"explanation": "Without nosniff, browsers may guess the MIME type of a response, which can turn an upload into an executable script.",
|
|
36
|
+
"recommendation": "Set X-Content-Type-Options: nosniff on all responses."
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"id": "HDR-005",
|
|
40
|
+
"name": "Referrer-Policy",
|
|
41
|
+
"severity_when_missing": "low",
|
|
42
|
+
"severity_when_weak": "low",
|
|
43
|
+
"pattern": "no-referrer|same-origin|strict-origin|no-referrer-when-downgrade",
|
|
44
|
+
"explanation": "Referrer-Policy controls how much of the previous URL is leaked to other sites, protecting sensitive query strings and paths.",
|
|
45
|
+
"recommendation": "Set Referrer-Policy: strict-origin-when-cross-origin (or no-referrer for highly sensitive applications)."
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"id": "HDR-006",
|
|
49
|
+
"name": "Permissions-Policy",
|
|
50
|
+
"severity_when_missing": "low",
|
|
51
|
+
"explanation": "Permissions-Policy restricts which browser features (camera, microphone, geolocation) a page and its frames may use.",
|
|
52
|
+
"recommendation": "Set Permissions-Policy with a restrictive default, e.g. Permissions-Policy: camera=(), microphone=(), geolocation=()."
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"id": "HDR-007",
|
|
56
|
+
"name": "Cross-Origin-Resource-Policy",
|
|
57
|
+
"severity_when_missing": "low",
|
|
58
|
+
"severity_when_weak": "low",
|
|
59
|
+
"pattern": "same-origin|cross-origin",
|
|
60
|
+
"explanation": "CORP stops other origins from loading this site's resources, reducing cross-origin data leakage.",
|
|
61
|
+
"recommendation": "Set Cross-Origin-Resource-Policy: same-origin unless cross-origin embedding is explicitly required."
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"id": "HDR-008",
|
|
65
|
+
"name": "X-Powered-By",
|
|
66
|
+
"severity_when_present": "info",
|
|
67
|
+
"explanation": "The X-Powered-By header reveals the framework and often its version, giving attackers a head start on known vulnerabilities.",
|
|
68
|
+
"recommendation": "Remove the X-Powered-By header (or disable the framework option that adds it)."
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"id": "HDR-009",
|
|
72
|
+
"name": "X-XSS-Protection",
|
|
73
|
+
"severity_when_present": "low",
|
|
74
|
+
"explanation": "X-XSS-Protection is deprecated: modern browsers ignore it, and in some configurations it can introduce vulnerabilities. Content-Security-Policy is the replacement.",
|
|
75
|
+
"recommendation": "Remove the X-XSS-Protection header and rely on Content-Security-Policy instead."
|
|
76
|
+
}
|
|
77
|
+
]
|
inspectra/models.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Core domain models shared across Inspectra.
|
|
2
|
+
|
|
3
|
+
These dataclasses are the contract every module works against: checks emit
|
|
4
|
+
:class:`Finding` objects, the risk engine scores them, and reporters render
|
|
5
|
+
the resulting :class:`ScanResult`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from enum import StrEnum
|
|
13
|
+
|
|
14
|
+
from inspectra import __version__
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Severity(StrEnum):
|
|
18
|
+
"""Risk severity of a finding, ordered from least to most severe."""
|
|
19
|
+
|
|
20
|
+
INFO = "info"
|
|
21
|
+
LOW = "low"
|
|
22
|
+
MEDIUM = "medium"
|
|
23
|
+
HIGH = "high"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Confidence(StrEnum):
|
|
27
|
+
"""How sure we are that a finding reflects reality."""
|
|
28
|
+
|
|
29
|
+
LOW = "low"
|
|
30
|
+
MEDIUM = "medium"
|
|
31
|
+
HIGH = "high"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(slots=True)
|
|
35
|
+
class Finding:
|
|
36
|
+
"""A single observation produced by a check.
|
|
37
|
+
|
|
38
|
+
Every finding is explainable: it states what was observed, why it
|
|
39
|
+
matters, the evidence, the confidence, the severity and a practical
|
|
40
|
+
recommendation.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
rule_id: str
|
|
44
|
+
title: str
|
|
45
|
+
category: str
|
|
46
|
+
severity: Severity
|
|
47
|
+
confidence: Confidence
|
|
48
|
+
description: str
|
|
49
|
+
why_it_matters: str
|
|
50
|
+
recommendation: str
|
|
51
|
+
evidence: list[str] = field(default_factory=list)
|
|
52
|
+
fingerprint: str | None = None
|
|
53
|
+
_baseline_status: str | None = None
|
|
54
|
+
evidence_hash: str | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(slots=True)
|
|
58
|
+
class Target:
|
|
59
|
+
"""A validated scan target.
|
|
60
|
+
|
|
61
|
+
``ip_addresses`` and ``is_private`` are populated by the DNS check once
|
|
62
|
+
resolution has happened, which is why the dataclass is mutable.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
input: str
|
|
66
|
+
hostname: str
|
|
67
|
+
port: int | None = None
|
|
68
|
+
scheme: str = "https"
|
|
69
|
+
ip_addresses: list[str] = field(default_factory=list)
|
|
70
|
+
is_private: bool = False
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def base_url(self) -> str:
|
|
74
|
+
"""The URL used to reach the target over its working scheme."""
|
|
75
|
+
port = f":{self.port}" if self.port else ""
|
|
76
|
+
return f"{self.scheme}://{self.hostname}{port}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(slots=True)
|
|
80
|
+
class ScanOptions:
|
|
81
|
+
"""User-selected options that influence how a scan runs."""
|
|
82
|
+
|
|
83
|
+
output_dir: str = "inspectra-report"
|
|
84
|
+
report_format: str = "markdown"
|
|
85
|
+
ports: str | None = None
|
|
86
|
+
top_ports: int = 1000
|
|
87
|
+
skip_ports: bool = False
|
|
88
|
+
directories: bool = False
|
|
89
|
+
directory_wordlist: str | None = None
|
|
90
|
+
fail_on: str = "high"
|
|
91
|
+
save_baseline: str | None = None
|
|
92
|
+
baseline: str | None = None
|
|
93
|
+
output_path: str | None = None
|
|
94
|
+
allow_private: bool = False
|
|
95
|
+
authorized: bool = False
|
|
96
|
+
no_redact: bool = False
|
|
97
|
+
save_fixtures: str | None = None
|
|
98
|
+
replay_dir: str | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(slots=True)
|
|
102
|
+
class ScanMetadata:
|
|
103
|
+
"""Provenance and timing information embedded in every report."""
|
|
104
|
+
|
|
105
|
+
tool: str = "inspectra"
|
|
106
|
+
version: str = __version__
|
|
107
|
+
target: str = ""
|
|
108
|
+
started_at: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
109
|
+
finished_at: datetime | None = None
|
|
110
|
+
duration_seconds: float = 0.0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(slots=True)
|
|
114
|
+
class ScanResult:
|
|
115
|
+
"""The complete output of a scan: target, findings, score and metadata."""
|
|
116
|
+
|
|
117
|
+
target: Target
|
|
118
|
+
findings: list[Finding] = field(default_factory=list)
|
|
119
|
+
metadata: ScanMetadata = field(default_factory=ScanMetadata)
|
|
120
|
+
posture_score: float | None = None
|
|
121
|
+
grade: str | None = None
|
|
122
|
+
_baseline_summary: dict | None = None
|
|
123
|
+
scope: dict | None = None
|
|
124
|
+
redaction: dict | None = None
|
|
125
|
+
|
|
126
|
+
def count_by_severity(self, severity: Severity) -> int:
|
|
127
|
+
"""Count findings at the given severity."""
|
|
128
|
+
return sum(1 for finding in self.findings if finding.severity is severity)
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def total_findings(self) -> int:
|
|
132
|
+
"""Total number of findings recorded during the scan."""
|
|
133
|
+
return len(self.findings)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def has_actionable_findings(self) -> bool:
|
|
137
|
+
"""True when any finding is at least LOW severity (drives exit codes)."""
|
|
138
|
+
return any(finding.severity is not Severity.INFO for finding in self.findings)
|
inspectra/network.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""HTTP and TLS primitives shared by the network-facing checks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import socket
|
|
6
|
+
import ssl
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from cryptography import x509
|
|
12
|
+
from cryptography.x509.oid import ExtensionOID, NameOID
|
|
13
|
+
|
|
14
|
+
from inspectra import __version__
|
|
15
|
+
|
|
16
|
+
DEFAULT_TIMEOUT = httpx.Timeout(15.0, connect=10.0)
|
|
17
|
+
MAX_REDIRECTS = 5
|
|
18
|
+
USER_AGENT = f"Inspectra/{__version__} (passive security assessment; authorized use only)"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_client() -> httpx.Client:
|
|
22
|
+
"""Create a shared HTTP client for the scan.
|
|
23
|
+
|
|
24
|
+
``trust_env=False`` keeps scans from being silently routed through any
|
|
25
|
+
proxy configured in the environment.
|
|
26
|
+
"""
|
|
27
|
+
return httpx.Client(
|
|
28
|
+
timeout=DEFAULT_TIMEOUT,
|
|
29
|
+
follow_redirects=False,
|
|
30
|
+
trust_env=False,
|
|
31
|
+
headers={"User-Agent": USER_AGENT},
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(slots=True)
|
|
36
|
+
class TlsInfo:
|
|
37
|
+
"""Parsed TLS handshake and certificate details."""
|
|
38
|
+
|
|
39
|
+
version: str
|
|
40
|
+
cipher: str
|
|
41
|
+
subject_cn: str
|
|
42
|
+
issuer: str
|
|
43
|
+
not_valid_before: datetime
|
|
44
|
+
not_valid_after: datetime
|
|
45
|
+
san_dns: list[str]
|
|
46
|
+
is_self_signed: bool
|
|
47
|
+
hostname_matches: bool
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def days_remaining(self) -> int:
|
|
51
|
+
"""Whole days until the certificate expires (negative when expired)."""
|
|
52
|
+
return (self.not_valid_after - datetime.now(UTC)).days
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def is_expired(self) -> bool:
|
|
56
|
+
"""True when the certificate is already past its expiry date."""
|
|
57
|
+
return self.days_remaining < 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def inspect_tls(hostname: str, port: int = 443, timeout: float = 10.0) -> TlsInfo:
|
|
61
|
+
"""Perform a real TLS handshake and return parsed certificate details.
|
|
62
|
+
|
|
63
|
+
Raises ``ssl.SSLError`` / ``OSError`` when the handshake fails.
|
|
64
|
+
"""
|
|
65
|
+
context = ssl.create_default_context()
|
|
66
|
+
with (
|
|
67
|
+
socket.create_connection((hostname, port), timeout=timeout) as sock,
|
|
68
|
+
context.wrap_socket(sock, server_hostname=hostname) as tls_sock,
|
|
69
|
+
):
|
|
70
|
+
version = tls_sock.version() or "unknown"
|
|
71
|
+
cipher = tls_sock.cipher()
|
|
72
|
+
cipher_name = cipher[0] if cipher else "unknown"
|
|
73
|
+
der_cert = tls_sock.getpeercert(binary_form=True)
|
|
74
|
+
assert der_cert is not None, "verified TLS session must present a certificate"
|
|
75
|
+
cert = x509.load_der_x509_certificate(der_cert)
|
|
76
|
+
try:
|
|
77
|
+
san = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value
|
|
78
|
+
san_dns = list(san.get_values_for_type(x509.DNSName)) # type: ignore[attr-defined]
|
|
79
|
+
except x509.ExtensionNotFound:
|
|
80
|
+
san_dns = []
|
|
81
|
+
subject_cn = _common_name(cert.subject)
|
|
82
|
+
issuer_cn = _common_name(cert.issuer)
|
|
83
|
+
return TlsInfo(
|
|
84
|
+
version=version,
|
|
85
|
+
cipher=cipher_name,
|
|
86
|
+
subject_cn=subject_cn,
|
|
87
|
+
issuer=issuer_cn,
|
|
88
|
+
not_valid_before=cert.not_valid_before_utc,
|
|
89
|
+
not_valid_after=cert.not_valid_after_utc,
|
|
90
|
+
san_dns=san_dns,
|
|
91
|
+
is_self_signed=cert.issuer == cert.subject,
|
|
92
|
+
hostname_matches=_hostname_matches(hostname, san_dns, subject_cn),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _common_name(name: x509.Name) -> str:
|
|
97
|
+
try:
|
|
98
|
+
value = name.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
|
|
99
|
+
except IndexError:
|
|
100
|
+
return ""
|
|
101
|
+
return str(value)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _hostname_matches(hostname: str, san_dns: list[str], cn: str) -> bool:
|
|
105
|
+
return any(_pattern_matches(hostname, candidate) for candidate in [*san_dns, cn])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _pattern_matches(hostname: str, pattern: str) -> bool:
|
|
109
|
+
pattern = pattern.lower()
|
|
110
|
+
if pattern.startswith("*."):
|
|
111
|
+
suffix = pattern[1:]
|
|
112
|
+
return hostname.lower().endswith(suffix) and hostname.count(".") >= pattern.count(".")
|
|
113
|
+
return hostname.lower() == pattern
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Scan orchestrator: runs the registered checks and applies the risk engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from inspectra import __version__
|
|
13
|
+
from inspectra.analysis import risk
|
|
14
|
+
from inspectra.baseline import fingerprint_for
|
|
15
|
+
from inspectra.checks import CheckError, FatalCheckError, ordered_checks
|
|
16
|
+
from inspectra.checks.context import ScanContext
|
|
17
|
+
from inspectra.models import ScanMetadata, ScanOptions, ScanResult, Target
|
|
18
|
+
from inspectra.redact import redact_evidence
|
|
19
|
+
from inspectra.replay import FixtureStore, Recorder, Replayer, ReplayMissError
|
|
20
|
+
from inspectra.utils import truncate
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("inspectra")
|
|
23
|
+
|
|
24
|
+
ProgressCallback = Callable[[str], None]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ScanAborted(Exception):
|
|
28
|
+
"""Raised when a fatal problem prevents the scan from completing."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def run_scan(
|
|
32
|
+
target: Target,
|
|
33
|
+
options: ScanOptions,
|
|
34
|
+
progress: ProgressCallback | None = None,
|
|
35
|
+
) -> ScanResult:
|
|
36
|
+
"""Execute all checks against the target and produce a scored result.
|
|
37
|
+
|
|
38
|
+
Individual check failures degrade gracefully (logged, scan continues);
|
|
39
|
+
only :class:`FatalCheckError` aborts the scan.
|
|
40
|
+
"""
|
|
41
|
+
started = datetime.now(UTC)
|
|
42
|
+
metadata = ScanMetadata(version=__version__, target=target.input, started_at=started)
|
|
43
|
+
result = ScanResult(target=target, metadata=metadata)
|
|
44
|
+
context = ScanContext(options=options)
|
|
45
|
+
|
|
46
|
+
# M4: replay mode never opens a socket; record mode wraps the client.
|
|
47
|
+
# Validate the replay directory before any check runs: a missing or empty
|
|
48
|
+
# fixture dir means the scan cannot produce meaningful results and must
|
|
49
|
+
# fail fast instead of going green with zero findings.
|
|
50
|
+
store: FixtureStore | None = None
|
|
51
|
+
if options.replay_dir:
|
|
52
|
+
replay_dir = Path(options.replay_dir)
|
|
53
|
+
if not replay_dir.is_dir():
|
|
54
|
+
raise ScanAborted(
|
|
55
|
+
f"Replay directory not found: {replay_dir}. "
|
|
56
|
+
"Run with --save-fixtures first to create fixtures."
|
|
57
|
+
)
|
|
58
|
+
index_path = replay_dir / "index.json"
|
|
59
|
+
if not index_path.is_file():
|
|
60
|
+
raise ScanAborted(
|
|
61
|
+
f"No fixture index in replay directory: {replay_dir}. "
|
|
62
|
+
"Run with --save-fixtures first to create fixtures."
|
|
63
|
+
)
|
|
64
|
+
index = json.loads(index_path.read_text(encoding="utf-8"))
|
|
65
|
+
if not index:
|
|
66
|
+
raise ScanAborted(
|
|
67
|
+
f"Replay directory is empty: {replay_dir}. "
|
|
68
|
+
"Run with --save-fixtures first to create fixtures."
|
|
69
|
+
)
|
|
70
|
+
store = FixtureStore(replay_dir)
|
|
71
|
+
context.client = Replayer(store)
|
|
72
|
+
elif options.save_fixtures:
|
|
73
|
+
from inspectra.network import build_client # lazy: keeps CLI startup fast
|
|
74
|
+
|
|
75
|
+
store = FixtureStore(options.save_fixtures)
|
|
76
|
+
client = build_client()
|
|
77
|
+
context.client = Recorder(client, store)
|
|
78
|
+
_client_context = client
|
|
79
|
+
else:
|
|
80
|
+
from inspectra.network import build_client # lazy: keeps CLI startup fast
|
|
81
|
+
|
|
82
|
+
client = build_client()
|
|
83
|
+
context.client = client
|
|
84
|
+
_client_context = client
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
if options.replay_dir:
|
|
88
|
+
# Replayer has no context manager; run directly.
|
|
89
|
+
# Skip checks that need raw sockets (dns, ports, tls) in replay mode.
|
|
90
|
+
for name, check in ordered_checks(options.directories):
|
|
91
|
+
if name in ("dns", "ports", "tls"):
|
|
92
|
+
continue
|
|
93
|
+
if progress is not None:
|
|
94
|
+
progress(name)
|
|
95
|
+
try:
|
|
96
|
+
result.findings.extend(check(target, context))
|
|
97
|
+
except FatalCheckError as exc:
|
|
98
|
+
raise ScanAborted(str(exc)) from exc
|
|
99
|
+
except ReplayMissError as exc:
|
|
100
|
+
raise ScanAborted(
|
|
101
|
+
f"No replay fixture for {exc.url}. "
|
|
102
|
+
"Run with --save-fixtures first to create fixtures."
|
|
103
|
+
) from exc
|
|
104
|
+
except CheckError as exc:
|
|
105
|
+
logger.warning("Check '%s' skipped: %s", name, exc)
|
|
106
|
+
except Exception as exc: # defensive: never let one check kill a scan
|
|
107
|
+
logger.warning("Check '%s' failed unexpectedly: %s", name, exc)
|
|
108
|
+
else:
|
|
109
|
+
with _client_context:
|
|
110
|
+
for name, check in ordered_checks(options.directories):
|
|
111
|
+
if progress is not None:
|
|
112
|
+
progress(name)
|
|
113
|
+
try:
|
|
114
|
+
result.findings.extend(check(target, context))
|
|
115
|
+
except FatalCheckError as exc:
|
|
116
|
+
raise ScanAborted(str(exc)) from exc
|
|
117
|
+
except CheckError as exc:
|
|
118
|
+
logger.warning("Check '%s' skipped: %s", name, exc)
|
|
119
|
+
except Exception as exc: # defensive: never let one check kill a scan
|
|
120
|
+
logger.warning("Check '%s' failed unexpectedly: %s", name, exc)
|
|
121
|
+
finally:
|
|
122
|
+
if store is not None and not options.replay_dir:
|
|
123
|
+
_client_context.close()
|
|
124
|
+
|
|
125
|
+
for finding in result.findings:
|
|
126
|
+
finding.evidence = [truncate(line) for line in finding.evidence]
|
|
127
|
+
evidence_text = finding.evidence[0] if finding.evidence else None
|
|
128
|
+
finding.fingerprint = fingerprint_for(
|
|
129
|
+
finding.rule_id, result.target.base_url, evidence_text
|
|
130
|
+
)
|
|
131
|
+
# M4: evidence_hash over canonical JSON of evidence.
|
|
132
|
+
finding.evidence_hash = _evidence_hash(finding.evidence)
|
|
133
|
+
risk.apply(result)
|
|
134
|
+
if not options.no_redact:
|
|
135
|
+
for finding in result.findings:
|
|
136
|
+
finding.evidence = redact_evidence(finding.evidence)
|
|
137
|
+
result.metadata.finished_at = datetime.now(UTC)
|
|
138
|
+
result.metadata.duration_seconds = (result.metadata.finished_at - started).total_seconds()
|
|
139
|
+
return result
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _evidence_hash(evidence: list[str]) -> str:
|
|
143
|
+
"""SHA-256 of canonical JSON of the evidence list, truncated to 16 chars."""
|
|
144
|
+
canonical = json.dumps(evidence, sort_keys=True, separators=(",", ":"))
|
|
145
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
|
inspectra/py.typed
ADDED
|
File without changes
|