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.
@@ -0,0 +1,136 @@
1
+ """Rule registry and the line-oriented pattern engine.
2
+
3
+ Pattern rules run per line (so every regex sees bounded input and the scan stays
4
+ linear in file size), skip comment lines for the file's language, and honour
5
+ inline suppressions::
6
+
7
+ risky_call() # auditwright: ignore[AW-PY-001]
8
+ risky_call() // auditwright: ignore
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Iterable, Iterator
15
+ from dataclasses import dataclass
16
+
17
+ from ..model import Finding, RuleMeta
18
+ from ..walk import SourceFile
19
+
20
+ REGISTRY: dict[str, RuleMeta] = {}
21
+
22
+ _SUPPRESS = re.compile(r"auditwright:\s*ignore(?:\[([A-Za-z0-9_,\- ]+)\])?")
23
+
24
+ COMMENT_PREFIXES = {
25
+ "Python": ("#",),
26
+ "Shell": ("#",),
27
+ "PowerShell": ("#",),
28
+ "Ruby": ("#",),
29
+ "YAML": ("#",),
30
+ "Terraform": ("#", "//"),
31
+ "Elixir": ("#",),
32
+ "R": ("#",),
33
+ "Dockerfile": ("#",),
34
+ "SQL": ("--",),
35
+ "Lua": ("--",),
36
+ "HTML": ("<!--",),
37
+ }
38
+ _C_STYLE = ("//", "/*", "*")
39
+
40
+
41
+ def register(meta: RuleMeta) -> RuleMeta:
42
+ if meta.id in REGISTRY and REGISTRY[meta.id] != meta:
43
+ raise ValueError(f"duplicate rule id {meta.id}")
44
+ REGISTRY[meta.id] = meta
45
+ return meta
46
+
47
+
48
+ def is_comment(line: str, language: str) -> bool:
49
+ s = line.lstrip()
50
+ if not s:
51
+ return True
52
+ prefixes = COMMENT_PREFIXES.get(language, _C_STYLE)
53
+ return s.startswith(prefixes)
54
+
55
+
56
+ def suppressed(line: str, rule_id: str) -> bool:
57
+ m = _SUPPRESS.search(line)
58
+ if not m:
59
+ return False
60
+ if not m.group(1):
61
+ return True
62
+ return rule_id in {x.strip() for x in m.group(1).split(",")}
63
+
64
+
65
+ def snippet(line: str) -> str:
66
+ return line.strip()[:240]
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class PatternRule:
71
+ meta: RuleMeta
72
+ languages: frozenset[str]
73
+ pattern: re.Pattern[str]
74
+ message: str
75
+ unless: re.Pattern[str] | None = None
76
+ confidence: str = "medium"
77
+ files: re.Pattern[str] | None = None # optional filter on the relative path
78
+
79
+ def applies(self, f: SourceFile) -> bool:
80
+ if self.languages and f.language not in self.languages:
81
+ return False
82
+ return not (self.files and not self.files.search(f.rel))
83
+
84
+
85
+ def pattern_rule(
86
+ rule_id: str,
87
+ title: str,
88
+ category: str,
89
+ severity: str,
90
+ languages: Iterable[str],
91
+ pattern: str,
92
+ message: str,
93
+ *,
94
+ cwe: str = "",
95
+ owasp: str = "",
96
+ fix: str = "",
97
+ unless: str | None = None,
98
+ confidence: str = "medium",
99
+ files: str | None = None,
100
+ flags: int = 0,
101
+ ) -> PatternRule:
102
+ meta = register(RuleMeta(rule_id, title, category, severity, cwe, owasp, fix, message))
103
+ return PatternRule(
104
+ meta,
105
+ frozenset(languages),
106
+ re.compile(pattern, flags),
107
+ message,
108
+ re.compile(unless, flags) if unless else None,
109
+ confidence,
110
+ re.compile(files) if files else None,
111
+ )
112
+
113
+
114
+ def run_patterns(rules: list[PatternRule], files: Iterable[SourceFile]) -> Iterator[Finding]:
115
+ for f in files:
116
+ applicable = [r for r in rules if r.applies(f)]
117
+ if not applicable:
118
+ continue
119
+ for lineno, line in enumerate(f.lines(), 1):
120
+ if len(line) > 4000: # minified bundles: not human-written code
121
+ continue
122
+ if is_comment(line, f.language):
123
+ continue
124
+ for r in applicable:
125
+ m = r.pattern.search(line)
126
+ if not m or (r.unless and r.unless.search(line)) or suppressed(line, r.meta.id):
127
+ continue
128
+ yield Finding.from_rule(
129
+ r.meta,
130
+ r.message,
131
+ file=f.rel,
132
+ line=lineno,
133
+ column=m.start() + 1,
134
+ snippet=snippet(line),
135
+ confidence=r.confidence,
136
+ )
@@ -0,0 +1,101 @@
1
+ """Cryptography inventory and post-quantum readiness.
2
+
3
+ Every public-key algorithm that a large quantum computer breaks with Shor's
4
+ algorithm (RSA, elliptic-curve and finite-field Diffie-Hellman, DSA, ECDSA,
5
+ EdDSA) is inventoried, so teams can plan migration to the NIST post-quantum
6
+ standards (ML-KEM / FIPS 203, ML-DSA / FIPS 204, SLH-DSA / FIPS 205). Key
7
+ exchange matters most today because recorded traffic can be decrypted later
8
+ ("harvest now, decrypt later").
9
+
10
+ Weak primitives (DES, RC4, ECB mode, short RSA keys) are reported as findings.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections.abc import Iterator
17
+ from typing import Any
18
+
19
+ from ..model import Finding, RuleMeta
20
+ from ..walk import CODE_LANGUAGES, SourceFile
21
+ from .base import is_comment, register, snippet, suppressed
22
+
23
+ A02 = "A02:2021 Cryptographic Failures"
24
+
25
+ PQ = register(RuleMeta("AW-PQ-001", "Quantum-vulnerable public-key cryptography", "crypto", "info", "CWE-327", A02,
26
+ "Plan migration to hybrid or pure post-quantum schemes (ML-KEM for key exchange, ML-DSA or SLH-DSA for signatures); prioritise key exchange protecting long-lived secrets.")) # fmt: skip
27
+ WEAK = register(RuleMeta("AW-CRY-001", "Broken or weak cipher", "crypto", "high", "CWE-327", A02,
28
+ "Use AES-GCM or ChaCha20-Poly1305.")) # fmt: skip
29
+ ECB = register(RuleMeta("AW-CRY-002", "ECB block cipher mode", "crypto", "medium", "CWE-327", A02,
30
+ "Use an authenticated mode such as GCM with a unique nonce per message.")) # fmt: skip
31
+ SHORTKEY = register(RuleMeta("AW-CRY-003", "RSA key shorter than 2048 bits", "crypto", "high", "CWE-326", A02,
32
+ "Use at least 3072-bit RSA, or better, elliptic-curve keys now and post-quantum schemes next.")) # fmt: skip
33
+ STATIC_IV = register(RuleMeta("AW-CRY-004", "Hard-coded IV or nonce", "crypto", "medium", "CWE-329", A02,
34
+ "Generate a fresh random IV/nonce for every encryption.")) # fmt: skip
35
+
36
+ FAMILIES: list[tuple[str, str, bool, re.Pattern[str]]] = [
37
+ # (family, use, quantum_vulnerable, pattern)
38
+ ("RSA", "encryption/signatures", True, re.compile(
39
+ r"rsa\.generate_private_key|RSA\.generate|RSA\.import_key|KeyPairGenerator\.getInstance\(\s*\"RSA|generateKeyPair(?:Sync)?\(\s*['\"]rsa|"
40
+ r"rsa\.GenerateKey|PKCS1v15|padding\.OAEP|RSAPublicKey|RSA_PKCS1|\"RS(?:256|384|512)\"|'RS(?:256|384|512)'|RSACryptoServiceProvider|RSA\.Create\(")),
41
+ ("ECDSA/ECDH", "signatures/key exchange", True, re.compile(
42
+ r"ec\.generate_private_key|ec\.SECP\d+|SECP(?:256|384|521)[KR]1|secp256k1|prime256v1|\bP-(?:256|384|521)\b|ecdsa\.GenerateKey|"
43
+ r"elliptic\.P(?:256|384|521)|ECDH\b|ecdh\.|\"ES(?:256|384|512)\"|'ES(?:256|384|512)'|ECDsa\.Create|KeyPairGenerator\.getInstance\(\s*\"EC")),
44
+ ("EdDSA/X25519", "signatures/key exchange", True, re.compile(r"Ed25519|Ed448|X25519|X448|ed25519\.|curve25519|nacl\.signing|nacl\.public|\"EdDSA\"")),
45
+ ("Diffie-Hellman/DSA", "key exchange/signatures", True, re.compile(r"\bdh\.generate_parameters|DiffieHellman|createDiffieHellman|dsa\.generate_private_key|\bDSA\.generate|KeyPairGenerator\.getInstance\(\s*\"DSA")),
46
+ ("Post-quantum (ML-KEM/ML-DSA/SLH-DSA)", "post-quantum", False, re.compile(r"(?i)ML-?KEM|Kyber\d*|ML-?DSA|Dilithium|SLH-?DSA|SPHINCS|\bliboqs\b|\boqs\.|X25519MLKEM768|X25519Kyber768")),
47
+ ("AES", "symmetric encryption", False, re.compile(r"\bAES(?:GCM|SIV|CCM)?\b|algorithms\.AES|aes-(?:128|192|256)|createCipheriv\(\s*['\"]aes")),
48
+ ("ChaCha20-Poly1305", "symmetric encryption", False, re.compile(r"(?i)chacha20")),
49
+ ] # fmt: skip
50
+
51
+ _WEAK = re.compile(
52
+ r"\b(?:DES|DES3|ARC4|ARC2|Blowfish|CAST)\.new\(|algorithms\.(?:TripleDES|ARC4|Blowfish|IDEA|CAST5)\b|getInstance\(\s*\"(?:DES|DESede|RC4|RC2|Blowfish)[\"/]|createCipheriv\(\s*['\"](?:des|rc4|bf|rc2)|\b(?:des|rc4)\.NewCipher|\b(?:RC4|TripleDES|DES|RC2)\.Create\("
53
+ ) # auditwright: ignore
54
+ _ECB = re.compile(r"MODE_ECB|modes\.ECB\(|/ECB/|-ecb['\"]|aes-\d+-ecb", re.I) # auditwright: ignore
55
+ _SHORT = re.compile(
56
+ r"(?:key_size\s*=\s*|RSA\.generate\(\s*|modulusLength\s*:\s*|GenerateKey\([^,]*,\s*|initialize\(\s*)(512|768|1024|1536)\b"
57
+ )
58
+ _STATIC_IV = re.compile(
59
+ r"(?i)\b(?:iv|nonce)\s*=\s*(?:b?[\"'][^\"']{8,}[\"']|bytes\(\s*\d+\s*\)|new\s+byte\[\s*\d+\s*\]|Buffer\.alloc\(\s*\d+\s*\))"
60
+ )
61
+
62
+
63
+ def analyze(files: list[SourceFile]) -> tuple[list[Finding], list[dict[str, Any]]]:
64
+ findings: list[Finding] = []
65
+ inventory: dict[tuple[str, str], dict[str, Any]] = {}
66
+ for f in files:
67
+ if f.language not in CODE_LANGUAGES:
68
+ continue
69
+ reported_pq: set[str] = set()
70
+ for i, line in enumerate(f.lines(), 1):
71
+ if len(line) > 4000 or is_comment(line, f.language):
72
+ continue
73
+ for family, use, vulnerable, rx in FAMILIES:
74
+ if rx.search(line):
75
+ key = (family, f.rel)
76
+ entry = inventory.setdefault(
77
+ key,
78
+ {"family": family, "use": use, "quantum_vulnerable": vulnerable, "file": f.rel, "lines": []},
79
+ )
80
+ if len(entry["lines"]) < 20:
81
+ entry["lines"].append(i)
82
+ if vulnerable and family not in reported_pq and not suppressed(line, PQ.id):
83
+ reported_pq.add(family)
84
+ findings.append(Finding.from_rule(
85
+ PQ, f"{family} ({use}) will be breakable by a cryptographically relevant quantum computer.",
86
+ file=f.rel, line=i, snippet=snippet(line), confidence="medium",
87
+ )) # fmt: skip
88
+ for rule, rx, msg in (
89
+ (WEAK, _WEAK, "A broken cipher is used."),
90
+ (ECB, _ECB, "ECB mode leaks patterns in the plaintext."),
91
+ (SHORTKEY, _SHORT, "The RSA modulus is too short to resist factoring."),
92
+ (STATIC_IV, _STATIC_IV, "A constant IV/nonce breaks the cipher's security guarantees."),
93
+ ):
94
+ if rx.search(line) and not suppressed(line, rule.id):
95
+ findings.append(Finding.from_rule(rule, msg, file=f.rel, line=i, snippet=snippet(line),
96
+ confidence="medium")) # fmt: skip
97
+ return findings, sorted(inventory.values(), key=lambda e: (not e["quantum_vulnerable"], e["family"], e["file"]))
98
+
99
+
100
+ def iter_findings(files: list[SourceFile]) -> Iterator[Finding]:
101
+ yield from analyze(files)[0]