auditwright 0.1.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.
auditwright/pentest.py ADDED
@@ -0,0 +1,405 @@
1
+ """Authorised, non-destructive web pen test of a single origin.
2
+
3
+ Only run against systems you own or have written permission to test. The
4
+ module sends a bounded number of ordinary HTTP requests (no fuzzing, no
5
+ brute force, no payloads that change state), waits between requests, never
6
+ follows redirects, and never leaves the origin you name.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import secrets
13
+ import socket
14
+ import ssl
15
+ import time
16
+ from datetime import UTC, datetime
17
+ from typing import Any
18
+ from urllib.parse import urlencode, urlsplit
19
+
20
+ from .model import Finding, RuleMeta
21
+ from .net import Http, Response
22
+ from .rules.base import register
23
+
24
+ A01 = "A01:2021 Broken Access Control"
25
+ A02 = "A02:2021 Cryptographic Failures"
26
+ A03 = "A03:2021 Injection"
27
+ A05 = "A05:2021 Security Misconfiguration"
28
+ A07 = "A07:2021 Identification and Authentication Failures"
29
+
30
+
31
+ def _r(id_, title, sev, cwe, owasp, fix) -> RuleMeta:
32
+ return register(RuleMeta(id_, title, "pentest", sev, cwe, owasp, fix))
33
+
34
+
35
+ R = {
36
+ "tls_invalid": _r("AW-WEB-001", "Invalid TLS certificate", "high", "CWE-295", A02, "Install a certificate from a trusted CA that matches the host name, with the full chain."),
37
+ "tls_expiry": _r("AW-WEB-002", "TLS certificate expires soon", "medium", "CWE-298", A02, "Renew the certificate and automate renewal."),
38
+ "tls_old": _r("AW-WEB-003", "Legacy TLS protocol accepted", "medium", "CWE-326", A02, "Disable TLS 1.0 and 1.1; allow TLS 1.2 and 1.3 only."),
39
+ "no_https": _r("AW-WEB-004", "HTTP is not redirected to HTTPS", "medium", "CWE-319", A02, "Redirect all plain-HTTP requests to HTTPS with 301/308 and enable HSTS."),
40
+ "hsts": _r("AW-WEB-005", "Missing or weak HSTS", "medium", "CWE-523", A05, "Send Strict-Transport-Security: max-age=63072000; includeSubDomains; preload."),
41
+ "csp_missing": _r("AW-WEB-006", "No Content-Security-Policy", "medium", "CWE-1021", A05, "Add a CSP with script-src limited to self plus nonces or hashes; set object-src 'none' and base-uri 'self'."),
42
+ "csp_weak": _r("AW-WEB-007", "Weak Content-Security-Policy", "medium", "CWE-1021", A05, "Remove 'unsafe-inline', 'unsafe-eval' and wildcards from script-src; use nonces or hashes."),
43
+ "frame": _r("AW-WEB-008", "Page can be framed (clickjacking)", "medium", "CWE-1021", A05, "Send Content-Security-Policy: frame-ancestors 'none' (and X-Frame-Options: DENY for old browsers)."),
44
+ "nosniff": _r("AW-WEB-009", "Missing X-Content-Type-Options", "low", "CWE-693", A05, "Send X-Content-Type-Options: nosniff."),
45
+ "referrer": _r("AW-WEB-010", "Missing Referrer-Policy", "low", "CWE-200", A05, "Send Referrer-Policy: strict-origin-when-cross-origin (or no-referrer)."),
46
+ "permissions": _r("AW-WEB-011", "Missing Permissions-Policy", "info", "CWE-693", A05, "Send a Permissions-Policy that disables features you do not use (camera, microphone, geolocation...)."),
47
+ "disclosure": _r("AW-WEB-012", "Server software version disclosed", "low", "CWE-200", A05, "Remove version numbers from Server and X-Powered-By headers."),
48
+ "cookie": _r("AW-WEB-013", "Cookie without security flags", "medium", "CWE-614", A05, "Set Secure, HttpOnly and SameSite=Lax (or Strict) on session cookies."),
49
+ "cors": _r("AW-WEB-014", "CORS reflects arbitrary origins", "high", "CWE-942", A05, "Allow-list exact origins; never reflect the request Origin, especially with credentials."),
50
+ "trace": _r("AW-WEB-015", "TRACE method enabled", "low", "CWE-693", A05, "Disable TRACE on the web server and proxies."),
51
+ "exposed": _r("AW-WEB-016", "Sensitive file or endpoint exposed", "high", "CWE-538", A05, "Remove the file from the web root or block the path, then rotate any secrets it contained."),
52
+ "listing": _r("AW-WEB-017", "Directory listing enabled", "medium", "CWE-548", A05, "Disable directory indexes."),
53
+ "errors": _r("AW-WEB-018", "Verbose error page", "medium", "CWE-209", A05, "Show generic error pages in production and log details server-side."),
54
+ "redirect": _r("AW-WEB-019", "Open redirect", "medium", "CWE-601", A01, "Only redirect to relative paths or allow-listed hosts."),
55
+ "reflect": _r("AW-WEB-020", "Input reflected without encoding", "medium", "CWE-79", A03, "HTML-encode reflected input and add a strict CSP."),
56
+ "graphql": _r("AW-WEB-021", "GraphQL introspection enabled", "low", "CWE-200", A05, "Disable introspection in production."),
57
+ "securitytxt": _r("AW-WEB-022", "No security.txt", "info", "", A05, "Publish /.well-known/security.txt with a contact for vulnerability reports (RFC 9116)."),
58
+ "debugger": _r("AW-WEB-023", "Interactive debugger exposed", "critical", "CWE-489", A05, "Disable debug mode in production immediately; the console allows remote code execution."),
59
+ } # fmt: skip
60
+
61
+ # path, content signature (regex on body), severity override, description
62
+ EXPOSURES: list[tuple[str, str, str, str]] = [
63
+ ("/.git/HEAD", r"^ref: refs/|^[0-9a-f]{40}\s*$", "high", "Git metadata: the full source history can be downloaded"),
64
+ ("/.git/config", r"\[core\]", "high", "Git config"),
65
+ ("/.env", r"(?m)^[A-Z][A-Z0-9_]{2,}=.+", "critical", "Environment file with configuration and secrets"),
66
+ ("/.env.production", r"(?m)^[A-Z][A-Z0-9_]{2,}=.+", "critical", "Production environment file"),
67
+ ("/.env.local", r"(?m)^[A-Z][A-Z0-9_]{2,}=.+", "critical", "Local environment file"),
68
+ ("/.aws/credentials", r"aws_access_key_id", "critical", "AWS credentials"),
69
+ ("/.DS_Store", r"Bud1", "low", "macOS folder metadata listing file names"),
70
+ ("/.svn/entries", r"^\d+\s*$|svn", "high", "Subversion metadata"),
71
+ ("/.hg/requirements", r"revlogv1|store", "high", "Mercurial metadata"),
72
+ ("/server-status", r"Apache Server Status", "medium", "Apache server status page"),
73
+ ("/phpinfo.php", r"phpinfo\(\)|PHP Version", "medium", "phpinfo() output"),
74
+ ("/info.php", r"phpinfo\(\)|PHP Version", "medium", "phpinfo() output"),
75
+ ("/actuator/env", r"propertySources|activeProfiles", "high", "Spring Boot environment endpoint"),
76
+ ("/actuator/heapdump", r"JAVA PROFILE", "critical", "Spring Boot heap dump (contains secrets in memory)"),
77
+ ("/actuator", r"\"_links\"", "low", "Spring Boot actuator index"),
78
+ ("/backup.zip", r"^PK", "high", "Backup archive"),
79
+ ("/backup.sql", r"(?i)INSERT INTO|CREATE TABLE", "critical", "Database dump"),
80
+ ("/db.sql", r"(?i)INSERT INTO|CREATE TABLE", "critical", "Database dump"),
81
+ ("/dump.sql", r"(?i)INSERT INTO|CREATE TABLE", "critical", "Database dump"),
82
+ ("/wp-config.php.bak", r"DB_PASSWORD", "critical", "WordPress config backup"),
83
+ ("/config.php.bak", r"(?i)password", "high", "Config backup"),
84
+ ("/docker-compose.yml", r"(?m)^services\s*:", "medium", "Container topology"),
85
+ ("/.vscode/sftp.json", r"\"host\"", "high", "Editor deployment credentials"),
86
+ ("/id_rsa", r"PRIVATE KEY", "critical", "Private SSH key"),
87
+ ("/.npmrc", r"_authToken|registry", "high", "npm config (may contain tokens)"),
88
+ ("/swagger.json", r"\"swagger\"|\"openapi\"", "info", "API description"),
89
+ ("/openapi.json", r"\"openapi\"", "info", "API description"),
90
+ ("/.well-known/openid-configuration", r"\"issuer\"", "info", "OpenID configuration"),
91
+ ] # fmt: skip
92
+
93
+ DEBUG_CONSOLES = [
94
+ ("/console", r"Werkzeug Debugger|__debugger__"),
95
+ ("/__debug__/", r"Django"),
96
+ ("/_profiler", r"Symfony Profiler"),
97
+ ]
98
+ ERROR_MARKERS = re.compile(
99
+ r"Traceback \(most recent call last\)|at [a-z]+\.[A-Za-z.]+\([A-Za-z]+\.java:\d+\)|SQLSTATE\[|ORA-\d{5}|"
100
+ r"Warning: (?:mysqli?|pg)_|Whoops! There was an error|Werkzeug Debugger|Server Error in '/' Application|"
101
+ r"Microsoft OLE DB|DEBUG = True|You're seeing this error because you have <code>DEBUG = True</code>|"
102
+ r"Exception in thread|stack trace:|node_modules/[^\s]+\.js:\d+:\d+"
103
+ )
104
+
105
+
106
+ class PenTest:
107
+ def __init__(self, target: str, *, delay: float = 0.25, max_requests: int = 120, timeout: float = 12.0) -> None:
108
+ parts = urlsplit(target if "://" in target else f"https://{target}")
109
+ if parts.scheme not in ("http", "https") or not parts.hostname:
110
+ raise ValueError("target must be an http(s) URL or host name")
111
+ self.scheme = parts.scheme
112
+ self.host = parts.hostname
113
+ self.port = parts.port
114
+ self.netloc = parts.netloc
115
+ self.base = f"{parts.scheme}://{parts.netloc}"
116
+ self.path = parts.path or "/"
117
+ self.delay = delay
118
+ self.max_requests = max_requests
119
+ self.requests = 0
120
+ self.http = Http(timeout=timeout, max_bytes=2 * 1024 * 1024, allow_http=True, verify_tls=False)
121
+ self.findings: list[Finding] = []
122
+ self.facts: dict[str, Any] = {"target": self.base + self.path, "host": self.host}
123
+ self.marker = secrets.token_hex(6)
124
+
125
+ # -- plumbing -----------------------------------------------------------------
126
+ def fetch(
127
+ self, path: str, method: str = "GET", headers: dict[str, str] | None = None, *, base: str | None = None
128
+ ) -> Response | None:
129
+ if self.requests >= self.max_requests:
130
+ return None
131
+ self.requests += 1
132
+ if self.requests > 1:
133
+ time.sleep(self.delay)
134
+ try:
135
+ return self.http.request(method, (base or self.base) + path, headers=headers)
136
+ except (OSError, ValueError):
137
+ return None
138
+
139
+ def add(
140
+ self, key: str, msg: str, where: str = "", *, severity: str | None = None, confidence: str = "high", **extra
141
+ ) -> None:
142
+ kw = {"severity": severity} if severity else {}
143
+ self.findings.append(
144
+ Finding.from_rule(
145
+ R[key],
146
+ msg,
147
+ file=self.base + (where or self.path),
148
+ snippet=extra.pop("evidence", "")[:240],
149
+ confidence=confidence,
150
+ extra=extra,
151
+ **kw,
152
+ ) # fmt: skip
153
+ )
154
+
155
+ # -- checks -------------------------------------------------------------------
156
+ def run(self) -> tuple[list[Finding], dict[str, Any]]:
157
+ if self.scheme == "https":
158
+ self.check_tls()
159
+ self.check_http_redirect()
160
+ else:
161
+ self.add("no_https", "The target is served over plain HTTP.", severity="high")
162
+ home = self.fetch(self.path)
163
+ if home is None:
164
+ self.facts["error"] = "target did not respond"
165
+ return self.findings, self.facts
166
+ self.facts["status"] = home.status
167
+ self.facts["server"] = home.headers.get("server", "")
168
+ self.check_headers(home)
169
+ self.check_cookies(home)
170
+ self.check_cors()
171
+ self.check_methods()
172
+ not_found = self.fetch(f"/aw-{self.marker}-missing")
173
+ self.check_exposures(not_found)
174
+ self.check_errors()
175
+ self.check_redirects()
176
+ self.check_reflection()
177
+ self.check_graphql()
178
+ self.facts["requests"] = self.requests
179
+ return self.findings, self.facts
180
+
181
+ def _tls_connect(self, ctx: ssl.SSLContext) -> ssl.SSLSocket:
182
+ sock = socket.create_connection((self.host, self.port or 443), timeout=10)
183
+ try:
184
+ return ctx.wrap_socket(sock, server_hostname=self.host)
185
+ except BaseException:
186
+ sock.close()
187
+ raise
188
+
189
+ def check_tls(self) -> None:
190
+ try:
191
+ with self._tls_connect(ssl.create_default_context()) as s:
192
+ cert = s.getpeercert() or {}
193
+ self.facts["tls_version"] = s.version()
194
+ self.facts["cipher"] = (s.cipher() or ("",))[0]
195
+ not_after = cert.get("notAfter")
196
+ if not_after:
197
+ expires = datetime.fromtimestamp(ssl.cert_time_to_seconds(not_after), UTC)
198
+ days = (expires - datetime.now(UTC)).days
199
+ self.facts["cert_expires"] = expires.date().isoformat()
200
+ if days < 21:
201
+ self.add("tls_expiry", f"The certificate expires in {days} days ({expires.date()}).",
202
+ severity="high" if days < 7 else "medium") # fmt: skip
203
+ except ssl.SSLCertVerificationError as exc:
204
+ self.add("tls_invalid", f"Certificate verification failed: {exc.verify_message or exc}.")
205
+ except (OSError, ssl.SSLError) as exc:
206
+ self.facts["tls_error"] = f"{type(exc).__name__}"
207
+ return
208
+ for label, version in (("TLS 1.0", ssl.TLSVersion.TLSv1), ("TLS 1.1", ssl.TLSVersion.TLSv1_1)):
209
+ try:
210
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
211
+ ctx.check_hostname = False
212
+ ctx.verify_mode = ssl.CERT_NONE
213
+ ctx.minimum_version = version
214
+ ctx.maximum_version = version
215
+ ctx.set_ciphers("ALL:@SECLEVEL=0")
216
+ with self._tls_connect(ctx):
217
+ self.add("tls_old", f"The server completed a {label} handshake.")
218
+ except (OSError, ssl.SSLError, ValueError):
219
+ continue
220
+
221
+ def check_http_redirect(self) -> None:
222
+ if self.port not in (None, 443):
223
+ return
224
+ r = self.fetch(self.path, base=f"http://{self.host}")
225
+ if r is None:
226
+ return
227
+ loc = r.headers.get("location", "")
228
+ if not (r.status in (301, 302, 307, 308) and loc.startswith("https://")):
229
+ self.add("no_https", f"http://{self.host}{self.path} answered {r.status} without redirecting to HTTPS.",
230
+ evidence=f"HTTP {r.status} Location: {loc}") # fmt: skip
231
+
232
+ def check_headers(self, r: Response) -> None:
233
+ h = r.headers
234
+ if self.scheme == "https":
235
+ hsts = h.get("strict-transport-security", "")
236
+ m = re.search(r"max-age=(\d+)", hsts)
237
+ if not hsts:
238
+ self.add("hsts", "Strict-Transport-Security is not sent.")
239
+ elif not m or int(m.group(1)) < 15_552_000:
240
+ self.add("hsts", "HSTS max-age is shorter than 180 days.", evidence=hsts, severity="low")
241
+ csp = h.get("content-security-policy", "")
242
+ ctype = h.get("content-type", "")
243
+ is_html = "html" in ctype
244
+ if is_html and not csp:
245
+ self.add("csp_missing", "The page has no Content-Security-Policy.")
246
+ elif csp:
247
+ directives = {d.strip().split(" ", 1)[0].lower(): d.strip() for d in csp.split(";") if d.strip()}
248
+ script = directives.get("script-src") or directives.get("default-src", "")
249
+ weak = [
250
+ w
251
+ for w in ("'unsafe-inline'", "'unsafe-eval'", " * ", " data:", " http:", " https:")
252
+ if w in f" {script} "
253
+ ]
254
+ if "'unsafe-inline'" in weak and (
255
+ "'nonce-" in script or "'sha256-" in script or "'strict-dynamic'" in script
256
+ ):
257
+ weak.remove("'unsafe-inline'") # ignored by browsers when nonces/hashes are present
258
+ if weak:
259
+ self.add("csp_weak", f"script-src allows {', '.join(w.strip() for w in weak)}.", evidence=script)
260
+ if "object-src" not in directives and "'none'" not in directives.get("default-src", ""):
261
+ self.add("csp_weak", "CSP does not restrict object-src.", evidence=csp[:200], severity="low")
262
+ if (
263
+ is_html
264
+ and "frame-ancestors" not in csp
265
+ and h.get("x-frame-options", "").upper() not in ("DENY", "SAMEORIGIN")
266
+ ):
267
+ self.add("frame", "Neither frame-ancestors nor X-Frame-Options prevents framing.")
268
+ if h.get("x-content-type-options", "").lower() != "nosniff":
269
+ self.add("nosniff", "X-Content-Type-Options: nosniff is not sent.")
270
+ if not h.get("referrer-policy"):
271
+ self.add("referrer", "Referrer-Policy is not sent.")
272
+ if is_html and not h.get("permissions-policy"):
273
+ self.add("permissions", "Permissions-Policy is not sent.")
274
+ for name in ("server", "x-powered-by", "x-aspnet-version", "x-aspnetmvc-version", "x-generator"):
275
+ v = h.get(name, "")
276
+ if re.search(r"\d+\.\d+", v):
277
+ self.add("disclosure", f"{name}: {v}", evidence=f"{name}: {v}")
278
+
279
+ def check_cookies(self, r: Response) -> None:
280
+ for k, v in r.header_list:
281
+ if k.lower() != "set-cookie":
282
+ continue
283
+ name = v.split("=", 1)[0].strip()
284
+ attrs = v.lower()
285
+ missing = [flag for flag, present in (("Secure", "; secure" in attrs or self.scheme != "https"),
286
+ ("HttpOnly", "; httponly" in attrs), ("SameSite", "samesite=" in attrs)) if not present] # fmt: skip
287
+ if missing:
288
+ sensitive = bool(re.search(r"(?i)sess|auth|token|jwt|sid|login|remember", name))
289
+ self.add("cookie", f"Cookie '{name}' lacks {', '.join(missing)}.", evidence=f"Set-Cookie: {name}=...",
290
+ severity="medium" if sensitive else "low", confidence="high" if sensitive else "medium") # fmt: skip
291
+
292
+ def check_cors(self) -> None:
293
+ evil = f"https://aw-{self.marker}.example"
294
+ for origin in (evil, "null"):
295
+ r = self.fetch(self.path, headers={"Origin": origin})
296
+ if r is None:
297
+ continue
298
+ acao = r.headers.get("access-control-allow-origin", "")
299
+ creds = r.headers.get("access-control-allow-credentials", "").lower() == "true"
300
+ if acao == origin:
301
+ self.add("cors", f"Origin '{origin}' is reflected{' with credentials allowed' if creds else ''}.",
302
+ evidence=f"Access-Control-Allow-Origin: {acao}", severity="critical" if creds else "high") # fmt: skip
303
+ return
304
+ if acao == "*" and creds:
305
+ self.add("cors", "Wildcard origin combined with credentials.", evidence="ACAO: * / ACAC: true")
306
+ return
307
+
308
+ def check_methods(self) -> None:
309
+ r = self.fetch(self.path, "TRACE", headers={"X-Aw-Probe": self.marker})
310
+ if r is not None and r.status == 200 and self.marker in r.text():
311
+ self.add("trace", "TRACE echoes requests back.", evidence="HTTP 200 with echoed header")
312
+
313
+ def check_exposures(self, not_found: Response | None) -> None:
314
+ soft404 = not_found is not None and not_found.status == 200
315
+ for path, sig, sev, desc in EXPOSURES:
316
+ r = self.fetch(path)
317
+ if r is None or r.status != 200 or not r.body:
318
+ continue
319
+ body = r.body[:200_000].decode("latin-1")
320
+ if not re.search(sig, body):
321
+ continue
322
+ if soft404 and not_found is not None and body == not_found.body.decode("latin-1"):
323
+ continue
324
+ key = "exposed"
325
+ self.add(key, f"{path} is publicly readable: {desc}.", path, severity=sev,
326
+ evidence=re.sub(r"(?i)(password|secret|key|token)([=:]\s*)\S+", r"\1\2****", body[:160])) # fmt: skip
327
+ for path, sig in DEBUG_CONSOLES:
328
+ r = self.fetch(path)
329
+ if r is not None and r.status == 200 and re.search(sig, r.text()[:100_000]):
330
+ self.add("debugger", f"{path} serves a debugging console.", path)
331
+ r = self.fetch("/.well-known/security.txt")
332
+ if r is None or r.status != 200 or "contact:" not in r.text().lower():
333
+ self.add("securitytxt", "No /.well-known/security.txt with a Contact field.", "/.well-known/security.txt")
334
+ for path in ("/static/", "/uploads/", "/assets/", "/files/", "/images/"):
335
+ r = self.fetch(path)
336
+ if (
337
+ r is not None
338
+ and r.status == 200
339
+ and re.search(r"(?:<title>|<h1>)Index of /|Directory listing for /", r.text()[:20_000])
340
+ ):
341
+ self.add("listing", f"{path} lists its contents.", path)
342
+ break
343
+
344
+ def check_errors(self) -> None:
345
+ for path in (f"/aw-{self.marker}'\"%3C%3E", f"/?id=aw'{self.marker}\"", "/%00"):
346
+ r = self.fetch(path)
347
+ if r is None:
348
+ continue
349
+ m = ERROR_MARKERS.search(r.text()[:200_000])
350
+ if m:
351
+ sev = "critical" if "Werkzeug Debugger" in m.group(0) else "medium"
352
+ self.add("errors", "An error page reveals internal details.", path, severity=sev, evidence=m.group(0))
353
+ return
354
+
355
+ def check_redirects(self) -> None:
356
+ evil = f"https://aw-{self.marker}.example/"
357
+ for param in (
358
+ "next",
359
+ "url",
360
+ "redirect",
361
+ "redirect_uri",
362
+ "return",
363
+ "returnTo",
364
+ "return_url",
365
+ "continue",
366
+ "dest",
367
+ "target",
368
+ ):
369
+ r = self.fetch(f"{self.path}?{urlencode({param: evil})}")
370
+ if r is None:
371
+ continue
372
+ loc = r.headers.get("location", "")
373
+ if r.status in (301, 302, 303, 307, 308) and urlsplit(loc).hostname == urlsplit(evil).hostname:
374
+ self.add("redirect", f"The '{param}' parameter redirects to any site.", f"{self.path}?{param}=",
375
+ evidence=f"Location: {loc}") # fmt: skip
376
+ return
377
+
378
+ def check_reflection(self) -> None:
379
+ probe = f"aw{self.marker}<i>\"'"
380
+ for param in ("q", "search", "query", "s", "name"):
381
+ r = self.fetch(f"{self.path}?{urlencode({param: probe})}")
382
+ if r is None or "html" not in r.headers.get("content-type", ""):
383
+ continue
384
+ if probe in r.text():
385
+ self.add("reflect", f"The '{param}' parameter is reflected without HTML encoding.", f"{self.path}?{param}=",
386
+ confidence="medium", evidence=probe) # fmt: skip
387
+ return
388
+
389
+ def check_graphql(self) -> None:
390
+ for path in ("/graphql", "/api/graphql"):
391
+ if self.requests >= self.max_requests:
392
+ return
393
+ self.requests += 1
394
+ time.sleep(self.delay)
395
+ try:
396
+ r = self.http.post_json(self.base + path, {"query": "{__schema{queryType{name}}}"})
397
+ except (OSError, ValueError):
398
+ continue
399
+ if r.status == 200 and "__schema" in r.text() and "queryType" in r.text():
400
+ self.add("graphql", f"{path} answers introspection queries.", path)
401
+ return
402
+
403
+
404
+ def run(target: str, **kw) -> tuple[list[Finding], dict[str, Any]]:
405
+ return PenTest(target, **kw).run()
auditwright/py.typed ADDED
File without changes
@@ -0,0 +1 @@
1
+ """Report renderers."""
@@ -0,0 +1,220 @@
1
+ """Machine and text report formats: JSON, SARIF 2.1.0, JUnit XML, CSV, Markdown and terminal text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import json
8
+ from collections import Counter
9
+ from xml.sax.saxutils import escape as xml_escape
10
+
11
+ from .._util import safe_term
12
+ from .._version import __version__
13
+ from ..model import CATEGORIES, RANK, SEVERITIES, Report, score
14
+
15
+ SECURITY_SEVERITY = {"critical": "9.5", "high": "8.0", "medium": "5.5", "low": "3.0", "info": "0.0"}
16
+ SARIF_LEVEL = {"critical": "error", "high": "error", "medium": "warning", "low": "note", "info": "note"}
17
+
18
+
19
+ def to_json(report: Report) -> str:
20
+ return json.dumps(report.to_dict(), indent=2, default=str)
21
+
22
+
23
+ def to_sarif(report: Report) -> str:
24
+ rules: dict[str, dict] = {}
25
+ results = []
26
+ for f in report.sorted_findings():
27
+ if not f.file or "://" in f.file:
28
+ continue # SARIF consumers need a repository file location
29
+ if f.rule_id not in rules:
30
+ rules[f.rule_id] = {
31
+ "id": f.rule_id,
32
+ "name": "".join(w.capitalize() for w in f.title.replace("-", " ").split() if w.isalnum())[:80]
33
+ or f.rule_id,
34
+ "shortDescription": {"text": f.title},
35
+ "fullDescription": {"text": f.fix or f.title},
36
+ "help": {"text": f.fix or f.title, "markdown": f"**Fix:** {f.fix}" if f.fix else f.title},
37
+ "properties": {
38
+ "security-severity": SECURITY_SEVERITY[f.severity],
39
+ "tags": ["security", f.category, *([f.cwe] if f.cwe else []), *([f.owasp] if f.owasp else [])],
40
+ "precision": {"high": "high", "medium": "medium", "low": "low"}.get(f.confidence, "medium"),
41
+ },
42
+ }
43
+ region = {"startLine": max(1, f.line)}
44
+ if f.column:
45
+ region["startColumn"] = f.column
46
+ results.append(
47
+ {
48
+ "ruleId": f.rule_id,
49
+ "level": SARIF_LEVEL[f.severity],
50
+ "message": {"text": f.message},
51
+ "locations": [
52
+ {"physicalLocation": {"artifactLocation": {"uri": f.file.replace("\\", "/")}, "region": region}}
53
+ ],
54
+ "partialFingerprints": {"auditwright/v1": f.fingerprint},
55
+ "properties": {"severity": f.severity, "confidence": f.confidence},
56
+ }
57
+ )
58
+ doc = {
59
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
60
+ "version": "2.1.0",
61
+ "runs": [
62
+ {
63
+ "tool": {
64
+ "driver": {
65
+ "name": "auditwright",
66
+ "version": __version__,
67
+ "informationUri": "https://github.com/shah2017/auditwright",
68
+ "rules": list(rules.values()),
69
+ }
70
+ },
71
+ "results": results,
72
+ }
73
+ ],
74
+ }
75
+ return json.dumps(doc, indent=2)
76
+
77
+
78
+ def to_junit(report: Report, fail_on: str = "medium") -> str:
79
+ """Findings as failing test cases (one suite per category), plus executed test runs."""
80
+ out = ['<?xml version="1.0" encoding="UTF-8"?>', f'<testsuites name="auditwright" tests="{len(report.findings)}">']
81
+ for cat, items in report.by_category().items():
82
+ failing = [f for f in items if RANK[f.severity] >= RANK[fail_on]]
83
+ out.append(
84
+ f' <testsuite name="{xml_escape(CATEGORIES.get(cat, cat))}" tests="{len(items)}" failures="{len(failing)}">'
85
+ )
86
+ for f in items:
87
+ name = xml_escape(f"{f.rule_id} {f.file}:{f.line}", {'"': "&quot;"})
88
+ out.append(f' <testcase classname="auditwright.{xml_escape(cat)}" name="{name}">')
89
+ body = xml_escape(f"{f.message}\n{f.snippet}\nFix: {f.fix}")
90
+ tag = "failure" if RANK[f.severity] >= RANK[fail_on] else "skipped"
91
+ msg = xml_escape(f"[{f.severity}] {f.title}", {'"': "&quot;"})
92
+ out.append(f' <{tag} message="{msg}">{body}</{tag}>')
93
+ out.append(" </testcase>")
94
+ out.append(" </testsuite>")
95
+ for run in report.test_runs:
96
+ c = run.counts()
97
+ out.append(
98
+ f' <testsuite name="{xml_escape(run.framework)}" tests="{len(run.cases)}" failures="{c["failed"]}" errors="{c["error"]}" time="{run.duration:.3f}">'
99
+ )
100
+ for t in run.cases:
101
+ out.append(
102
+ f' <testcase classname="{xml_escape(t.classname, {chr(34): "&quot;"})}" name="{xml_escape(t.name, {chr(34): "&quot;"})}" time="{t.time:.3f}">'
103
+ )
104
+ if t.status in ("failed", "error"):
105
+ out.append(f' <failure message="{t.status}">{xml_escape(t.message)}</failure>')
106
+ elif t.status == "skipped":
107
+ out.append(" <skipped/>")
108
+ out.append(" </testcase>")
109
+ out.append(" </testsuite>")
110
+ out.append("</testsuites>")
111
+ return "\n".join(out) + "\n"
112
+
113
+
114
+ def _csv_safe(v: object) -> str:
115
+ """Neutralise spreadsheet formula injection (CWE-1236)."""
116
+ s = str(v)
117
+ return "'" + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s
118
+
119
+
120
+ def to_csv(report: Report) -> str:
121
+ buf = io.StringIO()
122
+ w = csv.writer(buf)
123
+ cols = [
124
+ "severity",
125
+ "confidence",
126
+ "category",
127
+ "rule_id",
128
+ "title",
129
+ "file",
130
+ "line",
131
+ "message",
132
+ "cwe",
133
+ "owasp",
134
+ "fix",
135
+ "fingerprint",
136
+ ]
137
+ w.writerow(cols)
138
+ for f in report.sorted_findings():
139
+ w.writerow([_csv_safe(getattr(f, c)) for c in cols])
140
+ return buf.getvalue()
141
+
142
+
143
+ def to_markdown(report: Report, limit: int = 200) -> str:
144
+ counts = report.counts()
145
+ sc = score(report)
146
+ md = [f"# Security and quality report: {report.target}", ""]
147
+ md.append(
148
+ f"**Grade {sc['grade']}** (score {sc['score']}/100) · "
149
+ + " · ".join(f"{s}: **{counts[s]}**" for s in reversed(SEVERITIES) if counts[s])
150
+ )
151
+ md.append("")
152
+ md.append(
153
+ f"_auditwright {report.tool_version} · {report.finished or report.started} · analyzers: {', '.join(report.analyzers)}_"
154
+ )
155
+ if report.errors:
156
+ md += ["", "**Incomplete checks:** " + "; ".join(report.errors)]
157
+ md += ["", "| Area | Findings |", "|---|---|"]
158
+ for cat, items in report.by_category().items():
159
+ c = Counter(f.severity for f in items)
160
+ md.append(
161
+ f"| {CATEGORIES.get(cat, cat)} | " + ", ".join(f"{c[s]} {s}" for s in reversed(SEVERITIES) if c[s]) + " |"
162
+ )
163
+ md += ["", "## Findings", "", "| Severity | Finding | Location | Fix |", "|---|---|---|---|"]
164
+ for f in report.sorted_findings()[:limit]:
165
+ loc = f"`{f.file}:{f.line}`" if f.line else (f"`{f.file}`" if f.file else "")
166
+ msg = f.message.replace("|", "\\|").replace("\n", " ")[:300]
167
+ md.append(f"| {f.severity} | **{f.title}** ({f.rule_id}): {msg} | {loc} | {f.fix.replace('|', '/')[:200]} |")
168
+ if len(report.findings) > limit:
169
+ md.append(f"\n_{len(report.findings) - limit} more findings in the JSON/HTML report._")
170
+ vulnerable = [d for d in report.dependencies if d.get("vulns")]
171
+ if report.dependencies:
172
+ md += [
173
+ "",
174
+ "## Dependencies",
175
+ "",
176
+ f"{len(report.dependencies)} packages, {len(vulnerable)} with known vulnerabilities.",
177
+ ]
178
+ for run in report.test_runs:
179
+ c = run.counts()
180
+ md.append(f"\n**Tests ({run.framework}):** {c['passed']} passed, {c['failed']} failed, {c['error']} errors, {c['skipped']} skipped"
181
+ + (f", coverage {run.coverage:.1f}%" if run.coverage is not None else "")) # fmt: skip
182
+ return "\n".join(md) + "\n"
183
+
184
+
185
+ COLORS = {"critical": "\033[1;35m", "high": "\033[1;31m", "medium": "\033[33m", "low": "\033[36m", "info": "\033[2m"}
186
+
187
+
188
+ def to_text(report: Report, *, color: bool = False, limit: int = 60, min_severity: str = "low") -> str:
189
+ def c(sev: str, s: str) -> str:
190
+ return f"{COLORS[sev]}{s}\033[0m" if color else s
191
+
192
+ counts = report.counts()
193
+ sc = score(report)
194
+ lines = [f"auditwright {report.tool_version}: {report.target}", ""]
195
+ shown = [f for f in report.sorted_findings() if RANK[f.severity] >= RANK[min_severity]]
196
+ for cat, items in report.by_category().items():
197
+ items = [f for f in items if f in shown]
198
+ if not items:
199
+ continue
200
+ lines.append(CATEGORIES.get(cat, cat))
201
+ for f in items[:limit]:
202
+ loc = f"{f.file}:{f.line}" if f.line else f.file
203
+ lines.append(f" {c(f.severity, f.severity.upper().ljust(8))} {f.rule_id:<11} {safe_term(loc, 90)}")
204
+ lines.append(f" {safe_term(f.message, 200)}")
205
+ if len(items) > limit:
206
+ lines.append(f" ... {len(items) - limit} more")
207
+ lines.append("")
208
+ for run in report.test_runs:
209
+ cnt = run.counts()
210
+ status = "ok" if run.exit_code == 0 else "FAILED" if run.exit_code is not None else "NOT RUN"
211
+ cov = f", coverage {run.coverage:.1f}%" if run.coverage is not None else ""
212
+ lines.append(f"Tests [{run.framework}] {status}: {cnt['passed']} passed, {cnt['failed']} failed, {cnt['error']} errors{cov}"
213
+ + (f" ({run.error})" if run.error else "")) # fmt: skip
214
+ if report.errors:
215
+ lines.append("Incomplete: " + "; ".join(report.errors))
216
+ summary = " ".join(f"{s}={counts[s]}" for s in reversed(SEVERITIES))
217
+ lines.append(
218
+ f"Grade {sc['grade']} (score {sc['score']}/100) {summary} suppressed={report.suppressed} baseline={report.baseline_matched}"
219
+ )
220
+ return "\n".join(lines)