forked from amandewatnitrr/hacking-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps_data_fetcher_bettercap.py
More file actions
1381 lines (1142 loc) · 49.5 KB
/
https_data_fetcher_bettercap.py
File metadata and controls
1381 lines (1142 loc) · 49.5 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
#!/usr/bin/env python3
"""
HTTPS Data Fetcher with Bettercap
SUMMARY:
- Extracts: page content, forms, links, scripts, security headers, cookies, technologies
- Captures: DNS queries, TCP connections, TLS handshakes, packet metadata, geo-location
- Analyzes: SSL/TLS configuration, CSP policies, CORS headers, technology stack
- Generates: comprehensive timestamped JSON reports with vulnerability assessments
NEW ENHANCEMENTS:
- SSL/TLS certificate analysis and chain validation
- Technology stack detection (Wappalyzer-style)
- Advanced security header analysis (CSP, CORS, etc.)
- Cookie security analysis
- Subdomain enumeration attempts
- GeoIP location analysis of discovered IPs
- Performance metrics and timing analysis
- JavaScript analysis for sensitive data exposure
- Advanced bettercap commands for deeper network analysis
- Vulnerability scoring system
- Export to multiple formats (JSON, CSV, HTML)
HOW IT WORKS:
1. HTTPS analysis with certificate inspection
2. Advanced HTML parsing with technology detection
3. Comprehensive security header analysis
4. bettercap integration with more modules
5. Network intelligence gathering and geolocation
6. Vulnerability assessment with scoring
7. Multi-format reporting with visualizations
REQUIREMENTS:
- Python 3.7+
- Bettercap installed (sudo apt install bettercap)
- Root/sudo access for packet capture
- Libraries: requests, beautifulsoup4, urllib3, cryptography, geoip2, builtwith
USAGE:
sudo python https_data_fetcher_bettercap.py <https_url> <interface> [options]
Options:
--no-verify Skip SSL verification
--deep-scan Enable deep scanning (subdomain enum, port scan)
--format FORMAT Output format: json, csv, html (default: json)
--timeout SECONDS Network capture timeout (default: 30)
--output DIR Output directory (default: current)
Examples:
sudo python https_data_fetcher_bettercap.py https://example.com eth0
sudo python https_data_fetcher_bettercap.py https://github.com wlan0 --deep-scan
sudo python https_data_fetcher_bettercap.py https://test.com eth0 --format html --timeout 60
VULNERABILITY SCORING:
Starts at 100 (perfect score), deductions applied for issues found:
Critical Issues (-15 points each):
- Weak TLS versions (TLS 1.0, 1.1)
- Weak encryption keys (< 2048 bits)
High Issues (-10 to -12 points each):
- Missing HSTS header
- Missing Content Security Policy
- Forms without CSRF protection
- Insecure cookies (missing Secure flag)
- Dangerous CSP directives (unsafe-inline, unsafe-eval)
Medium Issues (-5 to -8 points each):
- Missing security headers (X-Frame-Options, X-Content-Type-Options, etc.)
- SSL certificate issues (near expiry)
- Cookie issues (missing HttpOnly or SameSite)
- Insecure form submissions
- Suspicious scripts detected
Low Issues (-2 to -3 points each):
- Minor form security issues
- Cookie configuration warnings
Risk Levels:
80-100: LOW (Good security posture)
60-79: MEDIUM (Some improvements needed)
40-59: HIGH (Significant vulnerabilities)
0-39: CRITICAL (Immediate action required)
"""
import subprocess
import sys
import time
import threading
import json
import csv
import os
import re
import socket
import ssl
import hashlib
from datetime import datetime
from urllib.parse import urlparse, urljoin, parse_qs
from collections import defaultdict, Counter
import requests
from bs4 import BeautifulSoup
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
HAS_CRYPTO = True
except ImportError:
HAS_CRYPTO = False
print("[!] Warning: cryptography not installed - SSL analysis will be limited")
try:
import geoip2.database
import geoip2.errors
HAS_GEOIP = True
except ImportError:
HAS_GEOIP = False
print("[!] Warning: geoip2 not installed - IP geolocation will be limited")
# Disable SSL warnings for demonstration purposes
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# security headers to check
SECURITY_HEADERS = {
'Strict-Transport-Security': 'HSTS protection against downgrade attacks',
'X-Frame-Options': 'Clickjacking protection',
'X-Content-Type-Options': 'MIME sniffing protection',
'X-XSS-Protection': 'XSS filtering (legacy)',
'Content-Security-Policy': 'XSS and injection protection',
'Referrer-Policy': 'Referrer information control',
'Permissions-Policy': 'Feature policy control',
'Cross-Origin-Embedder-Policy': 'Cross-origin isolation',
'Cross-Origin-Opener-Policy': 'Cross-origin opener policy',
'Cross-Origin-Resource-Policy': 'Cross-origin resource sharing'
}
# Technology detection patterns
TECH_PATTERNS = {
'WordPress': [r'wp-content/', r'wp-includes/', r'/wp-admin/'],
'Drupal': [r'sites/default/', r'misc/drupal\.js', r'Drupal\.'],
'Joomla': [r'/components/com_', r'Joomla!', r'/media/jui/'],
'React': [r'react', r'_react', r'React\.'],
'Angular': [r'angular', r'ng-', r'Angular'],
'Vue.js': [r'vue\.js', r'Vue\.', r'v-'],
'jQuery': [r'jquery', r'jQuery', r'\$\('],
'Bootstrap': [r'bootstrap', r'Bootstrap'],
'Laravel': [r'laravel_session', r'Laravel'],
'Django': [r'csrfmiddlewaretoken', r'Django'],
'PHP': [r'\.php', r'PHPSESSID'],
'ASP.NET': [r'\.aspx', r'ASPXAUTH', r'ViewState'],
'Nginx': [r'nginx/', r'Server: nginx'],
'Apache': [r'apache', r'Server: Apache'],
'Cloudflare': [r'cloudflare', r'CF-RAY'],
'Google Analytics': [r'google-analytics', r'gtag\(', r'ga\('],
'Google Tag Manager': [r'googletagmanager', r'GTM-']
}
def get_ssl_info(hostname, port=443):
"""
SSL/TLS certificate analysis.
Args:
hostname (str): Target hostname
port (int): Port number (default: 443)
Returns:
dict: SSL certificate information and security analysis
"""
ssl_info = {
'certificate_valid': False,
'certificate_chain': [],
'cipher_suite': None,
'protocol_version': None,
'vulnerabilities': [],
'certificate_transparency': False,
'ocsp_stapling': False
}
if not HAS_CRYPTO:
return ssl_info
try:
# Create SSL context for connection
context = ssl.create_default_context()
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
# Connect and get certificate
with socket.create_connection((hostname, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
# Get peer certificate
der_cert = ssock.getpeercert_chain()[0]
cert = x509.load_der_x509_certificate(der_cert, default_backend())
ssl_info.update({
'certificate_valid': True,
'protocol_version': ssock.version(),
'cipher_suite': ssock.cipher()[0] if ssock.cipher() else None,
'subject': cert.subject.rfc4514_string(),
'issuer': cert.issuer.rfc4514_string(),
'serial_number': str(cert.serial_number),
'not_valid_before': cert.not_valid_before.isoformat(),
'not_valid_after': cert.not_valid_after.isoformat(),
'signature_algorithm': cert.signature_algorithm_oid._name if hasattr(cert.signature_algorithm_oid, '_name') else 'Unknown',
'public_key_size': cert.public_key().key_size if hasattr(cert.public_key(), 'key_size') else 'Unknown'
})
# Check for weak configurations
if ssl_info['protocol_version'] in ['TLSv1', 'TLSv1.1']:
ssl_info['vulnerabilities'].append(f"Weak TLS version: {ssl_info['protocol_version']}")
if ssl_info['public_key_size'] < 2048:
ssl_info['vulnerabilities'].append(f"Weak key size: {ssl_info['public_key_size']} bits")
# Check certificate expiry
days_until_expiry = (cert.not_valid_after - datetime.now()).days
if days_until_expiry < 30:
ssl_info['vulnerabilities'].append(f"Certificate expires in {days_until_expiry} days")
ssl_info['days_until_expiry'] = days_until_expiry
except ssl.SSLError as e:
ssl_info['ssl_error'] = str(e)
ssl_info['vulnerabilities'].append(f"SSL Error: {e}")
except (socket.error, OSError, ValueError) as e:
ssl_info['connection_error'] = str(e)
return ssl_info
def detect_technologies(content, headers, url):
"""
Technology stack detection.
Args:
content (str): HTML content
headers (dict): HTTP headers
url (str): Target URL
Returns:
dict: Detected technologies and confidence scores
"""
technologies = {}
content_lower = content.lower()
headers_str = str(headers).lower()
for tech, patterns in TECH_PATTERNS.items():
confidence = 0
matches = []
for pattern in patterns:
# Check in content
content_matches = len(re.findall(pattern, content_lower, re.IGNORECASE))
if content_matches > 0:
confidence += content_matches * 20
matches.extend(re.findall(pattern, content, re.IGNORECASE)[:3]) # Limit matches
# Check in headers
header_matches = len(re.findall(pattern, headers_str, re.IGNORECASE))
if header_matches > 0:
confidence += header_matches * 30
if confidence > 0:
technologies[tech] = {
'confidence': min(confidence, 100),
'evidence': matches[:5] # Limit evidence
}
return technologies
def analyze_cookies(headers):
"""
Cookie security analysis.
Args:
headers (dict): HTTP response headers
Returns:
dict: Cookie security analysis
"""
cookie_analysis = {
'total_cookies': 0,
'secure_cookies': 0,
'httponly_cookies': 0,
'samesite_cookies': 0,
'vulnerabilities': [],
'cookies': []
}
set_cookies = []
for key, value in headers.items():
if key.lower() == 'set-cookie':
if isinstance(value, list):
set_cookies.extend(value)
else:
set_cookies.append(value)
for cookie in set_cookies:
cookie_info = {
'raw': cookie,
'secure': 'secure' in cookie.lower(),
'httponly': 'httponly' in cookie.lower(),
'samesite': None
}
# Extract cookie name
if '=' in cookie:
cookie_info['name'] = cookie.split('=')[0].strip()
# Check SameSite attribute
if 'samesite=' in cookie.lower():
samesite_match = re.search(r'samesite=([^;]+)', cookie.lower())
if samesite_match:
cookie_info['samesite'] = samesite_match.group(1).strip()
cookie_analysis['cookies'].append(cookie_info)
cookie_analysis['total_cookies'] += 1
if cookie_info['secure']:
cookie_analysis['secure_cookies'] += 1
else:
cookie_analysis['vulnerabilities'].append(f"Cookie '{cookie_info.get('name', 'unknown')}' lacks Secure flag")
if cookie_info['httponly']:
cookie_analysis['httponly_cookies'] += 1
else:
cookie_analysis['vulnerabilities'].append(f"Cookie '{cookie_info.get('name', 'unknown')}' lacks HttpOnly flag")
if cookie_info['samesite']:
cookie_analysis['samesite_cookies'] += 1
else:
cookie_analysis['vulnerabilities'].append(f"Cookie '{cookie_info.get('name', 'unknown')}' lacks SameSite attribute")
return cookie_analysis
def analyze_csp(headers):
"""
Content Security Policy analysis.
Args:
headers (dict): HTTP response headers
Returns:
dict: CSP analysis results
"""
csp_analysis = {
'present': False,
'directives': {},
'vulnerabilities': [],
'score': 0
}
csp_header = None
for key, value in headers.items():
if key.lower() in ['content-security-policy', 'content-security-policy-report-only']:
csp_header = value
csp_analysis['present'] = True
csp_analysis['report_only'] = 'report-only' in key.lower()
break
if not csp_header:
csp_analysis['vulnerabilities'].append("No Content Security Policy found")
return csp_analysis
# Parse CSP directives
directives = {}
for directive in csp_header.split(';'):
if ':' in directive:
key, value = directive.split(':', 1)
directives[key.strip()] = value.strip()
csp_analysis['directives'] = directives
# Analyze for common issues
dangerous_keywords = ['unsafe-inline', 'unsafe-eval', '*']
for directive, value in directives.items():
for keyword in dangerous_keywords:
if keyword in value:
csp_analysis['vulnerabilities'].append(f"Dangerous '{keyword}' in {directive}")
csp_analysis['score'] -= 10
# Check for important directives
important_directives = ['default-src', 'script-src', 'object-src', 'base-uri']
for directive in important_directives:
if directive in directives:
csp_analysis['score'] += 15
else:
csp_analysis['vulnerabilities'].append(f"Missing important directive: {directive}")
csp_analysis['score'] = max(0, min(100, csp_analysis['score'] + 50)) # Normalize to 0-100
return csp_analysis
def fetch_https_data(url, verify_ssl=True):
"""
HTTPS data fetching with comprehensive analysis.
Args:
url (str): The HTTPS URL to fetch data from
verify_ssl (bool): Whether to verify SSL certificates
Returns:
dict: website analysis data
"""
print(f"[*] Fetching from: {url}")
try:
# Create session for cookie persistence
session = requests.Session()
session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
})
# Measure response time
start_time = time.time()
response = session.get(url, verify=verify_ssl, timeout=15)
response_time = time.time() - start_time
response.raise_for_status()
print(f"[+] Successfully fetched data (Status: {response.status_code}, Time: {response_time:.2f}s)")
# Parse HTML
soup = BeautifulSoup(response.content, 'html.parser')
# Data extraction
extracted_data = {
'title': soup.title.string.strip() if soup.title and soup.title.string else 'No title found',
'meta_tags': [],
'links': {'internal': [], 'external': [], 'suspicious': []},
'forms': [],
'scripts': {'inline': [], 'external': [], 'suspicious': []},
'images': [],
'headers': dict(response.headers),
'response_time': response_time,
'content_length': len(response.content),
'technologies': {},
'javascript_analysis': {},
'performance_metrics': {}
}
# Meta tag extraction
for meta in soup.find_all('meta'):
meta_info = {
'name': meta.get('name', ''),
'content': meta.get('content', ''),
'property': meta.get('property', ''),
'http_equiv': meta.get('http-equiv', '')
}
extracted_data['meta_tags'].append(meta_info)
# Link analysis
parsed_url = urlparse(url)
base_domain = parsed_url.netloc
for link in soup.find_all('a', href=True):
href = link['href']
full_url = urljoin(url, href)
link_parsed = urlparse(full_url)
link_info = {
'url': href,
'full_url': full_url,
'text': link.get_text(strip=True)[:100], # Limit text length
'target': link.get('target', ''),
'rel': link.get('rel', [])
}
if link_parsed.netloc == base_domain or not link_parsed.netloc:
extracted_data['links']['internal'].append(link_info)
else:
extracted_data['links']['external'].append(link_info)
# Check for suspicious links
suspicious_patterns = ['javascript:', 'data:', 'vbscript:', 'file:']
if any(pattern in href.lower() for pattern in suspicious_patterns):
extracted_data['links']['suspicious'].append(link_info)
# Form analysis
for form in soup.find_all('form'):
form_data = {
'action': form.get('action', ''),
'method': form.get('method', 'GET').upper(),
'enctype': form.get('enctype', ''),
'inputs': [],
'has_csrf': False,
'security_issues': []
}
# Analyze form inputs
for input_field in form.find_all(['input', 'textarea', 'select']):
input_info = {
'name': input_field.get('name', ''),
'type': input_field.get('type', 'text'),
'value': input_field.get('value', ''),
'required': input_field.has_attr('required')
}
form_data['inputs'].append(input_info)
# Check for CSRF tokens
if 'csrf' in input_info['name'].lower() or 'token' in input_info['name'].lower():
form_data['has_csrf'] = True
# Security analysis
if form_data['method'] == 'GET' and any('password' in inp['type'] for inp in form_data['inputs']):
form_data['security_issues'].append("Password field in GET form")
if not form_data['has_csrf'] and form_data['method'] == 'POST':
form_data['security_issues'].append("Missing CSRF protection")
if form_data['action'].startswith('http://'):
form_data['security_issues'].append("Form submits to HTTP (insecure)")
extracted_data['forms'].append(form_data)
# Script analysis
for script in soup.find_all('script'):
if script.get('src'):
# External script
script_info = {
'src': script['src'],
'type': 'external',
'integrity': script.get('integrity', ''),
'crossorigin': script.get('crossorigin', ''),
'defer': script.has_attr('defer'),
'async': script.has_attr('async')
}
extracted_data['scripts']['external'].append(script_info)
# Check for suspicious external scripts
suspicious_domains = ['eval', 'document.write', 'innerHTML']
if any(domain in script['src'].lower() for domain in suspicious_domains):
extracted_data['scripts']['suspicious'].append(script_info)
else:
# Inline script
script_content = script.string or ''
script_info = {
'content': script_content[:500], # Limit content length
'type': 'inline',
'length': len(script_content)
}
extracted_data['scripts']['inline'].append(script_info)
# Check for dangerous patterns
dangerous_patterns = ['eval(', 'document.write(', 'innerHTML', 'outerHTML', 'setTimeout(', 'setInterval(']
if any(pattern in script_content for pattern in dangerous_patterns):
extracted_data['scripts']['suspicious'].append(script_info)
# Image analysis
for img in soup.find_all('img'):
img_info = {
'src': img.get('src', ''),
'alt': img.get('alt', ''),
'loading': img.get('loading', ''),
'width': img.get('width', ''),
'height': img.get('height', '')
}
extracted_data['images'].append(img_info)
# Technology detection
extracted_data['technologies'] = detect_technologies(response.text, response.headers, url)
# SSL/TLS analysis
hostname = urlparse(url).netloc
extracted_data['ssl_analysis'] = get_ssl_info(hostname)
# Cookie analysis
extracted_data['cookie_analysis'] = analyze_cookies(response.headers)
# CSP analysis
extracted_data['csp_analysis'] = analyze_csp(response.headers)
# Performance metrics
extracted_data['performance_metrics'] = {
'response_time_ms': round(response_time * 1000, 2),
'content_size_kb': round(len(response.content) / 1024, 2),
'total_links': len(extracted_data['links']['internal']) + len(extracted_data['links']['external']),
'total_images': len(extracted_data['images']),
'total_scripts': len(extracted_data['scripts']['inline']) + len(extracted_data['scripts']['external'])
}
return {
'status_code': response.status_code,
'headers': dict(response.headers),
'content': response.text,
'extracted_data': extracted_data,
'url': url,
'timestamp': datetime.now().isoformat()
}
except Exception as e:
print(f"[!] Error in fetch: {e}")
return None
def start_bettercap(iface):
"""
Bettercap startup with additional modules.
Args:
iface (str): Network interface
Returns:
subprocess.Popen: bettercap process
"""
print(f"[*] Starting bettercap on interface {iface}...")
try:
proc = subprocess.Popen(
["sudo", "bettercap", "-iface", iface, "-eval",
"set net.sniff.verbose true; set net.sniff.local true; set http.proxy.sslstrip true"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
time.sleep(3)
if proc.poll() is not None:
print("[!] Bettercap failed to start")
return None
return proc
except Exception as e:
print(f"[!] Error starting bettercap: {e}")
return None
def capture_traffic(proc, target_url, duration=30, deep_scan=False):
"""
Traffic capture with additional analysis.
Args:
proc: Bettercap process
target_url (str): Target URL
duration (int): Capture duration
deep_scan (bool): Enable deep scanning
Returns:
dict: Network analysis data
"""
print(f"[*] Traffic capture for {duration} seconds...")
parsed_url = urlparse(target_url)
target_domain = parsed_url.netloc
captured_data = {
'dns_queries': [],
'http_requests': [],
'tcp_connections': [],
'ssl_handshakes': [],
'discovered_ips': set(),
'discovered_domains': set(),
'packet_count': 0,
'raw_output': []
}
output_lines = []
stop_reading = threading.Event()
def read_output():
while not stop_reading.is_set():
try:
line = proc.stdout.readline()
if line:
output_lines.append(line.strip())
print(f"[BETTERCAP] {line.strip()}")
except:
break
reader_thread = threading.Thread(target=read_output)
reader_thread.daemon = True
reader_thread.start()
# Bettercap commands
commands = [
"net.probe on",
"net.sniff on",
"dns.spoof on" if deep_scan else "",
"http.proxy on" if deep_scan else "",
"events.stream on",
"ticker on"
]
for cmd in commands:
if cmd and proc.poll() is None:
try:
proc.stdin.write(cmd + "\n")
proc.stdin.flush()
time.sleep(0.5)
except:
break
# Generate traffic
def generate_traffic():
time.sleep(2)
try:
# Multiple requests with different patterns
for i in range(5):
requests.get(target_url, timeout=5)
time.sleep(1)
# Try common paths
if deep_scan:
common_paths = ['/robots.txt', '/sitemap.xml', '/favicon.ico', '/.well-known/security.txt']
for path in common_paths:
try:
test_url = f"{target_url.rstrip('/')}{path}"
requests.get(test_url, timeout=3)
except:
pass
except:
pass
traffic_thread = threading.Thread(target=generate_traffic)
traffic_thread.daemon = True
traffic_thread.start()
time.sleep(duration)
# Stop capture
if proc.poll() is None:
try:
proc.stdin.write("net.sniff off\n")
proc.stdin.write("net.probe off\n")
proc.stdin.flush()
except:
pass
time.sleep(1)
stop_reading.set()
reader_thread.join(timeout=2)
for line in output_lines:
captured_data['raw_output'].append(line)
line_lower = line.lower()
# Parse different types of network events
if 'dns' in line_lower and 'query' in line_lower:
captured_data['dns_queries'].append(line)
elif 'http' in line_lower:
captured_data['http_requests'].append(line)
elif 'tcp' in line_lower or 'syn' in line_lower:
captured_data['tcp_connections'].append(line)
elif 'ssl' in line_lower or 'tls' in line_lower:
captured_data['ssl_handshakes'].append(line)
# Extract IPs and domains
ip_pattern = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
domain_pattern = r'\b[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b'
ips = re.findall(ip_pattern, line)
domains = re.findall(domain_pattern, line)
captured_data['discovered_ips'].update(ips)
captured_data['discovered_domains'].update(domains)
captured_data['packet_count'] += 1
# Convert sets to lists for JSON serialization
captured_data['discovered_ips'] = list(captured_data['discovered_ips'])
captured_data['discovered_domains'] = list(captured_data['discovered_domains'])
print(f"[+] Capture complete: {captured_data['packet_count']} events, {len(captured_data['discovered_ips'])} IPs, {len(captured_data['discovered_domains'])} domains")
return captured_data
def calculate_vulnerability_score(analysis_data):
"""
Calculate vulnerability score based on findings.
Args:
analysis_data (dict): Complete analysis data
Returns:
dict: Vulnerability scoring information
"""
score = 100 # Start with perfect score
critical_issues = []
high_issues = []
medium_issues = []
low_issues = []
extracted = analysis_data.get('extracted_data', {})
# SSL/TLS analysis
ssl_analysis = extracted.get('ssl_analysis', {})
for vuln in ssl_analysis.get('vulnerabilities', []):
if 'weak' in vuln.lower() or 'tls' in vuln.lower():
critical_issues.append(f"SSL: {vuln}")
score -= 15
else:
medium_issues.append(f"SSL: {vuln}")
score -= 5
# Security headers
headers = analysis_data.get('headers', {})
for header, description in SECURITY_HEADERS.items():
if header not in headers:
if header in ['Strict-Transport-Security', 'Content-Security-Policy']:
high_issues.append(f"Missing critical header: {header}")
score -= 10
else:
medium_issues.append(f"Missing header: {header}")
score -= 5
# Cookie analysis
cookie_analysis = extracted.get('cookie_analysis', {})
for vuln in cookie_analysis.get('vulnerabilities', []):
if 'secure' in vuln.lower():
high_issues.append(f"Cookie: {vuln}")
score -= 8
else:
medium_issues.append(f"Cookie: {vuln}")
score -= 3
# CSP analysis
csp_analysis = extracted.get('csp_analysis', {})
if not csp_analysis.get('present'):
high_issues.append("No Content Security Policy")
score -= 12
else:
for vuln in csp_analysis.get('vulnerabilities', []):
if 'unsafe' in vuln.lower():
high_issues.append(f"CSP: {vuln}")
score -= 8
else:
medium_issues.append(f"CSP: {vuln}")
score -= 4
# Form analysis
for form in extracted.get('forms', []):
for issue in form.get('security_issues', []):
if 'csrf' in issue.lower():
high_issues.append(f"Form: {issue}")
score -= 10
elif 'http' in issue.lower():
medium_issues.append(f"Form: {issue}")
score -= 6
else:
low_issues.append(f"Form: {issue}")
score -= 2
# Script analysis
suspicious_scripts = extracted.get('scripts', {}).get('suspicious', [])
for script in suspicious_scripts:
high_issues.append("Suspicious script detected")
score -= 8
score = max(0, score) # Ensure score doesn't go below 0
# Determine risk level
if score >= 80:
risk_level = "LOW"
elif score >= 60:
risk_level = "MEDIUM"
elif score >= 40:
risk_level = "HIGH"
else:
risk_level = "CRITICAL"
return {
'score': score,
'risk_level': risk_level,
'critical_issues': critical_issues,
'high_issues': high_issues,
'medium_issues': medium_issues,
'low_issues': low_issues,
'total_issues': len(critical_issues) + len(high_issues) + len(medium_issues) + len(low_issues)
}
def analyze_and_report(url_data, network_data):
"""
Analysis and reporting.
Args:
url_data (dict): Website data
network_data (dict): Network data
Returns:
dict: Comprehensive report
"""
print("\n[*] Analysis in progress...")
report = {
'metadata': {
'timestamp': datetime.now().isoformat(),
'target_url': url_data.get('url', '') if url_data else '',
'scan_duration': 0
},
'website_analysis': {},
'network_analysis': {},
'security_analysis': {},
'vulnerability_assessment': {},
'technology_stack': {},
'performance_analysis': {},
'recommendations': []
}
if url_data:
extracted = url_data.get('extracted_data', {})
# Website analysis
report['website_analysis'] = {
'basic_info': {
'title': extracted.get('title', 'N/A'),
'status_code': url_data.get('status_code', 0),
'server': url_data.get('headers', {}).get('Server', 'Unknown'),
'content_type': url_data.get('headers', {}).get('Content-Type', 'Unknown'),
'content_length': extracted.get('content_length', 0),
'response_time_ms': extracted.get('response_time', 0) * 1000
},
'content_analysis': {
'total_links': {
'internal': len(extracted.get('links', {}).get('internal', [])),
'external': len(extracted.get('links', {}).get('external', [])),
'suspicious': len(extracted.get('links', {}).get('suspicious', []))
},
'forms': {
'total': len(extracted.get('forms', [])),
'with_csrf': len([f for f in extracted.get('forms', []) if f.get('has_csrf')]),
'security_issues': sum(len(f.get('security_issues', [])) for f in extracted.get('forms', []))
},
'scripts': {
'inline': len(extracted.get('scripts', {}).get('inline', [])),
'external': len(extracted.get('scripts', {}).get('external', [])),
'suspicious': len(extracted.get('scripts', {}).get('suspicious', []))
},
'images': len(extracted.get('images', [])),
'meta_tags': len(extracted.get('meta_tags', []))
}
}
# Security analysis
report['security_analysis'] = {
'ssl_tls': extracted.get('ssl_analysis', {}),
'security_headers': {},
'cookie_security': extracted.get('cookie_analysis', {}),
'content_security_policy': extracted.get('csp_analysis', {}),
'form_security': [f for f in extracted.get('forms', []) if f.get('security_issues')]
}
# Check security headers
headers = url_data.get('headers', {})
for header, description in SECURITY_HEADERS.items():
report['security_analysis']['security_headers'][header] = {
'present': header in headers,
'value': headers.get(header, ''),
'description': description
}
# Technology stack
report['technology_stack'] = extracted.get('technologies', {})
# Performance analysis
report['performance_analysis'] = extracted.get('performance_metrics', {})
# Vulnerability assessment
report['vulnerability_assessment'] = calculate_vulnerability_score(url_data)
# Generate recommendations
recommendations = []
# SSL recommendations
ssl_vulns = extracted.get('ssl_analysis', {}).get('vulnerabilities', [])
if ssl_vulns:
recommendations.append({
'category': 'SSL/TLS',
'priority': 'HIGH',
'recommendation': 'Update SSL/TLS configuration to use modern protocols and strong ciphers',
'details': ssl_vulns
})
# Security headers recommendations
missing_headers = [h for h, info in report['security_analysis']['security_headers'].items() if not info['present']]
if missing_headers:
recommendations.append({
'category': 'Security Headers',
'priority': 'MEDIUM' if len(missing_headers) < 5 else 'HIGH',
'recommendation': 'Implement missing security headers',
'details': missing_headers
})
# CSP recommendations
if not extracted.get('csp_analysis', {}).get('present'):
recommendations.append({
'category': 'Content Security Policy',
'priority': 'HIGH',
'recommendation': 'Implement Content Security Policy to prevent XSS attacks',
'details': ['No CSP header found']