-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
255 lines (215 loc) · 9.69 KB
/
Copy pathscanner.py
File metadata and controls
255 lines (215 loc) · 9.69 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
"""
Linux Privilege Escalation Automation Toolkit
Automated security auditing tool for detecting privilege escalation vectors.
For educational and authorized penetration testing use only.
"""
import os
import sys
import subprocess
import platform
import json
import datetime
import argparse
import concurrent.futures
import time
from pathlib import Path
# Import modules
from modules.suid_scanner import SUIDBinaryScanner
from modules.permission_scanner import WeakPermissionScanner
from modules.service_scanner import ServiceScanner
from modules.cron_scanner import CronScanner
from modules.kernel_scanner import KernelScanner
from modules.report_generator import ReportGenerator
# ANSI color codes
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
RESET = '\033[0m'
BANNER = f"""
{Colors.RED}{Colors.BOLD}
██████╗ ██████╗ ██╗██╗ ██╗███████╗███████╗ ██████╗
██╔══██╗██╔══██╗██║██║ ██║██╔════╝██╔════╝██╔════╝
██████╔╝██████╔╝██║██║ ██║█████╗ ███████╗██║
██╔═══╝ ██╔══██╗██║╚██╗ ██╔╝██╔══╝ ╚════██║██║
██║ ██║ ██║██║ ╚████╔╝ ███████╗███████║╚██████╗
╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══════╝╚══════╝ ╚═════╝
{Colors.RESET}
{Colors.CYAN}Linux Privilege Escalation Automation Toolkit v1.0{Colors.RESET}
{Colors.YELLOW}[!] For authorized security auditing and educational use only{Colors.RESET}
"""
def print_section(title):
width = 60
print(f"\n{Colors.BLUE}{Colors.BOLD}{'=' * width}{Colors.RESET}")
print(f"{Colors.BLUE}{Colors.BOLD} {title}{Colors.RESET}")
print(f"{Colors.BLUE}{Colors.BOLD}{'=' * width}{Colors.RESET}")
def collect_system_info():
"""Step 1: Collect basic system information."""
print_section("STEP 1: System Information Collection")
info = {}
# Current user (cross-platform)
info['current_user'] = (
os.environ.get('USER') or
os.environ.get('USERNAME') or
subprocess.getoutput('whoami')
)
# os.getuid() / os.getgid() are Linux-only, not available on Windows
if hasattr(os, 'getuid'):
info['uid'] = os.getuid()
info['gid'] = os.getgid()
info['is_root'] = (info['uid'] == 0)
else:
info['uid'] = 'N/A (Windows)'
info['gid'] = 'N/A (Windows)'
info['is_root'] = False
# Groups
try:
info['groups'] = subprocess.getoutput('id').strip()
except Exception:
info['groups'] = 'Unknown'
# System details
info['hostname'] = platform.node()
info['kernel'] = platform.release()
info['os_info'] = subprocess.getoutput('cat /etc/os-release 2>/dev/null | head -5').strip()
info['uname_full']= subprocess.getoutput('uname -a').strip()
info['home_dir'] = str(Path.home())
info['scan_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Print collected info
status = (f"{Colors.RED}ROOT{Colors.RESET}" if info['is_root']
else f"{Colors.GREEN}Limited User{Colors.RESET}")
print(f" {Colors.WHITE}User :{Colors.RESET} {Colors.BOLD}{info['current_user']}{Colors.RESET} ({status})")
print(f" {Colors.WHITE}UID/GID :{Colors.RESET} {info['uid']} / {info['gid']}")
print(f" {Colors.WHITE}Hostname :{Colors.RESET} {info['hostname']}")
print(f" {Colors.WHITE}Kernel :{Colors.RESET} {info['kernel']}")
print(f" {Colors.WHITE}Groups :{Colors.RESET} {info['groups']}")
print(f" {Colors.WHITE}Scan Time :{Colors.RESET} {info['scan_time']}")
if info['is_root']:
print(f"\n {Colors.YELLOW}[!] Running as root - all checks will execute with full access{Colors.RESET}")
else:
print(f"\n {Colors.GREEN}[*] Running as limited user - some checks may be restricted{Colors.RESET}")
return info
def run_all_scanners(args):
"""Step 2 & 3: Run ALL scanners in PARALLEL for maximum speed."""
scanners = [
("STEP 2a: SUID/SGID Binary Discovery", SUIDBinaryScanner),
("STEP 2b: Weak File & Directory Permissions", WeakPermissionScanner),
("STEP 2c: Misconfigured Services & Sudo", ServiceScanner),
("STEP 2d: Cron Job Vulnerability Scan", CronScanner),
("STEP 2e: Kernel Exploit Detection", KernelScanner),
]
print(f"\n{Colors.CYAN}[*] Running all {len(scanners)} scanners in parallel...{Colors.RESET}")
start = time.time()
results = {}
def run_one(name, cls):
scanner = cls()
findings = scanner.scan()
return name, scanner, findings
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = {executor.submit(run_one, name, cls): name for name, cls in scanners}
for future in concurrent.futures.as_completed(futures):
try:
name, scanner, findings = future.result()
results[name] = (scanner, findings)
except Exception as e:
print(f" {Colors.RED}[!] Scanner error: {e}{Colors.RESET}")
elapsed = time.time() - start
print(f"{Colors.GREEN}[✓] All scans complete in {elapsed:.1f} seconds{Colors.RESET}")
# Print results in original order
all_findings = []
for title, cls in scanners:
if title in results:
scanner, findings = results[title]
print_section(title)
scanner.print_results(findings)
all_findings.extend(findings)
return all_findings
def print_summary(findings, system_info):
"""Print a summary of all findings."""
print_section("STEP 3: Analysis Summary")
high = [f for f in findings if f.get('severity') == 'HIGH']
medium = [f for f in findings if f.get('severity') == 'MEDIUM']
low = [f for f in findings if f.get('severity') == 'LOW']
info = [f for f in findings if f.get('severity') == 'INFO']
print(f"\n Total Findings : {Colors.BOLD}{len(findings)}{Colors.RESET}")
print(f" {Colors.RED}HIGH : {len(high)}{Colors.RESET}")
print(f" {Colors.YELLOW}MEDIUM : {len(medium)}{Colors.RESET}")
print(f" {Colors.GREEN}LOW : {len(low)}{Colors.RESET}")
print(f" {Colors.CYAN}INFO : {len(info)}{Colors.RESET}")
if high:
print(f"\n {Colors.RED}{Colors.BOLD}[!] Critical Issues Found:{Colors.RESET}")
for f in high[:5]:
print(f" {Colors.RED}► {f.get('title', 'Unknown')}{Colors.RESET}")
if len(high) > 5:
print(f" {Colors.RED} ... and {len(high) - 5} more{Colors.RESET}")
return {'high': len(high), 'medium': len(medium), 'low': len(low), 'info': len(info)}
def setup_reports_dir():
"""
Create a 'reports' folder next to scanner.py.
All reports are saved there with timestamps in the filename.
"""
# Always save relative to where scanner.py lives, not cwd
script_dir = Path(__file__).parent.resolve()
reports_dir = script_dir / "reports"
reports_dir.mkdir(exist_ok=True)
return reports_dir
def main():
# Platform check
if platform.system() == 'Windows':
print(f"\n{Colors.YELLOW}{Colors.BOLD}[!] WARNING: Running on Windows.{Colors.RESET}")
print(f"{Colors.YELLOW} This toolkit is designed for Linux systems.")
print(f" Most scans will return no results on Windows.")
print(f" To use properly: run on Linux, WSL, or a VirtualBox VM.")
print(f" Continuing anyway for demonstration...\n{Colors.RESET}")
parser = argparse.ArgumentParser(
description='Linux Privilege Escalation Automation Toolkit',
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--output', '-o',
default=None,
help='Custom report filename (without extension). Default: auto timestamp.'
)
parser.add_argument(
'--format', '-f',
choices=['json', 'txt', 'both'],
default='both',
help='Report output format (default: both)'
)
parser.add_argument(
'--quiet', '-q',
action='store_true',
help='Suppress banner output'
)
args = parser.parse_args()
if not args.quiet:
print(BANNER)
# Step 1: System info
system_info = collect_system_info()
# Steps 2 & 3: Run scanners
all_findings = run_all_scanners(args)
# Summary
counts = print_summary(all_findings, system_info)
# Step 4: Generate report
print_section("STEP 4: Generating Security Report")
# Build output path: reports/privesc_report_YYYY-MM-DD_HH-MM-SS
reports_dir = setup_reports_dir()
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if args.output:
# User gave a custom name — still save inside reports/
report_base = str(reports_dir / args.output)
else:
# Auto timestamped name
hostname = system_info.get('hostname', 'host')
report_name = f"privesc_report_{hostname}_{timestamp}"
report_base = str(reports_dir / report_name)
reporter = ReportGenerator(system_info, all_findings, counts)
reporter.generate(report_base, args.format)
print(f"\n{Colors.CYAN} Reports folder : {reports_dir}{Colors.RESET}")
print(f"{Colors.GREEN}{Colors.BOLD}[✓] Scan complete!{Colors.RESET}\n")
if __name__ == '__main__':
main()