Spaces:
Sleeping
Sleeping
Download attack_surface.py from rajesh9698/CYBER_OPS: direct link, hf CLI and curl.
- Browser
- Download file 9.56 kB
-
https://huggingface.co/spaces/rajesh9698/CYBER_OPS/resolve/main/attack_surface.py
- Command line
-
hf download hf://spaces/rajesh9698/CYBER_OPS/attack_surface.py
-
curl -L -o attack_surface.py https://huggingface.co/spaces/rajesh9698/CYBER_OPS/resolve/main/attack_surface.py
9.56 kB
| """ | |
| 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 | |
| } | |