-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebProtocolTester.py
661 lines (556 loc) · 21.7 KB
/
WebProtocolTester.py
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
import socket
import ssl
import re
import time
import threading
from typing import Dict, Optional, List, Tuple
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse
import json
class WebProtocolTester:
"""Advanced implementation for testing web protocols"""
def __init__(self):
# Basic settings
self.timeout = 3.0
self.max_retries = 2
self.thread_count = 10
self.ports_to_scan = [80, 443, 8080, 8443, 3000, 4000, 4433, 5000, 8000, 8008, 8888]
self.lock = threading.Lock()
self.open_ports = set()
# SSL context settings
self.ssl_context = self._create_ssl_context()
# Detection patterns
self.service_patterns = {
'apache': [
rb'Server: Apache/?([0-9.]+)?',
rb'X-Powered-By: PHP/?([0-9.]+)?'
],
'nginx': [
rb'Server: nginx/?([0-9.]+)?',
rb'X-FastCGI-Cache:'
],
'iis': [
rb'Server: Microsoft-IIS/?([0-9.]+)?',
rb'X-Powered-By: ASP.NET'
],
'tomcat': [
rb'Apache Tomcat/?([0-9.]+)?',
rb'X-Powered-By: Servlet'
],
'nodejs': [
rb'X-Powered-By: Express',
rb'X-Powered-By: Node'
]
}
# HTTP probes
self.http_probes = [
# Simple GET request
b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n',
# HEAD request
b'HEAD / HTTP/1.1\r\nHost: localhost\r\n\r\n',
# OPTIONS request
b'OPTIONS / HTTP/1.1\r\nHost: localhost\r\n\r\n',
# TRACE request
b'TRACE / HTTP/1.1\r\nHost: localhost\r\n\r\n'
]
# Common security checks
self.security_checks = [
{
'name': 'directory_listing',
'path': '/test_directory/',
'pattern': rb'Index of /',
'severity': 'MEDIUM'
},
{
'name': 'phpinfo',
'path': '/phpinfo.php',
'pattern': rb'PHP Version',
'severity': 'HIGH'
},
{
'name': 'admin_panel',
'path': '/admin/',
'pattern': rb'login|admin|backend',
'severity': 'MEDIUM'
}
]
def _create_ssl_context(self) -> ssl.SSLContext:
"""Create an SSL context with secure settings"""
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Disable old SSL versions
ctx.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
return ctx
def scan_ports(self, target: str) -> List[Dict]:
"""Simultaneous scanning of common web ports"""
results = []
print(f"\n[*] Scanning web ports on {target}")
with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
future_to_port = {executor.submit(self.test_web_port, target, port): port
for port in self.ports_to_scan}
for future in future_to_port:
try:
result = future.result()
if result and result.get('state') == 'open':
results.append(result)
with self.lock:
self.open_ports.add(future_to_port[future])
except Exception as e:
print(f"Error scanning port {future_to_port[future]}: {e}")
return results
def test_web_port(self, target: str, port: int) -> Optional[Dict]:
"""Comprehensive test of a web port"""
result = {
'port': port,
'state': 'closed',
'service': None,
'is_ssl': False,
'server': None,
'vulnerabilities': [],
'headers': {},
'security_issues': []
}
# Initial connection test
sock = self._create_socket(target, port)
if not sock:
return result
try:
# SSL test
if port in [443, 8443, 4433] or self._test_ssl(sock):
result['is_ssl'] = True
sock = self.ssl_context.wrap_socket(sock)
# Test web service
for probe in self.http_probes:
response = self._send_probe(sock, probe)
if response:
result['state'] = 'open'
# Identify service and version
service_info = self._detect_web_service(response)
result.update(service_info)
# Extract headers
headers = self._parse_headers(response)
result['headers'] = headers
# Security checks
security_issues = self._run_security_checks(sock, target, headers)
result['security_issues'] = security_issues
# Test SSL/TLS if enabled
if result['is_ssl']:
ssl_info = self._analyze_ssl(sock)
result['ssl_info'] = ssl_info
break
except Exception as e:
print(f"Error testing port {port}: {e}")
finally:
self._close_socket(sock)
return result if result['state'] == 'open' else None
def _create_socket(self, target: str, port: int) -> Optional[socket.socket]:
"""Create a socket with retries"""
for _ in range(self.max_retries):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((target, port))
return sock
except:
continue
return None
def _test_ssl(self, sock: socket.socket) -> bool:
"""Check for SSL/TLS support"""
try:
ssl_sock = self.ssl_context.wrap_socket(sock)
ssl_sock.do_handshake()
return True
except:
return False
def _send_probe(self, sock: socket.socket, data: bytes) -> Optional[bytes]:
"""Send a probe and receive a response"""
try:
sock.send(data)
response = b''
timeout = time.time() + self.timeout
while time.time() < timeout:
try:
chunk = sock.recv(4096)
if not chunk:
break
response += chunk
except socket.timeout:
break
return response
except:
return None
def _detect_web_service(self, response: bytes) -> Dict:
"""Identify the type and version of the web service"""
result = {
'service': 'unknown',
'version': None,
'server_software': None
}
for service, patterns in self.service_patterns.items():
for pattern in patterns:
match = re.search(pattern, response)
if match:
result['service'] = service
if len(match.groups()) > 0 and match.group(1):
result['version'] = match.group(1).decode()
break
if result['service'] != 'unknown':
break
# Extract server name
server_match = re.search(rb'Server: ([^\r\n]+)', response)
if server_match:
result['server_software'] = server_match.group(1).decode()
return result
def _parse_headers(self, response: bytes) -> Dict:
"""Parse HTTP headers"""
headers = {}
try:
header_section = response.split(b'\r\n\r\n')[0]
for line in header_section.split(b'\r\n')[1:]:
if b':' in line:
key, value = line.split(b':', 1)
headers[key.strip().decode()] = value.strip().decode()
except:
pass
return headers
def _run_security_checks(self, sock: socket.socket, target: str, headers: Dict) -> List[Dict]:
"""Execute security checks"""
issues = []
# Check for security headers
security_headers = {
'X-Frame-Options': 'Missing X-Frame-Options header',
'X-Content-Type-Options': 'Missing X-Content-Type-Options header',
'Strict-Transport-Security': 'Missing HSTS header',
'Content-Security-Policy': 'Missing CSP header'
}
for header, message in security_headers.items():
if header not in headers:
issues.append({
'type': 'missing_security_header',
'description': message,
'severity': 'MEDIUM'
})
# Check for common vulnerabilities
for check in self.security_checks:
probe = f'GET {check["path"]} HTTP/1.1\r\nHost: {target}\r\n\r\n'
response = self._send_probe(sock, probe.encode())
if response and re.search(check['pattern'], response):
issues.append({
'type': check['name'],
'path': check['path'],
'severity': check['severity']
})
# Check outdated servers
server = headers.get('Server', '')
version_match = re.search(r'([0-9.]+)', server)
if version_match:
version = version_match.group(1)
if self._is_outdated_version(server, version):
issues.append({
'type': 'outdated_server',
'description': f'Outdated server version: {server}',
'severity': 'HIGH'
})
return issues
def _is_outdated_version(self, server: str, version: str) -> bool:
"""Check for outdated server versions"""
outdated_versions = {
'Apache': '2.4.49',
'nginx': '1.18.0',
'Microsoft-IIS': '8.0'
}
for server_name, min_version in outdated_versions.items():
if server_name in server and self._compare_versions(version, min_version) < 0:
return True
return False
def _compare_versions(self, v1: str, v2: str) -> int:
"""Compare versions"""
v1_parts = [int(x) for x in v1.split('.') if x.isdigit()]
v2_parts = [int(x) for x in v2.split('.') if x.isdigit()]
for i in range(max(len(v1_parts), len(v2_parts))):
v1_part = v1_parts[i] if i < len(v1_parts) else 0
v2_part = v2_parts[i] if i < len(v2_parts) else 0
if v1_part < v2_part:
return -1
elif v1_part > v2_part:
return 1
return 0
def _analyze_ssl(self, sock: ssl.SSLSocket) -> Dict:
"""Analyze SSL/TLS configuration"""
ssl_info = {
'version': sock.version(),
'cipher': sock.cipher(),
'issues': []
}
# Check insecure protocols
if ssl_info['version'] in ['SSLv2', 'SSLv3', 'TLSv1', 'TLSv1.1']:
ssl_info['issues'].append({
'type': 'insecure_protocol',
'description': f'Insecure protocol {ssl_info["version"]} in use',
'severity': 'HIGH'
})
# Check weak ciphers
cipher = ssl_info['cipher'][0]
if any(x in cipher.lower() for x in ['null', 'anon', 'export', 'des', 'rc4', 'md5']):
ssl_info['issues'].append({
'type': 'weak_cipher',
'description': f'Weak cipher {cipher} in use',
'severity': 'HIGH'
})
return ssl_info
def _close_socket(self, sock: socket.socket) -> None:
"""Close the socket safely"""
try:
sock.shutdown(socket.SHUT_RDWR)
except:
pass
finally:
try:
sock.close()
except:
pass
def scan_target(self, target: str) -> Dict:
"""Scan an entire target"""
scan_start = time.time()
results = self.scan_ports(target)
scan_duration = time.time() - scan_start
return {
'target': target,
'scan_time': scan_duration,
'open_ports': len(self.open_ports),
'results': results
}
if __name__ == '__main__':
import sys
import argparse
parser = argparse.ArgumentParser(description='Web Protocol Tester')
parser.add_argument('target', help='Target IP or hostname')
parser.add_argument('-p', '--ports', help='Port range (e.g. 1-100)', default='1-1000')
args = parser.parse_args()
try:
# Parse port range
start_port, end_port = map(int, args.ports.split('-'))
# Create an instance of the class
tester = WebProtocolTester()
# Set the port range
tester.ports_to_scan = range(start_port, end_port + 1)
# Run scan with args.target
results = tester.scan_target(args.target)
print(json.dumps(results, indent=2))
except ValueError:
print("Error: Invalid port range. Use format: start-end (e.g. 1-100)")
sys.exit(1)
except Exception as e:
print(f"Error: {str(e)}")
sys.exit(1)
class WebVulnScanner:
"""Class for scanning web vulnerabilities"""
def __init__(self):
self.vuln_patterns = {
'sql_injection': [
r"(?i)you have an error in your sql syntax",
r"(?i)warning.*?\Wmysqli?_",
r"(?i)sqlite3.*?error",
r"(?i)pg_.*?error"
],
'xss': [
r"(?i)<script.*?>.*?</script.*?>",
r"(?i)javascript:",
r"(?i)onerror=",
r"(?i)onload="
],
'lfi': [
r"(?i)failed to open stream",
r"(?i)include.*?\.\.\/",
r"(?i)invalid files?\.?paths?"
]
}
self.vuln_payloads = {
'sql_injection': [
"'",
"1' OR '1'='1",
"1; DROP TABLE users--",
"1/**/AND/**/1=1"
],
'xss': [
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>",
"javascript:alert(1)"
],
'lfi': [
"../../../etc/passwd",
"..\\..\\..\\windows\\win.ini",
"....//....//etc/passwd"
]
}
def scan_vulnerabilities(self, target: str, port: int) -> List[Dict]:
"""Scan for vulnerabilities with various payloads"""
vulns = []
# Test common vulnerabilities
for vuln_type, payloads in self.vuln_payloads.items():
for payload in payloads:
path = f"/?test={payload}"
try:
response = self._send_request(target, port, path)
if response:
findings = self._check_response(response, vuln_type)
vulns.extend(findings)
except:
continue
return vulns
def _send_request(self, target: str, port: int, path: str) -> Optional[bytes]:
"""Send an HTTP request"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
try:
sock.connect((target, port))
request = f"GET {path} HTTP/1.1\r\nHost: {target}\r\n\r\n"
sock.send(request.encode())
response = b""
while True:
chunk = sock.recv(4096)
if not chunk:
break
response += chunk
return response
except:
return None
finally:
sock.close()
def _check_response(self, response: bytes, vuln_type: str) -> List[Dict]:
"""Check the response for vulnerability signs"""
findings = []
response_str = response.decode('utf-8', errors='ignore')
for pattern in self.vuln_patterns.get(vuln_type, []):
if re.search(pattern, response_str):
findings.append({
'type': vuln_type,
'pattern': pattern,
'severity': 'HIGH',
'description': f'Potential {vuln_type} vulnerability detected'
})
return findings
class WebFuzzer:
"""Class for fuzzing web parameters"""
def __init__(self):
self.fuzz_chars = "\"'<>\\%{}[]"
self.max_length = 8192
self.common_params = [
'id', 'page', 'file', 'dir', 'search',
'query', 'user', 'pass', 'key', 'token'
]
def fuzz_params(self, target: str, port: int) -> List[Dict]:
"""Fuzz GET parameters"""
results = []
for param in self.common_params:
# Test long values
long_value = "A" * self.max_length
path = f"/?{param}={long_value}"
try:
response = self._send_request(target, port, path)
if response and self._check_error_response(response):
results.append({
'param': param,
'type': 'buffer_overflow',
'value': f'Long string ({self.max_length} chars)'
})
except:
continue
# Test special characters
for char in self.fuzz_chars:
path = f"/?{param}={char * 100}"
try:
response = self._send_request(target, port, path)
if response and self._check_error_response(response):
results.append({
'param': param,
'type': 'special_chars',
'value': char
})
except:
continue
return results
def _send_request(self, target: str, port: int, path: str) -> Optional[bytes]:
"""Send an HTTP request"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
try:
sock.connect((target, port))
request = f"GET {path} HTTP/1.1\r\nHost: {target}\r\n\r\n"
sock.send(request.encode())
response = b""
while True:
chunk = sock.recv(4096)
if not chunk:
break
response += chunk
return response
except:
return None
finally:
sock.close()
def _check_error_response(self, response: bytes) -> bool:
"""Check the response for error indications"""
response_str = response.decode('utf-8', errors='ignore').lower()
error_signs = [
'error',
'exception',
'stack trace',
'overflow',
'crash',
'undefined',
'not found'
]
return any(sign in response_str for sign in error_signs)
class WebSecurityScanner:
"""Main class for web security scanning"""
def __init__(self):
self.protocol_tester = WebProtocolTester()
self.vuln_scanner = WebVulnScanner()
self.fuzzer = WebFuzzer()
def scan(self, target: str) -> Dict:
"""Full security scan"""
results = {
'target': target,
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
'port_scan': {},
'vulnerabilities': [],
'fuzzing': []
}
# Scan ports and services
port_results = self.protocol_tester.scan_target(target)
results['port_scan'] = port_results
# For each open port, perform vulnerability scanning and fuzzing
for port_info in port_results.get('results', []):
port = port_info['port']
# Vulnerability scanning
vulns = self.vuln_scanner.scan_vulnerabilities(target, port)
results['vulnerabilities'].extend(vulns)
# Fuzzing parameters
fuzz_results = self.fuzzer.fuzz_params(target, port)
results['fuzzing'].extend(fuzz_results)
return results
if __name__ == '__main__':
import sys
import argparse
parser = argparse.ArgumentParser(description='Web Protocol Tester')
parser.add_argument('target', help='Target IP or hostname')
parser.add_argument('-p', '--ports', help='Port range (e.g. 1-100)', default='1-1000')
args = parser.parse_args()
try:
# Parse the port range
start_port, end_port = map(int, args.ports.split('-'))
# Create an instance of the class
tester = WebProtocolTester()
# Set the port range
tester.ports_to_scan = range(start_port, end_port + 1)
# Run the scan with target
results = tester.scan_target(args.target)
print(json.dumps(results, indent=2))
except ValueError:
print("Error: Invalid port range. Use format: start-end (e.g. 1-100)")
sys.exit(1)
except Exception as e:
print(f"Error: {str(e)}")
sys.exit(1)