-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_vulnerability_scanner.py
More file actions
1034 lines (916 loc) · 39.8 KB
/
Copy pathweb_vulnerability_scanner.py
File metadata and controls
1034 lines (916 loc) · 39.8 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import contextlib
import html
import io
import json
import os
import socket
import sys
import threading
import webbrowser
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from urllib.parse import urlparse, urlunparse, urlencode, parse_qsl
import requests
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
from tkinter import font as tkfont
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
# Optional: tkvideo provides background video support (install with: pip install tkvideo)
try:
from tkvideo import tkvideo
TKVIDEO_AVAILABLE = True
except ImportError:
TKVIDEO_AVAILABLE = False
DEFAULT_TIMEOUT = 7
DEFAULT_HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) WebVulnScanner/1.0',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.9',
}
custom_payloads = []
scan_results = []
scanning = False
stop_requested = False
ml_model = None
scan_options = {}
current_target_url = ''
root = None # Global Tk root — needed for thread-safe after() scheduling
log_box = None # Global log widget reference
scan_button = None
status_labels = {}
progress_step = 0
progress_total = 0
scan_metrics = {
'hits': 0,
'categories': Counter(),
'severities': Counter(),
'score': 0,
}
severity_classification = {
'SQLi': ('High', 'CVE-2019-1234'),
'XSS': ('Medium', 'CVE-2020-5678'),
'CMD': ('High', 'CVE-2018-9102'),
'HTML-Injection': ('Low', 'CVE-2021-0003'),
'Headers': ('Medium', 'CVE-2022-3456'),
'Port': ('Info', 'N/A'),
'WAF': ('Medium', 'CVE-2024-9999'),
'Discovery': ('Low', 'N/A'),
'Auth': ('High', 'N/A')
}
score_weights = {
'High': 100,
'Medium': 50,
'Low': 20,
'Info': 5,
'Unknown': 10,
}
# Default payload sets used when no custom payloads are imported.
default_payloads = {
'SQLi': ["' OR 1=1 --", "'; DROP TABLE users; --", "1' AND '1'='1'"],
'XSS': ["<script>alert('XSS')</script>", "<img src=x onerror=alert('XSS')>"],
'HTML-Injection': ['<b>Injected</b>', '<h1>Test</h1>', "<input type='text'>"],
'CMD': [';id', '| whoami', '`ls`']
}
scan_parameters = {
'SQLi': 'input',
'XSS': 'input',
'HTML-Injection': 'input',
'CMD': 'cmd'
}
scan_explanations = {
'SQLi': 'SQL Injection Detected',
'XSS': 'Reflected XSS Detected',
'HTML-Injection': 'HTML Injection Detected',
'CMD': 'Command Injection Detected'
}
common_discovery_paths = [
'admin', 'login', 'dashboard', 'api', 'config', 'backup', '.env', 'robots.txt', 'sitemap.xml'
]
common_auth_paths = [
'login', 'admin/login', 'signin', 'accounts/login', 'user/login', 'auth/login'
]
def train_ml_model():
global ml_model
X = [
"' OR 1=1 --", "'; DROP TABLE users; --", "1' AND '1'='1'",
"<script>alert('XSS')</script>", "<img src=x onerror=alert('XSS')>",
"<body><script>alert(1)</script>", "<h1>Test</h1>",
"| cat /etc/passwd", "; ping -c 3 localhost", "`ls -la`",
"uname -a", "curl http://example.com", "hello", "normalinput", "search=python"
]
y = ['SQLi', 'SQLi', 'SQLi', 'XSS', 'XSS', 'XSS', 'HTML-Injection', 'CMD', 'CMD', 'CMD', 'CMD', 'None', 'None', 'None', 'None']
pipeline = Pipeline([
('vectorizer', CountVectorizer()),
('classifier', RandomForestClassifier(n_estimators=100, random_state=42))
])
pipeline.fit(X, y)
ml_model = pipeline
def classify_payload(payload):
if ml_model is None:
return 'Unknown', 0.0
try:
probabilities = ml_model.predict_proba([payload])[0]
best_index = int(probabilities.argmax())
label = ml_model.classes_[best_index]
confidence = float(probabilities[best_index])
if label == 'None' or confidence < 0.35:
return 'None', confidence
return label, confidence
except Exception:
try:
label = ml_model.predict([payload])[0]
return label, 0.0
except Exception:
return 'Unknown', 0.0
def normalize_url(raw_url):
raw_url = raw_url.strip()
if not raw_url:
return raw_url
parsed = urlparse(raw_url)
if not parsed.scheme:
parsed = parsed._replace(scheme='http')
if not parsed.netloc and parsed.path:
parsed = urlparse(f'{parsed.scheme}://{parsed.path}', scheme=parsed.scheme)
if not parsed.netloc:
parsed = urlparse(f'http://{raw_url}', scheme='http')
return urlunparse(parsed)
def ensure_valid_target_url(raw_url):
normalized = normalize_url(raw_url)
parsed = urlparse(normalized)
if parsed.scheme not in ('http', 'https'):
raise ValueError('Target URL must use http or https.')
if not parsed.netloc:
raise ValueError('Target URL is missing a hostname.')
return normalized
def safe_request(method, url, **kwargs):
timeout = kwargs.pop('timeout', DEFAULT_TIMEOUT)
session = requests.Session()
session.headers.update(DEFAULT_HEADERS)
response = session.request(method, url, timeout=timeout, **kwargs)
session.close()
return response
def build_payload_url(base_url, param, payload):
parsed = urlparse(base_url)
query_params = dict(parse_qsl(parsed.query, keep_blank_values=True))
query_params[param] = payload
new_query = urlencode(query_params, doseq=True)
return urlunparse(parsed._replace(query=new_query))
def import_payloads():
global custom_payloads
path = filedialog.askopenfilename(filetypes=[('Text files', '*.txt')])
if path:
with open(path, encoding='utf-8', errors='ignore') as f:
custom_payloads = [l.strip() for l in f if l.strip()]
messagebox.showinfo('Import', f'{len(custom_payloads)} payloads loaded')
def get_severity_score(severity):
return score_weights.get(severity, score_weights['Unknown'])
def enhanced_log(msg, log, category=None):
severity = 'Medium'
cve = 'CVE-2023-XXXXX'
if category and category in severity_classification:
severity, cve = severity_classification[category]
elif '[SQLi]' in msg:
severity, cve = 'High', 'CVE-2019-1234'
elif '[XSS]' in msg:
severity, cve = 'Medium', 'CVE-2020-5678'
elif '[CMD]' in msg:
severity, cve = 'High', 'CVE-2018-9102'
elif '[HTML-Injection]' in msg:
severity, cve = 'Low', 'CVE-2021-0003'
elif '[Headers]' in msg:
severity, cve = 'Medium', 'CVE-2022-3456'
elif '[Port]' in msg:
severity, cve = 'Info', 'N/A'
elif '[Auth]' in msg:
severity, cve = 'High', 'N/A'
tagged = f'{msg} | Severity: {severity} | CVE: {cve}'
scan_results.append(tagged)
scan_metrics['hits'] += 1
scan_metrics['severities'][severity] += 1
scan_metrics['score'] += get_severity_score(severity)
if category:
scan_metrics['categories'][category] += 1
log(tagged)
def reset_scan_metrics():
scan_metrics['hits'] = 0
scan_metrics['categories'].clear()
scan_metrics['severities'].clear()
scan_metrics['score'] = 0
def reset_scan_state():
global current_target_url
scan_results.clear()
reset_scan_metrics()
current_target_url = ''
def format_scan_summary():
lines = ['\n📌 Scan Summary:']
lines.append(f'Total findings: {scan_metrics["hits"]}')
for category, count in scan_metrics['categories'].items():
lines.append(f' • {category}: {count}')
for severity, count in scan_metrics['severities'].items():
lines.append(f' • Severity {severity}: {count}')
lines.append(f'Overall risk score: {scan_metrics["score"]}')
if scan_results:
lines.append('\nRecent findings:')
lines.extend(f' • {line}' for line in scan_results[-5:])
return '\n'.join(lines)
def parse_finding_summary(finding):
if '|' not in finding:
return {'category': 'Unknown', 'severity': 'Unknown', 'cve': 'N/A', 'message': finding}
message_part, meta_part = finding.split('|', 1)
category = message_part.strip().split(']', 1)[0].replace('[', '').strip() if message_part.startswith('[') and ']' in message_part else 'Unknown'
severity = 'Unknown'
cve = 'N/A'
for token in meta_part.split('|'):
token = token.strip()
if token.lower().startswith('severity:'):
severity = token.split(':', 1)[1].strip()
elif token.lower().startswith('cve:'):
cve = token.split(':', 1)[1].strip()
return {
'category': category,
'severity': severity,
'cve': cve,
'message': message_part.strip(),
}
def _run_payloads(url, param, payloads, category, check_fn, explanation, log, timeout=DEFAULT_TIMEOUT):
global stop_requested
found = False
log(f'🔎 {category} scan starting...')
for p in payloads:
if stop_requested:
log(f'⛔ {category} scan stopped.')
return
full_url = build_payload_url(url, param, p)
predicted_type, confidence = classify_payload(p)
try:
r = requests.get(full_url, timeout=timeout, allow_redirects=True)
if check_fn(r, p):
found = True
enhanced_log(
f'[{category}] 🚨 {explanation} at {full_url} (Payload: {p}) [Predicted: {predicted_type} {confidence:.0%}]',
log,
category=category
)
except Exception as e:
log(f'[Error] {category} scan error: {e}')
if not found:
log(f'✅ No {category} vulnerabilities detected.')
def get_payloads_for(category):
return custom_payloads or default_payloads.get(category, [])
def scan_sql_injection(url, log, timeout=DEFAULT_TIMEOUT):
_run_payloads(
url, scan_parameters['SQLi'], get_payloads_for('SQLi'), 'SQLi',
lambda r, p: any(err in r.text.lower() for err in ('sql', 'syntax', 'mysql', 'error', 'database', 'query')),
scan_explanations['SQLi'], log, timeout=timeout
)
def scan_xss(url, log, timeout=DEFAULT_TIMEOUT):
_run_payloads(
url, scan_parameters['XSS'], get_payloads_for('XSS'), 'XSS',
lambda r, p: any(tag in r.text.lower() for tag in ['<script>', 'onerror', 'onload', 'javascript:', 'alert(']),
scan_explanations['XSS'], log, timeout=timeout
)
def scan_html_injection(url, log, timeout=DEFAULT_TIMEOUT):
_run_payloads(
url, scan_parameters['HTML-Injection'], get_payloads_for('HTML-Injection'), 'HTML-Injection',
lambda r, p: any(tag in r.text.lower() for tag in ['<b>', '<h1>', '<input', '<div', '<span']),
scan_explanations['HTML-Injection'], log, timeout=timeout
)
def scan_command_injection(url, log, timeout=DEFAULT_TIMEOUT):
_run_payloads(
url, scan_parameters['CMD'], get_payloads_for('CMD'), 'CMD',
lambda r, p: 'uid=' in r.text or 'gid=' in r.text or 'command not found' in r.text.lower(),
scan_explanations['CMD'], log, timeout=timeout
)
def scan_headers(url, log, timeout=DEFAULT_TIMEOUT):
log('📋 Checking security headers...')
try:
r = requests.get(url, timeout=timeout)
recommended = [
'X-Frame-Options',
'X-Content-Type-Options',
'Strict-Transport-Security',
'Referrer-Policy',
'Content-Security-Policy'
]
missing = [h for h in recommended if h not in r.headers]
if missing:
enhanced_log(f"[Headers] Missing headers: {', '.join(missing)}", log)
else:
log('✅ All recommended security headers are present.')
if 'Retry-After' in r.headers:
enhanced_log('[Headers] Rate limiting header detected (Retry-After)', log, category='Headers')
except Exception as e:
log(f'[Error] Headers check failed: {e}')
def scan_waf_rate_limiting(url, log, timeout=DEFAULT_TIMEOUT):
log('🛡️ Checking for WAF / rate limiting...')
try:
r = requests.get(url, timeout=timeout, allow_redirects=True)
waf_signals = []
body = r.text.lower()
headers = {k.lower(): v for k, v in r.headers.items()}
blocked_keywords = ['access denied', 'request blocked', 'forbidden', 'waf', 'mod_security']
if any(keyword in body for keyword in blocked_keywords):
waf_signals.append('Blocked response detected')
if 'x-waf-policy' in headers or 'x-sucuri-cache' in headers or 'x-cdn' in headers:
waf_signals.append('WAF or CDN headers present')
if r.status_code == 429 or 'retry-after' in headers:
waf_signals.append('Rate limiting detected')
if waf_signals:
enhanced_log(f"[WAF] {', '.join(waf_signals)}", log, category='WAF')
else:
log('✅ No obvious WAF or rate-limiting behavior detected.')
except Exception as e:
log(f'[Error] WAF check failed: {e}')
def scan_directory_discovery(url, log, timeout=DEFAULT_TIMEOUT):
log('🧭 Discovering common directories and endpoints...')
parsed = urlparse(url)
base = urlunparse(parsed._replace(query='', fragment=''))
found = []
def probe(path):
target = base.rstrip('/') + '/' + path.lstrip('/')
try:
r = requests.get(target, timeout=min(timeout, 5), allow_redirects=False)
if r.status_code in (200, 301, 302, 401, 403):
return target, r.status_code
except Exception:
return None
return None
with ThreadPoolExecutor(max_workers=6) as executor:
futures = {executor.submit(probe, p): p for p in common_discovery_paths}
for future in as_completed(futures):
result = future.result()
if result:
target, status = result
found.append((target, status))
enhanced_log(f'[Discovery] Found {target} (HTTP {status})', log, category='Discovery')
if not found:
log('✅ No common directories or endpoints discovered.')
def scan_csrf_protection(url, log, timeout=DEFAULT_TIMEOUT):
log('🔐 Checking for CSRF protection on forms...')
try:
r = requests.get(url, timeout=timeout)
body = r.text.lower()
if '<form' in body:
hidden_csrf = any(token in body for token in ['csrfmiddlewaretoken', 'csrf-token', 'csrf_token', 'anti-csrf', 'anticsrf', 'csrf'])
if hidden_csrf:
enhanced_log('[CSRF] Hidden CSRF protection token detected on page', log, category='Auth')
else:
enhanced_log('[CSRF] No obvious CSRF hidden token found in forms', log, category='WAF')
else:
log('ℹ️ No HTML form found to evaluate CSRF protection.')
except Exception as e:
log(f'[Error] CSRF check failed: {e}')
def scan_http_methods(url, log, timeout=DEFAULT_TIMEOUT):
log('🚪 Checking supported HTTP methods...')
try:
r = requests.options(url, timeout=timeout)
allowed = r.headers.get('Allow', '')
if allowed:
allowed_methods = [m.strip() for m in allowed.split(',') if m.strip()]
unsafe = [m for m in allowed_methods if m in ('PUT', 'DELETE', 'TRACE', 'CONNECT', 'PATCH')]
if unsafe:
enhanced_log(f'[Methods] Unsafe methods allowed: {", ".join(unsafe)}', log, category='WAF')
else:
log(f'✅ Allowed methods: {", ".join(allowed_methods)}')
else:
log('⚠️ No Allow header present in OPTIONS response.')
except Exception as e:
log(f'[Error] HTTP methods check failed: {e}')
def scan_authentication(url, log, timeout=DEFAULT_TIMEOUT):
log('🔑 Performing authentication endpoint discovery...')
parsed = urlparse(url)
base = urlunparse(parsed._replace(query='', fragment=''))
found = False
for path in common_auth_paths:
if stop_requested:
log('⛔ Authentication scan stopped.')
return
target = base.rstrip('/') + '/' + path.lstrip('/')
try:
r = requests.get(target, timeout=min(timeout, 5), allow_redirects=True)
body = r.text.lower()
if r.status_code == 401 or any(field in body for field in ['name="username"', "name='username'", 'name="password"', "name='password'", 'login', 'signin']):
found = True
enhanced_log(f'[Auth] Potential auth endpoint found: {target} (HTTP {r.status_code})', log, category='Auth')
except Exception as e:
log(f'[Error] Authentication probe failed for {target}: {e}')
if not found:
log('✅ No obvious authentication endpoints detected.')
def scan_ports(url, log, timeout=DEFAULT_TIMEOUT):
log('🔌 Scanning common ports...')
host = url.split('://')[-1].split('/')[0]
try:
ip = socket.gethostbyname(host)
for port in (21, 22, 80, 443, 8080):
if stop_requested:
log('⛔ Port scan stopped.')
return
with socket.socket() as s:
s.settimeout(min(timeout, 1))
if s.connect_ex((ip, port)) == 0:
enhanced_log(f'[Port] {ip}:{port} is open', log, category='Port')
except Exception as e:
log(f'[Error] Port scan failed: {e}')
def _safe_log(widget, msg):
"""Schedule a log insert on the main Tkinter thread (thread-safe)."""
if widget is not None:
if root is not None:
root.after(0, lambda: (widget.insert(tk.END, msg + '\n'), widget.see(tk.END)))
else:
widget.insert(tk.END, msg + '\n')
widget.see(tk.END)
return
print(msg)
def set_scan_button_state(enabled):
if root is not None and scan_button is not None:
root.after(0, lambda: scan_button.config(state=tk.NORMAL if enabled else tk.DISABLED))
def update_status(label_key, value):
if root is not None and label_key in status_labels:
root.after(0, lambda: status_labels[label_key].config(text=value))
def update_progress(current, total):
global progress_step, progress_total
progress_step = current
progress_total = total
if root is not None and 'progress' in status_labels:
root.after(0, lambda: status_labels['progress'].config(text=f'Step {current}/{total}'))
def log_scan_summary(log):
log('\n📌 Scan Summary:')
for line in scan_results[-10:]:
log(f' • {line}')
def simulate_scan(url, widget, check_headers=True, scan_common_ports=True, check_waf=True, check_methods=True, check_csrf=True, discover_endpoints=True, check_auth=True, timeout=DEFAULT_TIMEOUT):
global scanning, stop_requested, current_target_url
scanning = True
stop_requested = False
scan_results.clear()
reset_scan_metrics()
current_target_url = ''
def log(m):
_safe_log(widget, m)
try:
normalized = ensure_valid_target_url(url)
except ValueError as exc:
log(f'❌ Invalid target URL: {exc}')
update_status('scan_status', 'Status: Failed')
scanning = False
set_scan_button_state(True)
return
current_target_url = normalized
update_status('target', f'Target: {normalized}')
update_status('scan_status', 'Status: Running')
set_scan_button_state(False)
total_steps = 4 + int(check_headers) + int(scan_common_ports) + int(check_waf) + int(check_methods) + int(check_csrf) + int(discover_endpoints) + int(check_auth)
update_progress(0, total_steps)
log(f'🚀 Starting scan of {normalized}')
try:
step = 1
update_progress(step, progress_total)
scan_sql_injection(normalized, log, timeout=timeout)
step += 1
update_progress(step, progress_total)
scan_xss(normalized, log, timeout=timeout)
step += 1
update_progress(step, progress_total)
scan_html_injection(normalized, log, timeout=timeout)
step += 1
update_progress(step, progress_total)
scan_command_injection(normalized, log, timeout=timeout)
if check_headers:
step += 1
update_progress(step, progress_total)
scan_headers(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping security headers check.')
if check_waf:
step += 1
update_progress(step, progress_total)
scan_waf_rate_limiting(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping WAF / rate limit check.')
if check_methods:
step += 1
update_progress(step, progress_total)
scan_http_methods(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping HTTP methods check.')
if check_csrf:
step += 1
update_progress(step, progress_total)
scan_csrf_protection(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping CSRF protection check.')
if scan_common_ports:
step += 1
update_progress(step, progress_total)
scan_ports(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping common port scan.')
if discover_endpoints:
step += 1
update_progress(step, progress_total)
scan_directory_discovery(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping endpoint discovery.')
if check_auth:
step += 1
update_progress(step, progress_total)
scan_authentication(normalized, log, timeout=timeout)
else:
log('ℹ️ Skipping authentication test.')
if stop_requested:
log('🛑 Scan stopped by user.')
update_status('scan_status', 'Status: Stopped')
else:
log('🏁 Scan complete.')
log(format_scan_summary())
update_status('scan_status', 'Status: Complete')
finally:
scanning = False
set_scan_button_state(True)
def start_scan(entry, widget, check_headers=True, scan_common_ports=True, check_waf=True, check_methods=True, check_csrf=True, discover_endpoints=True, check_auth=True):
global scanning, scan_options, stop_requested
if scanning:
return messagebox.showinfo('Scan in Progress', 'A scan is already running.')
raw_url = entry.get().strip()
if not raw_url:
return messagebox.showerror('Missing URL', 'Please enter a target URL.')
try:
normalized_url = ensure_valid_target_url(raw_url)
except ValueError as exc:
return messagebox.showerror('Invalid URL', str(exc))
stop_requested = False
scan_options = {
'Headers': check_headers,
'WAF': check_waf,
'HTTP Methods': check_methods,
'CSRF': check_csrf,
'Ports': scan_common_ports,
'Discovery': discover_endpoints,
'Authentication': check_auth,
}
if widget is not None:
widget.delete(1.0, tk.END)
update_status('scan_status', 'Status: Initializing')
threading.Thread(
target=simulate_scan,
args=(normalized_url, widget, check_headers, scan_common_ports, check_waf, check_methods, check_csrf, discover_endpoints, check_auth),
daemon=True
).start()
def stop_scan():
global stop_requested
if scanning:
stop_requested = True
update_status('scan_status', 'Status: Stop Requested')
if root is not None:
messagebox.showinfo('Stopping', 'Scan will stop shortly.')
def build_scan_report_payload(target_url):
normalized = ensure_valid_target_url(target_url)
payload = {
'target': normalized,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'summary': {
'total_findings': scan_metrics['hits'],
'categories': dict(scan_metrics['categories']),
'severities': dict(scan_metrics['severities']),
'score': scan_metrics['score'],
},
'findings': list(scan_results),
}
return payload
def get_report_text():
header = [
'Vulnerability Scan Report',
f'Time: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}',
f'Target: {current_target_url or "Unknown"}',
'-' * 60,
]
report_body = [format_scan_summary()]
if scan_options:
enabled = [name for name, enabled in scan_options.items() if enabled]
report_body.append('\nEnabled checks:')
report_body.extend(f' • {name}' for name in enabled)
if scan_results:
report_body.append('\nDetailed findings:')
report_body.extend(scan_results)
else:
full_text = log_box.get('1.0', tk.END).strip() if log_box is not None else ''
if full_text:
report_body.append('\nFull log output:')
report_body.append(full_text)
return '\n'.join(header + [''] + report_body)
def export_report(file_path, output_format='json'):
payload = build_scan_report_payload(current_target_url or 'Unknown')
if output_format == 'json':
with open(file_path, 'w', encoding='utf-8') as fh:
json.dump(payload, fh, indent=2)
return file_path
if output_format == 'csv':
rows = []
for finding in payload['findings']:
parsed = parse_finding_summary(finding)
rows.append({
'target': payload['target'],
'category': parsed['category'],
'severity': parsed['severity'],
'cve': parsed['cve'],
'message': parsed['message'],
})
fieldnames = ['target', 'category', 'severity', 'cve', 'message']
import csv
with open(file_path, 'w', newline='', encoding='utf-8') as fh:
writer = csv.DictWriter(fh, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
return file_path
if output_format == 'html':
rows_html = []
for finding in payload['findings']:
parsed = parse_finding_summary(finding)
rows_html.append(
'<tr>'
f'<td>{html.escape(payload["target"])}</td>'
f'<td>{html.escape(parsed["category"])}</td>'
f'<td>{html.escape(parsed["severity"])}</td>'
f'<td>{html.escape(parsed["cve"])}</td>'
f'<td>{html.escape(parsed["message"])}</td>'
'</tr>'
)
html_doc = f'''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web Vulnerability Scan Report</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 24px; color: #222; }}
table {{ border-collapse: collapse; width: 100%; margin-top: 20px; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; vertical-align: top; }}
th {{ background: #f3f3f3; }}
h1 {{ margin-bottom: 8px; }}
.meta {{ margin-bottom: 16px; color: #444; }}
</style>
</head>
<body>
<h1>Web Vulnerability Scan Report</h1>
<div class="meta">
<div><strong>Target:</strong> {html.escape(payload['target'])}</div>
<div><strong>Timestamp:</strong> {html.escape(payload['timestamp'])}</div>
<div><strong>Total Findings:</strong> {payload['summary']['total_findings']}</div>
<div><strong>Overall Score:</strong> {payload['summary']['score']}</div>
</div>
<table>
<thead>
<tr>
<th>Target</th>
<th>Category</th>
<th>Severity</th>
<th>CVE</th>
<th>Finding</th>
</tr>
</thead>
<tbody>
{''.join(rows_html) if rows_html else '<tr><td colspan="5">No findings recorded.</td></tr>'}
</tbody>
</table>
</body>
</html>'''
with open(file_path, 'w', encoding='utf-8') as fh:
fh.write(html_doc)
return file_path
raise ValueError(f'Unsupported export format: {output_format}')
def load_scan_config(config_path):
try:
with open(config_path, 'r', encoding='utf-8') as fh:
config = json.load(fh)
except FileNotFoundError:
return {}
except json.JSONDecodeError:
return {}
return config if isinstance(config, dict) else {}
def save_report():
report_text = get_report_text()
if not report_text:
return messagebox.showinfo('No Data', 'No scan results to save.')
path = filedialog.asksaveasfilename(
defaultextension='.txt', filetypes=[('Text files', '*.txt')]
)
if path:
with open(path, 'w', encoding='utf-8') as f:
f.write(report_text)
messagebox.showinfo('Saved', 'Report successfully saved.')
def show_project_info():
html_content = """<!DOCTYPE html>
<html>
<head>
<title>Project Information</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f2f2f2; }
.container { max-width: 800px; margin: 0 auto; padding: 50px 20px; background-color: #fff; box-shadow: 0 0 10px rgba(0,0,0,0.2); border-radius: 4px; position: relative; }
.photo { position: absolute; top: 20px; right: 20px; width: 100px; height: 100px; border-radius: 50%; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
h1 { font-size: 36px; margin-bottom: 30px; }
p { font-size: 18px; line-height: 1.5; margin-bottom: 20px; }
table { width: 100%; margin-bottom: 20px; border-collapse: collapse; }
table td, table th { padding: 10px; text-align: left; border: 1px solid #ddd; }
table th { background-color: #f2f2f2; font-size: 18px; }
@media only screen and (max-width: 600px) {
.container { padding: 30px 10px; }
h1 { font-size: 24px; }
}
</style>
</head>
<body>
<div class="container">
<h1>Project Information</h1>
<p>This project was developed by <b>C Nagendra Varma, R Deepak Agarwal, P Naga Karthik Reddy, P Revathi</b> as part of a <b>Cyber Security Internship</b>. This project is designed to <b>Secure the Organizations in Real World from Cyber Frauds performed by Hackers.</b></p>
<table>
<tr><th>Project Details</th><th>Value</th></tr>
<tr><td>Project Name</td><td>Automated Vulnerability Scanner for Web Applications</td></tr>
<tr><td>Project Description</td><td>Implementing Secured Encryption for Files which Contains Sensity Data</td></tr>
<tr><td>Project Start Date</td><td>15-July-2026</td></tr>
<tr><td>Project End Date</td><td>09-August-2026</td></tr>
<tr><td>Project Status</td><td><b>Completed</b></td></tr>
</table>
<h2>Developer Details</h2>
<table>
<tr><th>Name</th><th>Employee ID</th><th>Email</th></tr>
<tr><td>C Nagendra Varma</td><td>ST#IS#9539</td><td>chamarthinagendravarma@gmail.com</td></tr>
<tr><td>R Deepak Agarwal</td><td>ST#IS#9542</td><td>deepakagarwal1428@gmail.com</td></tr>
<tr><td>Pidugu Naga Karthik Reddy</td><td>ST#IS#9543</td><td>karthikreddypidugu6@gmail.com</td></tr>
<tr><td>Pilli Revathi</td><td>ST#IS#9544</td><td>revathipilli421@gmail.com</td></tr>
</table>
<h2>Company Details</h2>
<table>
<tr><th>Company</th><th>Value</th></tr>
<tr><td>Name</td><td>Supraja Technologies</td></tr>
<tr><td>Email</td><td>contact@suprajatechnologies.com</td></tr>
</table>
</div>
</body>
</html>"""
path = os.path.abspath('project_info.html')
with open(path, 'w', encoding='utf-8') as f:
f.write(html_content)
webbrowser.open(f'file:///{path}')
def run_cli_scan(target_url, output_format='text', check_headers=True, scan_common_ports=True, check_waf=True, check_methods=True, check_csrf=True, discover_endpoints=True, check_auth=True, timeout=DEFAULT_TIMEOUT):
output = []
try:
normalized = ensure_valid_target_url(target_url)
reset_scan_state()
scan_output = io.StringIO()
with contextlib.redirect_stdout(scan_output):
simulate_scan(
normalized,
None,
check_headers,
scan_common_ports,
check_waf,
check_methods,
check_csrf,
discover_endpoints,
check_auth,
timeout=timeout,
)
output.extend(line for line in scan_output.getvalue().splitlines() if line)
output.append(format_scan_summary())
if output_format == 'json':
return json.dumps(build_scan_report_payload(normalized), indent=2)
if output_format == 'csv':
raise ValueError('CSV output is supported only via export_report()')
return '\n'.join(output)
except Exception as exc:
error_message = f'❌ CLI scan failed: {exc}'
if output_format == 'json':
return json.dumps({'error': error_message}, indent=2)
return error_message
def parse_args():
parser = argparse.ArgumentParser(description='Web vulnerability scanner')
parser.add_argument('--target', help='Target URL to scan, e.g. https://example.com')
parser.add_argument('--format', choices=['text', 'json', 'html'], default='text', help='Output format')
parser.add_argument('--timeout', type=float, default=DEFAULT_TIMEOUT, help='HTTP timeout in seconds for network checks')
parser.add_argument('--config', help='Path to a JSON config file with scan settings')
parser.add_argument('--no-headers', action='store_true', help='Skip security header checks')
parser.add_argument('--no-ports', action='store_true', help='Skip port scan')
parser.add_argument('--no-waf', action='store_true', help='Skip WAF check')
parser.add_argument('--no-methods', action='store_true', help='Skip HTTP methods check')
parser.add_argument('--no-csrf', action='store_true', help='Skip CSRF checks')
parser.add_argument('--no-discovery', action='store_true', help='Skip endpoint discovery')
parser.add_argument('--no-auth', action='store_true', help='Skip authentication endpoint discovery')
return parser.parse_args()
def create_gui():
global root, log_box
train_ml_model()
root = tk.Tk()
root.title('ML-Powered Vulnerability Scanner')
root.geometry('900x650')
root.resizable(False, False)
icon = os.path.join('assets', 'icon.ico')
if os.path.exists(icon):
root.iconbitmap(icon)
# Background label — always dark so text is readable even without video
lbl = tk.Label(root, bg='black')
lbl.place(x=0, y=0, relwidth=1, relheight=1)
vid = os.path.join('assets', 'background.mp4')
if TKVIDEO_AVAILABLE and os.path.exists(vid):
tkvideo(vid, lbl, loop=1, size=(900, 650)).play()
heading_font = tkfont.Font(family='Helvetica', size=18, weight='bold')
heading = tk.Label(
root,
text='Automated Vulnerability Scanner for Web Applications',
font=heading_font,
fg='cyan',
bg='black'
)
heading.pack(pady=(10, 5))
def animate_heading():
current = heading.cget('fg')
heading.config(fg='white' if current == 'cyan' else 'cyan')
heading.after(600, animate_heading)
animate_heading()
frm = tk.Frame(root, bg='black', bd=5)
frm.pack(pady=(0, 10))
tk.Label(frm, text='Target URL:', fg='white', bg='black', font=('Arial', 12)).pack(pady=5)
entry = tk.Entry(frm, width=50, fg='white', bg='#222', insertbackground='white', font=('Arial', 12))
entry.pack(pady=5)
tk.Button(frm, text='Import Payloads', command=import_payloads).pack(pady=5)
options_frame = tk.Frame(root, bg='black', bd=2, relief=tk.RIDGE)
options_frame.pack(pady=(0, 10), fill='x', padx=10)
tk.Label(options_frame, text='Optional Checks:', fg='white', bg='black', font=('Arial', 11, 'bold')).grid(row=0, column=0, sticky='w', padx=10, pady=5)
headers_var = tk.BooleanVar(value=True)
ports_var = tk.BooleanVar(value=True)
waf_var = tk.BooleanVar(value=True)
methods_var = tk.BooleanVar(value=True)
csrf_var = tk.BooleanVar(value=True)
discovery_var = tk.BooleanVar(value=True)
tk.Checkbutton(options_frame, text='Security Headers', variable=headers_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=1, padx=10)
tk.Checkbutton(options_frame, text='Common Ports', variable=ports_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=2, padx=10)
tk.Checkbutton(options_frame, text='WAF / Rate Limit', variable=waf_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=3, padx=10)
tk.Checkbutton(options_frame, text='HTTP Methods', variable=methods_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=4, padx=10)
tk.Checkbutton(options_frame, text='CSRF Test', variable=csrf_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=5, padx=10)
tk.Checkbutton(options_frame, text='Endpoint Discovery', variable=discovery_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=6, padx=10)
auth_var = tk.BooleanVar(value=True)
tk.Checkbutton(options_frame, text='Authentication Test', variable=auth_var, bg='black', fg='white', selectcolor='#333', activebackground='black', activeforeground='white').grid(row=0, column=7, padx=10)
btn_frame = tk.Frame(root, bg='black')
btn_frame.pack(pady=(0, 10))
global scan_button
scan_button = tk.Button(
btn_frame,
text='Start Scan',
command=lambda: start_scan(
entry,
log_box,
headers_var.get(),
ports_var.get(),
waf_var.get(),
methods_var.get(),
csrf_var.get(),
discovery_var.get(),
auth_var.get()
),
width=15,
bg='#0f0'
)
scan_button.grid(row=0, column=0, padx=5)
tk.Button(btn_frame, text='Stop Scan', command=stop_scan, width=15, bg='#f33').grid(row=0, column=1, padx=5)
tk.Button(btn_frame, text='Download Report', command=save_report, width=15, bg='#09f').grid(row=0, column=2, padx=5)
tk.Button(btn_frame, text='Project Info', command=show_project_info, width=15, bg='#fc0').grid(row=0, column=3, padx=5)
tk.Button(btn_frame, text='Exit', command=root.destroy, width=15, bg='#888').grid(row=0, column=4, padx=5)
status_frame = tk.Frame(root, bg='black')
status_frame.pack(pady=(0, 10), fill='x', padx=10)
status_labels['target'] = tk.Label(status_frame, text='Target: None', fg='white', bg='black', font=('Arial', 10))
status_labels['target'].pack(side='left', padx=(0, 10))
status_labels['progress'] = tk.Label(status_frame, text='Step 0/0', fg='white', bg='black', font=('Arial', 10))
status_labels['progress'].pack(side='left', padx=(0, 10))
status_labels['scan_status'] = tk.Label(status_frame, text='Status: Idle', fg='white', bg='black', font=('Arial', 10, 'bold'))