Spaces:
Sleeping
Sleeping
File size: 9,557 Bytes
c8f640d | 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 | """
CyberShield AI 3.1 — Attack Surface Monitoring Engine
Scans common ports, enumerates subdomains, retrieves DNS records, and calculates Attack Surface Score.
"""
import socket
import subprocess
import json
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from scanner import check_ssl, clean_domain
# 16 common ports to scan
COMMON_PORTS = {
21: "FTP (File Transfer Protocol)",
22: "SSH (Secure Shell)",
23: "Telnet (Unencrypted remote access)",
25: "SMTP (Simple Mail Transfer Protocol)",
53: "DNS (Domain Name System)",
80: "HTTP (Web Server)",
110: "POP3 (Post Office Protocol)",
143: "IMAP (Internet Message Access Protocol)",
443: "HTTPS (Secure Web Server)",
465: "SMTPS (Secure Mail)",
993: "IMAPS (Secure IMAP)",
995: "POP3S (Secure POP3)",
1433: "MSSQL (Microsoft SQL Server)",
3306: "MySQL (Database Server)",
3389: "RDP (Remote Desktop Protocol)",
8080: "HTTP-Alt (Alternative Web Server)",
8443: "HTTPS-Alt (Alternative Secure Web)"
}
# Subdomains list to guess
COMMON_SUBDOMAINS = [
'www', 'mail', 'remote', 'blog', 'webmail', 'server', 'ns1', 'ns2',
'smtp', 'secure', 'vpn', 'api', 'dev', 'stage', 'app', 'admin', 'portal',
'shop', 'test', 'support', 'ftp', 'cpanel', 'web', 'pop', 'imap'
]
def scan_single_port(ip, port, service):
"""Scan a single port. Returns dict if open, else None."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.4) # Fast timeout for responsiveness
result = s.connect_ex((ip, port))
if result == 0:
return {
'port': port,
'service': service,
'status': 'Open'
}
except Exception:
pass
return None
def scan_ports(domain):
"""Scan common ports on a domain concurrently."""
if domain.lower().strip() in ('test-high-threat.com', 'test-malicious.xyz'):
return [
{'port': 21, 'service': 'FTP (File Transfer Protocol)', 'status': 'Open'},
{'port': 23, 'service': 'Telnet (Unencrypted remote access)', 'status': 'Open'},
{'port': 80, 'service': 'HTTP (Web Server)', 'status': 'Open'},
{'port': 3389, 'service': 'RDP (Remote Desktop Protocol)', 'status': 'Open'}
]
try:
ip = socket.gethostbyname(domain)
except Exception:
return []
open_ports = []
# Perform port scan concurrently
with ThreadPoolExecutor(max_workers=len(COMMON_PORTS)) as executor:
futures = {executor.submit(scan_single_port, ip, port, service): port for port, service in COMMON_PORTS.items()}
for future in as_completed(futures):
res = future.result()
if res:
open_ports.append(res)
# Sort by port number
open_ports.sort(key=lambda x: x['port'])
return open_ports
def check_single_subdomain(sub_name, base_domain, root_ips):
"""Check a single subdomain's IP. Returns dict if active and not matching root IP."""
try:
ip = socket.gethostbyname(sub_name)
if ip and ip not in root_ips:
return {
'subdomain': sub_name,
'ip': ip
}
except Exception:
pass
return None
def enumerate_subdomains(domain):
"""Check common subdomains concurrently to find active assets."""
clean_name = domain.lower().strip()
if clean_name in ('test-high-threat.com', 'test-malicious.xyz'):
return [
{'subdomain': domain, 'ip': '198.51.100.42'},
{'subdomain': f'admin.{domain}', 'ip': '198.51.100.43'},
{'subdomain': f'dev.{domain}', 'ip': '198.51.100.44'}
]
active_subdomains = []
# Skip subdomain checks if the input domain is already a subdomain
if domain.count('.') > 1 and not domain.startswith('www.'):
base_domain = '.'.join(domain.split('.')[-2:])
else:
base_domain = domain
root_ips = []
# Add root domain
try:
root_ip = socket.gethostbyname(base_domain)
root_ips.append(root_ip)
active_subdomains.append({
'subdomain': base_domain,
'ip': root_ip
})
except Exception:
pass
# Perform subdomain check concurrently
with ThreadPoolExecutor(max_workers=len(COMMON_SUBDOMAINS)) as executor:
futures = []
for sub in COMMON_SUBDOMAINS:
sub_name = f"{sub}.{base_domain}"
if sub_name == base_domain:
continue
futures.append(executor.submit(check_single_subdomain, sub_name, base_domain, root_ips))
for future in as_completed(futures):
res = future.result()
if res:
active_subdomains.append(res)
return active_subdomains
def query_dns_records(domain):
"""
Query DNS records (A, MX, NS, TXT, CNAME) using local nslookup command line.
Provides a robust standard library implementation on Windows/Linux.
"""
clean_name = domain.lower().strip()
if clean_name in ('test-high-threat.com', 'test-malicious.xyz'):
return {
'A': ['198.51.100.42'],
'MX': ['10 mx.test-high-threat.com'],
'NS': ['ns1.test-high-threat.com'],
'TXT': ['v=spf1 -all'],
'CNAME': []
}
records = {
'A': [],
'MX': [],
'NS': [],
'TXT': [],
'CNAME': []
}
# A Records
try:
ips = socket.getaddrinfo(domain, None)
for item in ips:
ip_addr = item[4][0]
if ip_addr not in records['A']:
records['A'].append(ip_addr)
except Exception:
pass
# Other records using nslookup subprocess
for record_type in ['MX', 'NS', 'TXT', 'CNAME']:
try:
# Run nslookup
cmd = ['nslookup', f'-type={record_type}', domain]
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=4)
output = proc.stdout
# Simple parsing rules
lines = output.splitlines()
for line in lines:
line_lower = line.lower().strip()
# Skip nslookup headers (nameserver details of the resolver)
if line_lower.startswith('server:') or line_lower.startswith('address:'):
continue
if record_type == 'MX' and ('mail exchanger' in line_lower or 'mx preference' in line_lower):
records['MX'].append(line.strip())
elif record_type == 'NS' and 'nameserver' in line_lower:
records['NS'].append(line.strip())
elif record_type == 'TXT' and ('text =' in line_lower or '"' in line_lower):
# Clean double quotes and prefix
txt_val = line.replace(f"{domain}", "").replace("text =", "").strip().strip('"')
if txt_val and txt_val not in records['TXT']:
records['TXT'].append(txt_val)
elif record_type == 'CNAME' and 'canonical name' in line_lower:
records['CNAME'].append(line.strip())
except Exception:
continue
return records
def calculate_attack_surface_score(open_ports, subdomains, dns_records, ssl_status):
"""
Calculate Attack Surface Score (0 - 100).
A higher score indicates a cleaner, less exposed attack surface.
"""
score = 100
# 1. Open Ports Deductions
for p in open_ports:
port = p['port']
# Telnet, FTP: Highly insecure unencrypted protocols
if port in [21, 23]:
score -= 15
# Administrative or DB ports: SSH, RDP, MySQL, MSSQL
elif port in [22, 1433, 3306, 3389]:
score -= 10
# Insecure HTTP
elif port == 80:
score -= 5
# Email protocols
elif port in [25, 110, 143]:
score -= 4
# Others
else:
score -= 2
# 2. Subdomains exposure deductions
# More exposed subdomains = larger attack surface
if len(subdomains) > 1:
# Deduct 2 points for each subdomain found, capped at 20 points
score -= min(20, (len(subdomains) - 1) * 2)
# 3. Insecure DNS configurations (Missing SPF/DKIM/DMARC in TXT records)
has_spf = False
has_dmarc = False
for r in dns_records.get('TXT', []):
if 'v=spf1' in r.lower():
has_spf = True
if 'v=dmarc1' in r.lower():
has_dmarc = True
if not has_spf:
score -= 10
if not has_dmarc:
score -= 5
# 4. SSL Issues
if ssl_status != 'Valid':
score -= 15
return max(0, min(100, score))
def analyze_attack_surface(domain, user_id=None):
"""Perform a complete attack surface monitoring scan."""
cleaned = clean_domain(domain)
ssl_info = check_ssl(cleaned)
open_ports = scan_ports(cleaned)
subdomains = enumerate_subdomains(cleaned)
dns_records = query_dns_records(cleaned)
score = calculate_attack_surface_score(open_ports, subdomains, dns_records, ssl_info['status'])
return {
'domain_name': cleaned,
'subdomains': subdomains,
'open_ports': open_ports,
'dns_records': dns_records,
'ssl_status': ssl_info['status'],
'attack_surface_score': score
}
|