-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeCleanse.py
More file actions
124 lines (107 loc) · 6.22 KB
/
Copy pathCodeCleanse.py
File metadata and controls
124 lines (107 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import sys
import re
import math
import os
# Ultra-modern, rich RGB 24-bit color palette
class Colors:
# Smooth, premium gradient tones
BRAND = '\033[38;2;139;92;246m' # Soft Royal Purple
INFO = '\033[38;2;56;189;248m' # Ice Cyan
SUCCESS = '\033[38;2;52;211;153m' # Sage Mint Green
WARNING = '\033[38;2;251;191;36m' # Amber Gold
FAIL = '\033[38;2;248;113;113m' # Soft Coral Red
MUTED = '\033[38;2;156;163;175m' # Platinum Gray
# Text styles
ENDC = '\033[0m'
BOLD = '\033[1m'
DIM = '\033[2m'
def calculate_shannon_entropy(data):
"""
Calculates the information entropy of a string.
High entropy strings (random looking) usually indicate API keys or passwords.
"""
if not data:
return 0
entropy = 0
for x in range(256):
p_x = float(data.count(chr(x))) / len(data)
if p_x > 0:
entropy += - p_x * math.log(p_x, 2)
return entropy
def scan_line(line, line_num, file_path):
"""
Scans an individual line using a multi-layer regular expression matrix
and predictive entropy thresholds.
"""
findings = []
patterns = {
"Potential API Key / Secret Token": r'(?i)(api_key|secret|password|passwd|auth_token|access_token|private_key)\s*=\s*[\'"][^\'"]+[\'"]',
"Hardcoded Database Connection String": r'(?i)(mongodb\+srv|mysql|postgresql)://[^\s]+',
"Exposed Standard AWS Token Pattern": r'AKIA[0-9A-Z]{16}',
}
for issue_type, pattern in patterns.items():
if re.search(pattern, line):
findings.append({
"file": file_path,
"line": line_num,
"type": issue_type,
"content": line.strip(),
"severity": "CRITICAL"
})
strings_in_line = re.findall(r'[\'"]([^\'"]{12,})[\'"]', line)
for string in strings_in_line:
entropy = calculate_shannon_entropy(string)
if entropy > 4.5:
findings.append({
"file": file_path,
"line": line_num,
"type": f"High Entropy Key Structure (Score: {entropy:.2f})",
"content": string,
"severity": "RISK"
})
return findings
def execute_pre_commit_scan():
# Elegant custom header design
print(f"\n{Colors.BRAND}{Colors.BOLD}┌──────────────────────────────────────────────┐")
print(f"│ 🛡️ C O D E C L E A N S E │")
print(f"│ DevSecOps Local Repository Gatekeeper │")
print(f"└──────────────────────────────────────────────┘{Colors.ENDC}")
print(f"{Colors.INFO} » Commencing predictive static-analysis matrix...{Colors.ENDC}\n")
all_vulnerabilities = []
target_extensions = ('.py', '.js', '.json', '.env', '.yml', '.txt', '.conf')
for root, dirs, files in os.walk('.'):
if '.git' in root:
continue
for file in files:
if file.endswith(target_extensions) and file.lower()!= 'codecleanse.py':
file_path = os.path.join(root, file)
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
for idx, line in enumerate(f, 1):
issues = scan_line(line, idx, file_path)
if issues:
all_vulnerabilities.extend(issues)
except Exception as e:
pass
if all_vulnerabilities:
print(f" {Colors.FAIL}{Colors.BOLD}✕ DEPLOYMENT BLOCKED: Action Required{Colors.ENDC}")
print(f" {Colors.MUTED}The following operational data exposures must be resolved before committing:{Colors.ENDC}\n")
# Sleek, clean table architecture
print(f" {Colors.BOLD}{Colors.MUTED}┌──────────────────────┬──────┬─────────────────────────────────────┬──────────┐{Colors.ENDC}")
print(f" {Colors.BOLD}{Colors.MUTED}│ Source File │ Line │ Threat Classification │ Status │{Colors.ENDC}")
print(f" {Colors.BOLD}{Colors.MUTED}├──────────────────────┼──────┼─────────────────────────────────────┼──────────┐{Colors.ENDC}")
for issue in all_vulnerabilities:
clean_file = issue['file'].replace('.\\', '')[:20]
status_color = Colors.FAIL if issue['severity'] == "CRITICAL" else Colors.WARNING
print(f" {Colors.MUTED}│{Colors.ENDC} {clean_file:<20} {Colors.MUTED}│{Colors.ENDC} {issue['line']:<4} {Colors.MUTED}│{Colors.ENDC} {issue['type'][:35]:<35} {Colors.MUTED}│{Colors.ENDC} {status_color}{issue['severity']:<8}{Colors.ENDC} {Colors.MUTED}│{Colors.ENDC}")
print(f" {Colors.MUTED}│{Colors.ENDC} {Colors.DIM}↳ Raw Leak Variant:{Colors.ENDC} {Colors.WARNING}{issue['content'][:52]}{Colors.ENDC}")
print(f" {Colors.BOLD}{Colors.MUTED}├──────────────────────┼──────┼─────────────────────────────────────┼──────────┐{Colors.ENDC}")
print(f"\n 📊 {Colors.BOLD}Summary Assessment: Found {Colors.FAIL}{len(all_vulnerabilities)}{Colors.ENDC} policy violations.{Colors.ENDC}\n")
sys.exit(1)
else:
print(f" {Colors.SUCCESS}{Colors.BOLD}✔ INTELLIGENT SCAN PASSED CLEANLY{Colors.ENDC}")
print(f" {Colors.MUTED}No code telemetry leaks or unstructured credentials detected.{Colors.ENDC}")
print(f" {Colors.INFO}Safe infrastructure state verified. Proceeding with Git tracking.{Colors.ENDC}\n")
sys.exit(0)
if __name__ == "__main__":
execute_pre_commit_scan()