From 6973c181bf07cc93ba1f3339a3ebb6cf85dc572d Mon Sep 17 00:00:00 2001 From: ItsWanheda Date: Thu, 5 Nov 2026 13:19:11 +0330 Subject: [PATCH 1/6] fix(protocols): repair SNMP MongoDB Redis and database handshakes --- modules/database_enum.py | 207 +++++++++-------------- modules/mongodb_enum.py | 279 ++++++++++++------------------- modules/redis_enum.py | 179 ++++++++------------ modules/snmp_enum.py | 344 ++++++++++++++++++--------------------- 4 files changed, 401 insertions(+), 608 deletions(-) diff --git a/modules/database_enum.py b/modules/database_enum.py index da7ee73..119a8d3 100644 --- a/modules/database_enum.py +++ b/modules/database_enum.py @@ -1,151 +1,90 @@ -""" -Database Enumerator (MySQL, PostgreSQL, MSSQL) -- Protocol-level handshake probes -- Detect version and capabilities -- Detect auth requirements -""" -import socket -import struct -import re -from typing import Dict +"""Read-only MySQL, PostgreSQL, and MSSQL protocol handshakes.""" +from __future__ import annotations +import socket, ssl, struct +from typing import Any, Dict +def _recv_exact(sock: socket.socket,size: int)->bytes: + data=bytearray() + while len(data)1 else None @staticmethod - def scan(ip: str, port: int = 3306) -> Dict: - result = { - "module": "mysql", "target": ip, "port": port, - "open": False, "version": None, "vulnerabilities": [] - } + def scan(ip: str,port: int=3306)->Dict[str,Any]: + result={"module":"mysql","target":ip,"port":port,"open":False,"version":None,"vulnerabilities":[]} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5.0) - s.connect((ip, port)) - # MySQL handshake: packet length (3) + seq (1) + protocol version (1) + server version (null-terminated) - header = s.recv(4) - if len(header) < 4: - s.close() - return result - pkt_len = header | (header << 8) | (header << 16) - data = s.recv(pkt_len) - s.close() - result["open"] = True - # Skip protocol version (1 byte) - version_end = data.find(b"\x00", 1) - if version_end > 0: - result["version"] = data[1:version_end].decode("latin-1", errors="replace") - result["vulnerabilities"].append({ - "name": "MySQL exposed to network", - "severity": "MEDIUM", - "cve": "N/A" - }) - except Exception as e: - result["error"] = str(e) + with socket.create_connection((ip,port),timeout=5) as sock: + sock.settimeout(5); header=_recv_exact(sock,4) + size=int.from_bytes(header[:3],"little") + if not 6<=size<=1024*1024: raise ValueError("Invalid MySQL handshake length") + packet=_recv_exact(sock,size) + version=MySQLEnumerator.parse_handshake(packet) + if version is None: raise ValueError("Unrecognized MySQL handshake") + result["open"]=True; result["version"]=version + result["observations"]=["Handshake detected; network exposure alone is not a confirmed vulnerability."] + except (OSError,ValueError,ConnectionError) as exc: result["error"]=type(exc).__name__ return result - class PostgreSQLEnumerator: - DEFAULT_PORT = 5432 - + DEFAULT_PORT=5432 @staticmethod - def scan(ip: str, port: int = 5432) -> Dict: - result = { - "module": "postgresql", "target": ip, "port": port, - "open": False, "version": None, "vulnerabilities": [] - } + def startup_message(user: str="spectrascan",database: str="postgres")->bytes: + body=struct.pack(">I",196608)+f"user\x00{user}\x00database\x00{database}\x00client_encoding\x00UTF8\x00\x00".encode() + return struct.pack(">I",len(body)+4)+body + @staticmethod + def scan(ip: str,port: int=5432)->Dict[str,Any]: + result={"module":"postgresql","target":ip,"port":port,"open":False,"ssl_supported":None, + "tls_negotiated":False,"auth_required":None,"version":None,"vulnerabilities":[]} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5.0) - s.connect((ip, port)) - # PostgreSQL: send SSL request first to see if SSL is supported - ssl_req = struct.pack(">IIII", 8, 80877103, 0, 0) - s.send(ssl_req) - resp = s.recv(1) - if resp == b"S": - result["ssl_supported"] = True - s.close() - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5.0) - s.connect((ip, port)) - else: - result["ssl_supported"] = False - # Send startup message - fails with error that contains version info - startup = struct.pack(">II", 8, 196608) # protocol 3.0 - s.send(startup) - data = s.recv(1024) - s.close() - result["open"] = True - # Error message format: 'E' + length(4) + fields - if data and data[0:1] in (b"E", b"R"): - # Try to find version in error message text - text = data.decode("latin-1", errors="replace") - ver_match = re.search(r"(\d+\.\d+(?:\.\d+)?)", text) - if ver_match: - result["version"] = ver_match.group(1) - result["error_response_sample"] = text[:200] - result["vulnerabilities"].append({ - "name": "PostgreSQL exposed to network", - "severity": "MEDIUM", - "cve": "N/A" - }) - except Exception as e: - result["error"] = str(e) + with socket.create_connection((ip,port),timeout=5) as raw: + raw.settimeout(5); raw.sendall(struct.pack(">II",8,80877103)) + response=_recv_exact(raw,1); result["open"]=True; result["ssl_supported"]=response==b"S" + channel=raw + if response==b"S": + try: + channel=ssl.create_default_context().wrap_socket(raw,server_hostname=ip) + result["tls_negotiated"]=True + except ssl.SSLError: + result["tls_error"]="certificate_or_handshake_error"; return result + elif response!=b"N": + result["error"]="unexpected_ssl_response"; return result + channel.sendall(PostgreSQLEnumerator.startup_message()) + kind=_recv_exact(channel,1); size=struct.unpack(">I",_recv_exact(channel,4))[0] + if not 4<=size<=1024*1024: raise ValueError("Invalid PostgreSQL response length") + payload=_recv_exact(channel,size-4) + if kind==b"R": + result["auth_required"]=True + result["auth_method_code"]=struct.unpack(">I",payload[:4])[0] if len(payload)>=4 else None + elif kind==b"E": + sample=payload.decode("utf-8",errors="replace") + result["auth_required"]="password" in sample.lower() or "authentication" in sample.lower() + result["error_response_sample"]=sample[:200] + else: result["response_type"]=kind.decode("ascii",errors="replace") + except (OSError,ValueError,ConnectionError,struct.error) as exc: result["error"]=type(exc).__name__ return result - class MSSQLEnumerator: - DEFAULT_PORT = 1433 - + DEFAULT_PORT=1433 @staticmethod - def scan(ip: str, port: int = 1433) -> Dict: - result = { - "module": "mssql", "target": ip, "port": port, - "open": False, "version": None, "instance_name": None, - "vulnerabilities": [] - } + def scan(ip: str,port: int=1433)->Dict[str,Any]: + result={"module":"mssql","target":ip,"port":port,"open":False,"version":None,"instance_name":None,"vulnerabilities":[]} + prelogin=bytes([0x12,0x01,0x00,0x2f,0,0,0,1,0,0,0x15,0,6,1,0,0x1b,0,1,2,0,0x1c,0,1,3,0,0x1d,0,0,4,0,0,0xff]) try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5.0) - s.connect((ip, port)) - # TDS PRELOGIN - prelogin = bytes([ - 0x12, 0x01, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x15, 0x00, 0x06, 0x01, 0x00, 0x1b, - 0x00, 0x01, 0x02, 0x00, 0x1c, 0x00, 0x01, 0x03, - 0x00, 0x1d, 0x00, 0x00, 0x04, 0x00, 0x00, 0xff - ]) - s.send(prelogin) - resp = s.recv(4096) - s.close() - result["open"] = True - # Parse PRELOGIN response - if len(resp) > 30: - # Look for version in TDS response - text = resp.decode("latin-1", errors="replace") - ver_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", text) - if ver_match: - result["version"] = ver_match.group(1) - # Instance name often in payload - idx = resp.find(b"MSSQLSERVER") - if idx > 0: - end = resp.find(b"\x00", idx) - result["instance_name"] = resp[idx:end].decode("latin-1", errors="replace") - result["vulnerabilities"].append({ - "name": "MSSQL exposed to network", - "severity": "MEDIUM", - "cve": "N/A" - }) - except Exception as e: - result["error"] = str(e) + with socket.create_connection((ip,port),timeout=5) as sock: + sock.settimeout(5); sock.sendall(prelogin); response=sock.recv(4096) + result["open"]=bool(response); result["response_bytes"]=len(response) + except OSError as exc: result["error"]=type(exc).__name__ return result - -def scan_all_databases(ip: str) -> Dict: - """Scan all common database ports.""" - return { - "mysql": MySQLEnumerator.scan(ip), - "postgresql": PostgreSQLEnumerator.scan(ip), - "mssql": MSSQLEnumerator.scan(ip), - } \ No newline at end of file +def scan_all_databases(ip: str)->Dict[str,Any]: + return {"mysql":MySQLEnumerator.scan(ip),"postgresql":PostgreSQLEnumerator.scan(ip), + "mssql":MSSQLEnumerator.scan(ip)} diff --git a/modules/mongodb_enum.py b/modules/mongodb_enum.py index 21f54b1..c408f97 100644 --- a/modules/mongodb_enum.py +++ b/modules/mongodb_enum.py @@ -1,183 +1,118 @@ -""" -MongoDB Enumerator -- Detect MongoDB (27017) -- Try unauthenticated connection -- Get server info, databases, sample documents -- Detect wire version -""" -import socket -import struct -from typing import Dict, List +"""MongoDB OP_MSG framing and BSON parsing.""" +from __future__ import annotations +import socket, struct +from typing import Any, Dict +MAX_MESSAGE_SIZE=16*1024*1024 -class MongoDBEnumerator: - DEFAULT_PORT = 27017 +def _recv_exact(sock: socket.socket,size: int)->bytes: + data=bytearray() + while len(data) bool: + def check_open(ip: str,port: int=27017,timeout: float=3.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def _send_op_msg(sock: socket.socket, doc: bytes) -> bytes: - """Send OP_MSG (opcode 2013) with given BSON document.""" - # Flags (4) + section kind (1=doc, 0) + bson - section = b"\x00" + doc - # Body excludes opcode and requestID - body = struct.pack("bytes: + body=struct.pack("MAX_MESSAGE_SIZE: raise ValueError("MongoDB request too large") + sock.sendall(struct.pack("MAX_MESSAGE_SIZE or opcode!=2013: + raise ValueError("Invalid MongoDB response header") + if response_to not in (0,request_id): raise ValueError("MongoDB response id mismatch") + payload=_recv_exact(sock,response_length-16) + if payload[4]!=0: raise ValueError("Unsupported OP_MSG section") + document=payload[5:] + size=struct.unpack_from("len(document): raise ValueError("Invalid BSON response length") + return document[:size] @staticmethod - def _bson_encode(doc: dict) -> bytes: - """Minimal BSON encoder for simple documents.""" - parts = b"" - for k, v in doc.items(): - key_bytes = k.encode("utf-8") - if isinstance(v, int): - parts += b"\x10" + key_bytes + b"\x00" + struct.pack("bytes: + elements=bytearray() + for key,value in doc.items(): + if "\x00" in key: raise ValueError("BSON keys cannot contain NUL") + k=key.encode()+b"\x00" + if isinstance(value,bool): elements+=b"\x08"+k+(b"\x01" if value else b"\x00") + elif isinstance(value,int): + if -(2**31)<=value<2**31: elements+=b"\x10"+k+struct.pack(" Dict: - """Very minimal BSON parser for top-level documents.""" - result = {} - try: - if offset + 5 > len(data): - return result - doc_len = struct.unpack(" end: - break - result[key] = struct.unpack(" end: - break - str_len = struct.unpack("Dict[str,Any]: + if offset<0 or offset+5>len(data): raise ValueError("Truncated BSON document") + size=struct.unpack_from("len(data) or data[end-1]!=0: raise ValueError("Invalid BSON document bounds") + result={}; pos=offset+4 + while posend: raise ValueError("Invalid BSON string length") + value=data[pos:pos+n-1].decode("utf-8",errors="replace"); pos+=n + elif kind in (3,4): + n=struct.unpack_from("end: raise ValueError("Invalid nested BSON length") + nested=MongoDBEnumerator._parse_bson(data,pos) + value=nested if kind==3 else [nested[k] for k in sorted(nested,key=lambda v:int(v)) if k.isdigit()] + pos+=n + elif kind==5: + n=struct.unpack_from("end: raise ValueError("Invalid BSON binary length") + value=data[pos:pos+n].hex(); pos+=n + elif kind==8: + if pos>=end: raise ValueError("Truncated BSON bool") + value=bool(data[pos]); pos+=1 + elif kind==9: value=struct.unpack_from("end-1: raise ValueError("BSON value outside document") + result[key]=value return result - @staticmethod - def scan(ip: str, port: int = 27017) -> Dict: - result = { - "module": "mongodb", "target": ip, "port": port, - "open": False, "auth_required": True, "version": None, - "databases": [], "vulnerabilities": [] - } - if not MongoDBEnumerator.check_open(ip, port): - return result - result["open"] = True - + def scan(ip: str,port: int=27017)->Dict[str,Any]: + result={"module":"mongodb","target":ip,"port":port,"open":False,"auth_required":None, + "version":None,"databases":[],"vulnerabilities":[]} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(5.0) - s.connect((ip, port)) - - # Build hello/isMaster command - doc = MongoDBEnumerator._bson_encode({ - "hello": 1, - "$db": "admin" - }) - resp = MongoDBEnumerator._send_op_msg(s, doc) - s.close() - - if resp: - parsed = MongoDBEnumerator._parse_bson(resp, 16) # skip header - # OP_MSG response has section - if "ok" in parsed: - result["auth_required"] = False - result["version"] = parsed.get("maxWireVersion") - # Try to list databases - s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s2.settimeout(5.0) - s2.connect((ip, port)) - doc2 = MongoDBEnumerator._bson_encode({ - "listDatabases": 1, - "nameOnly": True, - "$db": "admin" - }) - resp2 = MongoDBEnumerator._send_op_msg(s2, doc2) - s2.close() - if resp2: - parsed2 = MongoDBEnumerator._parse_bson(resp2, 16) - if "databases" in parsed2: - result["databases"] = [d.get("name") for d in parsed2["databases"] if isinstance(d, dict) and "name" in d] - elif "documents" in parsed2: - result["databases"] = [d.get("name") for d in parsed2["documents"] if isinstance(d, dict) and "name" in d] - except Exception as e: - result["error"] = str(e) - - if not result["auth_required"]: - result["vulnerabilities"].append({ - "name": "MongoDB accessible without authentication", - "severity": "CRITICAL", - "cve": "N/A" - }) - - return result \ No newline at end of file + with socket.create_connection((ip,port),timeout=5) as sock: + sock.settimeout(5) + hello=MongoDBEnumerator._bson_encode({"hello":1,"$db":"admin"}) + hello_doc=MongoDBEnumerator._parse_bson(MongoDBEnumerator._send_op_msg(sock,hello,1)) + result["open"]=True; result["max_wire_version"]=hello_doc.get("maxWireVersion") + cmd=MongoDBEnumerator._bson_encode({"listDatabases":1,"nameOnly":True,"$db":"admin"}) + response=MongoDBEnumerator._parse_bson(MongoDBEnumerator._send_op_msg(sock,cmd,2)) + if response.get("ok") in (1,1.0,True): + result["auth_required"]=False + result["databases"]=[d.get("name") for d in response.get("databases",[]) if isinstance(d,dict) and d.get("name")] + result["vulnerabilities"].append({"name":"MongoDB database listing accessible without authentication","severity":"HIGH","cve":"N/A"}) + else: + result["auth_required"]=True; result["auth_error"]=str(response.get("errmsg","not authorized"))[:200] + except (OSError,ValueError,struct.error,ConnectionError) as exc: result["error"]=type(exc).__name__ + return result diff --git a/modules/redis_enum.py b/modules/redis_enum.py index 1e3d283..e1c9ba6 100644 --- a/modules/redis_enum.py +++ b/modules/redis_enum.py @@ -1,120 +1,75 @@ -""" -Redis Enumerator -- Detect Redis (6379) -- Try unauthenticated access -- Get INFO, CONFIG, KEYS * (carefully) -- Detect ACL -""" +"""Bounded Redis RESP2 reader and read-only exposure checks.""" +from __future__ import annotations import socket -from typing import Dict +from typing import Any, Dict +MAX_RESPONSE=65536 +def _read_line(stream)->bytes: + line=stream.readline(8193) + if not line or len(line)>8192 or not line.endswith(b"\r\n"): raise ValueError("Invalid Redis RESP line") + return line[:-2] -class RedisEnumerator: - DEFAULT_PORT = 6379 +def _read_resp(stream,depth: int=0)->Any: + if depth>8: raise ValueError("Redis RESP nesting too deep") + prefix=stream.read(1) + if prefix==b"+": return _read_line(stream).decode("utf-8",errors="replace") + if prefix==b"-": return "ERROR: "+_read_line(stream).decode("utf-8",errors="replace") + if prefix==b":": return int(_read_line(stream)) + if prefix==b"$": + size=int(_read_line(stream)) + if size==-1: return None + if size<0 or size>MAX_RESPONSE: raise ValueError("Redis bulk response exceeds limit") + raw=stream.read(size+2) + if len(raw)!=size+2 or not raw.endswith(b"\r\n"): raise ValueError("Truncated Redis bulk response") + return raw[:-2].decode("utf-8",errors="replace") + if prefix==b"*": + count=int(_read_line(stream)) + if count==-1: return None + if count<0 or count>1024: raise ValueError("Redis array exceeds limit") + return [_read_resp(stream,depth+1) for _ in range(count)] + if not prefix: raise ConnectionError("Redis peer closed connection") + raise ValueError("Unsupported RESP type") +class RedisEnumerator: + DEFAULT_PORT=6379 @staticmethod - def check_open(ip: str, port: int = 6379, timeout: float = 3.0) -> bool: + def check_open(ip: str,port: int=6379,timeout: float=3.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def send_command(ip: str, port: int, command: str, timeout: float = 5.0) -> str: - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - # RESP protocol: *1\r\n$4\r\nPING\r\n - parts = command.split() - req = f"*{len(parts)}\r\n" - for p in parts: - req += f"${len(p)}\r\n{p}\r\n" - s.send(req.encode()) - data = b"" - while True: - chunk = s.recv(4096) - if not chunk: - break - data += chunk - if len(data) > 65536 or b"\r\n" in chunk: - # For most simple commands, the response should be received - import time - time.sleep(0.3) - try: - s.settimeout(0.3) - more = s.recv(4096) - if more: - data += more - except socket.timeout: - pass - break - s.close() - return data.decode("latin-1", errors="replace") - except Exception as e: - return f"ERROR: {e}" - + def send_command(ip: str,port: int,command: str,timeout: float=5.0)->str: + args=command.split() + if not args or len(args)>16 or any("\r" in x or "\n" in x for x in args): raise ValueError("Invalid Redis command") + payload=f"*{len(args)}\r\n".encode() + for arg in args: + value=arg.encode(); payload+=b"$"+str(len(value)).encode()+b"\r\n"+value+b"\r\n" + with socket.create_connection((ip,port),timeout=timeout) as sock: + sock.settimeout(timeout); sock.sendall(payload) + with sock.makefile("rb") as stream: value=_read_resp(stream) + if value is None: return "" + return "\n".join("" if v is None else str(v) for v in value) if isinstance(value,list) else str(value) @staticmethod - def scan(ip: str, port: int = 6379) -> Dict: - result = { - "module": "redis", "target": ip, "port": port, - "open": False, "auth_required": True, "version": None, - "info": {}, "vulnerabilities": [] - } - if not RedisEnumerator.check_open(ip, port): - return result - result["open"] = True - - # Try PING - ping_resp = RedisEnumerator.send_command(ip, port, "PING") - result["auth_required"] = not ping_resp.startswith("+PONG") - result["ping_response"] = ping_resp.strip() - - if result["auth_required"]: - return result - - # Get version - info_resp = RedisEnumerator.send_command(ip, port, "INFO server") - for line in info_resp.split("\n"): - line = line.strip() - if line.startswith("redis_version:"): - result["version"] = line.split(":", 1).strip() - elif ":" in line and not line.startswith("#"): - k, _, v = line.partition(":") - if k.strip() and len(result["info"]) < 30: - result["info"][k.strip()] = v.strip() - - # Get keyspace (database sizes) - keys_resp = RedisEnumerator.send_command(ip, port, "DBSIZE") - result["db_size"] = keys_resp.strip() - - # Sample keys (limit to 10) - keys_resp = RedisEnumerator.send_command(ip, port, "RANDOMKEY") - sample_key = keys_resp.strip().lstrip("$").split("\r\n")[-1] if "$" in keys_resp else "" - result["sample_key"] = sample_key[:100] if sample_key else None - - # Vulnerabilities - result["vulnerabilities"].append({ - "name": "Redis accessible without authentication", - "severity": "CRITICAL", - "cve": "N/A" - }) - - if result["version"]: - try: - v_parts = [int(x) for x in result["version"].split(".")] - # Detect versions < 6.0 (no ACL) - if v_parts < 6: - result["vulnerabilities"].append({ - "name": f"Redis {result['version']} - no ACL support, weak auth model", - "severity": "HIGH", - "cve": "N/A" - }) - except Exception: - pass - - return result \ No newline at end of file + def scan(ip: str,port: int=6379)->Dict[str,Any]: + result={"module":"redis","target":ip,"port":port,"open":False,"auth_required":None, + "version":None,"info":{},"vulnerabilities":[]} + if not RedisEnumerator.check_open(ip,port): return result + result["open"]=True + try: + ping=RedisEnumerator.send_command(ip,port,"PING"); result["ping_response"]=ping[:200] + if ping.startswith("ERROR: NOAUTH") or ping.startswith("ERROR: WRONGPASS"): + result["auth_required"]=True; return result + if ping!="PONG": result["error"]="Unexpected Redis PING response"; return result + info=RedisEnumerator.send_command(ip,port,"INFO server") + if info.startswith("ERROR:"): + result["auth_required"]=True; result["access_note"]=info[:200]; return result + result["auth_required"]=False + for line in info.splitlines(): + key,sep,value=line.strip().partition(":") + if sep and len(result["info"])<30: result["info"][key]=value + if sep and key=="redis_version": result["version"]=value + result["vulnerabilities"].append({"name":"Redis INFO accessible without authentication","severity":"HIGH","cve":"N/A"}) + dbsize=RedisEnumerator.send_command(ip,port,"DBSIZE") + if not dbsize.startswith("ERROR:"): result["db_size"]=dbsize + except (OSError,ValueError,ConnectionError) as exc: result["error"]=type(exc).__name__ + return result diff --git a/modules/snmp_enum.py b/modules/snmp_enum.py index 586d9e8..154ea48 100644 --- a/modules/snmp_enum.py +++ b/modules/snmp_enum.py @@ -1,202 +1,166 @@ -""" -SNMP Enumerator -- Detect SNMP (UDP 161) -- Query system info, processes, users, network interfaces -- Tries common community strings -- Uses pysnmp if available, otherwise raw BER parser fallback, otherwise snmpwalk -""" -import socket -import subprocess -import random -import struct -from typing import Dict, List - +"""SNMPv2c query and response handling using bounded BER parsing.""" +from __future__ import annotations +import random, shutil, socket, subprocess +from typing import Any, Dict, List, Optional, Tuple + +class SNMPError(ValueError): pass + +def _length(n: int) -> bytes: + if n < 0: raise ValueError("negative BER length") + if n < 128: return bytes([n]) + raw = n.to_bytes((n.bit_length()+7)//8, "big") + return bytes([0x80|len(raw)]) + raw + +def _tlv(tag: int, value: bytes) -> bytes: + return bytes([tag]) + _length(len(value)) + value + +def _integer(value: int, tag: int = 2) -> bytes: + if value == 0: raw = b"\x00" + else: + raw = value.to_bytes(max(1,(value.bit_length()+8)//8),"big",signed=True) + while len(raw)>1 and ((raw[0]==0 and not raw[1]&128) or (raw[0]==255 and raw[1]&128)): raw=raw[1:] + return _tlv(tag,raw) + +def _base128(value: int) -> bytes: + if value < 0: raise ValueError("negative OID arc") + out=[value&127]; value >>= 7 + while value: out.append(128|(value&127)); value >>= 7 + return bytes(reversed(out)) + +def _oid(oid: str) -> bytes: + try: arcs=[int(v) for v in oid.strip(".").split(".")] + except (TypeError,ValueError) as exc: raise ValueError("invalid OID") from exc + if len(arcs)<2 or arcs[0] not in (0,1,2) or any(v<0 for v in arcs) or (arcs[0]<2 and arcs[1]>39): + raise ValueError("invalid OID arcs") + return _tlv(6,_base128(40*arcs[0]+arcs[1])+b"".join(_base128(v) for v in arcs[2:])) + +def _read_length(data: bytes, pos: int) -> Tuple[int,int]: + if pos>=len(data): raise SNMPError("missing BER length") + first=data[pos]; pos+=1 + if first<128: return first,pos + count=first&127 + if not count or count>4 or pos+count>len(data) or data[pos]==0: raise SNMPError("invalid BER length") + size=int.from_bytes(data[pos:pos+count],"big") + if size<128: raise SNMPError("non-canonical BER length") + return size,pos+count + +def _read_tlv(data: bytes,pos: int=0) -> Tuple[int,bytes,int]: + if pos>=len(data): raise SNMPError("missing BER tag") + tag=data[pos]; size,start=_read_length(data,pos+1); end=start+size + if end>len(data): raise SNMPError("BER value exceeds message") + return tag,data[start:end],end + +def _decode_oid(raw: bytes) -> str: + arcs=[]; value=0 + for byte in raw: + value=(value<<7)|(byte&127) + if not byte&128: arcs.append(value); value=0 + if not raw or raw[-1]&128 or not arcs: raise SNMPError("invalid OID encoding") + first=min(arcs[0]//40,2) + return ".".join(map(str,[first,arcs[0]-40*first,*arcs[1:]])) + +def _decode_value(tag: int, raw: bytes) -> str: + if tag==6: return _decode_oid(raw) + if tag in (2,65,66,67,70): + n=int.from_bytes(raw,"big",signed=(tag==2)) + return f"{n} ticks" if tag==67 else str(n) + if tag==4: return raw.decode("utf-8",errors="replace") + if tag==5: return "NULL" + if tag in (128,129,130): return {128:"noSuchObject",129:"noSuchInstance",130:"endOfMibView"}[tag] + return raw.hex() + +def _parse_response(data: bytes, expected_oid: Optional[str]=None) -> str: + tag,msg,end=_read_tlv(data) + if tag!=48 or end!=len(data): raise SNMPError("invalid SNMP envelope") + _,_,pos=_read_tlv(msg,0) + community_tag,_,pos=_read_tlv(msg,pos) + if community_tag!=4: raise SNMPError("invalid community field") + pdu_tag,pdu,_=_read_tlv(msg,pos) + if pdu_tag!=162: raise SNMPError("expected GetResponse PDU") + _,_,pos=_read_tlv(pdu,0) + status_tag,status,pos=_read_tlv(pdu,pos) + _,_,pos=_read_tlv(pdu,pos) + list_tag,bindings,_=_read_tlv(pdu,pos) + if status_tag!=2 or list_tag!=48 or int.from_bytes(status,"big",signed=True)!=0: + raise SNMPError("SNMP agent returned an error") + bind_tag,binding,bind_end=_read_tlv(bindings) + if bind_tag!=48 or bind_end!=len(bindings): raise SNMPError("invalid variable binding") + oid_tag,oid_raw,pos=_read_tlv(binding,0) + value_tag,value_raw,_=_read_tlv(binding,pos) + returned=_decode_oid(oid_raw) if oid_tag==6 else "" + if expected_oid and returned!=expected_oid: raise SNMPError("response OID mismatch") + return _decode_value(value_tag,value_raw) class SNMPEnumerator: - DEFAULT_COMMUNITIES = ["public", "private", "manager", "monitor", "admin", "cisco", "snmp"] - SYSTEM_OIDS = { - "1.3.6.1.2.1.1.1.0": "sysDescr", - "1.3.6.1.2.1.1.2.0": "sysObjectID", - "1.3.6.1.2.1.1.3.0": "sysUpTime", - "1.3.6.1.2.1.1.4.0": "sysContact", - "1.3.6.1.2.1.1.5.0": "sysName", - "1.3.6.1.2.1.1.6.0": "sysLocation", - "1.3.6.1.2.1.1.7.0": "sysServices", - } - - @staticmethod - def _ber_encode_length(length: int) -> bytes: - if length < 128: - return bytes([length]) - data = [] - while length > 0: - data.insert(0, length & 0xff) - length >>= 8 - return bytes([0x80 | len(data)] + data) - - @staticmethod - def _ber_encode_integer(value: int) -> bytes: - if value == 0: - data = b"\x00" - else: - data = [] - v = value - while v > 0: - data.insert(0, v & 0xff) - v >>= 8 - if data & 0x80: - data.insert(0, 0) - data = bytes(data) - return b"\x02" + SNMPEnumerator._ber_encode_length(len(data)) + data - - @staticmethod - def _ber_encode_string(s: bytes) -> bytes: - return b"\x04" + SNMPEnumerator._ber_encode_length(len(s)) + s - - @staticmethod - def _ber_encode_oid(oid: str) -> bytes: - parts = [int(x) for x in oid.split(".")] - if len(parts) < 2: - return b"" - encoded = [40 * parts + parts] - for p in parts[2:]: - if p < 128: - encoded.append(p) - else: - stack = [] - v = p - while v > 0: - stack.append(v & 0x7f) - v >>= 7 - stack.reverse() - for i in range(len(stack) - 1): - stack[i] |= 0x80 - encoded.extend(stack) - data = bytes(encoded) - return b"\x06" + SNMPEnumerator._ber_encode_length(len(data)) + data + DEFAULT_COMMUNITIES=["public","private","manager","monitor","admin","cisco","snmp"] + SYSTEM_OIDS={ + "1.3.6.1.2.1.1.1.0":"sysDescr","1.3.6.1.2.1.1.2.0":"sysObjectID", + "1.3.6.1.2.1.1.3.0":"sysUpTime","1.3.6.1.2.1.1.4.0":"sysContact", + "1.3.6.1.2.1.1.5.0":"sysName","1.3.6.1.2.1.1.6.0":"sysLocation", + "1.3.6.1.2.1.1.7.0":"sysServices"} + _ber_encode_length=staticmethod(_length) + _ber_encode_integer=staticmethod(_integer) + _ber_encode_oid=staticmethod(_oid) @staticmethod - def _build_get_request(community: str, oid: str, request_id: int = None) -> bytes: - if request_id is None: - request_id = random.randint(1, 2**31 - 1) - - # VarBind: OID + NULL - varbind = ( - b"\x30" + SNMPEnumerator._ber_encode_length(0) - + SNMPEnumerator._ber_encode_oid(oid) - + b"\x05\x00" - ) - varbind = b"\x30" + SNMPEnumerator._ber_encode_length(len(varbind)) + varbind - - # PDU: GetRequest (0xa0) - req_id = SNMPEnumerator._ber_encode_integer(request_id) - error = SNMPEnumerator._ber_encode_integer(0) - err_idx = SNMPEnumerator._ber_encode_integer(0) - pdu_body = req_id + error + err_idx + varbind - pdu = b"\xa0" + SNMPEnumerator._ber_encode_length(len(pdu_body)) + pdu_body - - # Version: 1 (SNMPv2c) - version = b"\x02\x01\x01" - community_enc = SNMPEnumerator._ber_encode_string(community.encode()) - msg_body = version + community_enc + pdu - msg = b"\x30" + SNMPEnumerator._ber_encode_length(len(msg_body)) + msg_body - return msg + def _build_get_request(community: str, oid: str, request_id: Optional[int]=None) -> bytes: + rid=request_id if request_id is not None else random.randint(1,2**31-1) + binding=_tlv(48,_oid(oid)+_tlv(5,b"")) + bindings=_tlv(48,binding) + pdu=_tlv(160,_integer(rid)+_integer(0)+_integer(0)+bindings) + return _tlv(48,_integer(1)+_tlv(4,community.encode("utf-8"))+pdu) @staticmethod - def query(ip: str, community: str, oid: str, timeout: float = 3.0) -> str: - """Send SNMP GET request, return value as string or None.""" + def query(ip: str, community: str, oid: str, timeout: float=3.0) -> Optional[str]: try: - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.settimeout(timeout) - pkt = SNMPEnumerator._build_get_request(community, oid) - s.sendto(pkt, (ip, 161)) - data, _ = s.recvfrom(4096) - s.close() - # Crude parser: find OCTET STRING or INTEGER value after the OID - # Skip to varbind value - if b"\x04" in data or b"\x02" in data or b"\x06" in data: - # Find last value-type byte and read length - for marker in [b"\x04", b"\x02", b"\x06", b"\x41"]: - idx = data.rfind(marker) - if idx >= 0 and idx + 1 < len(data): - length = data[idx + 1] - if length & 0x80 == 0 and idx + 2 + length <= len(data): - value = data[idx + 2: idx + 2 + length] - try: - return value.decode("utf-8", errors="replace") - except Exception: - return value.hex() - # Fallback: dump everything after OID match - return data.hex() - except socket.timeout: - return None - except Exception: - return None - return None + family=socket.AF_INET6 if ":" in ip else socket.AF_INET + with socket.socket(family,socket.SOCK_DGRAM) as sock: + sock.settimeout(timeout) + sock.sendto(SNMPEnumerator._build_get_request(community,oid),(ip,161)) + data,_=sock.recvfrom(65535) + value=_parse_response(data,oid) + return None if value.startswith("noSuch") or value=="NULL" else value + except (OSError,SNMPError,ValueError): return None @staticmethod - def scan(ip: str, communities: List[str] = None) -> Dict: - result = { - "module": "snmp", "target": ip, "open": False, - "community": None, "system": {}, "vulnerabilities": [] - } - communities = communities or SNMPEnumerator.DEFAULT_COMMUNITIES - - # First detect if SNMP is responding at all + def _snmpwalk(ip: str, communities: List[str]) -> Optional[Dict[str,str]]: + exe=shutil.which("snmpwalk") + if not exe: return None for community in communities: - val = SNMPEnumerator.query(ip, community, "1.3.6.1.2.1.1.1.0", timeout=2.0) - if val and len(val) > 0 and "noSuch" not in val.lower(): - result["open"] = True - result["community"] = community - # Query system info - for oid, name in SNMPEnumerator.SYSTEM_OIDS.items(): - v = SNMPEnumerator.query(ip, community, oid, timeout=2.0) - if v: - result["system"][name] = v - break + try: + proc=subprocess.run([exe,"-v2c","-c",community,"-t","2",ip,"1.3.6.1.2.1.1"], + capture_output=True,text=True,timeout=15,check=False) + except (OSError,subprocess.TimeoutExpired): continue + if proc.returncode==0 and proc.stdout: + values={} + for line in proc.stdout.splitlines(): + key,sep,value=line.partition("=") + if sep: values[key.strip()]=value.strip() + if values: return {"community":community,**values} + return None + @staticmethod + def scan(ip: str, communities: Optional[List[str]]=None) -> Dict[str,Any]: + result={"module":"snmp","target":ip,"open":False,"community":None,"system":{},"vulnerabilities":[]} + candidates=list(communities or SNMPEnumerator.DEFAULT_COMMUNITIES) + for community in candidates: + value=SNMPEnumerator.query(ip,community,"1.3.6.1.2.1.1.1.0",2.0) + if value is None: continue + result.update(open=True,community=community) + result["system"]["sysDescr"]=value + for oid,name in SNMPEnumerator.SYSTEM_OIDS.items(): + if name=="sysDescr": continue + other=SNMPEnumerator.query(ip,community,oid,2.0) + if other is not None: result["system"][name]=other + break if not result["open"]: - # Last resort: try snmpwalk - for community in communities: - if subprocess.run(["which", "snmpwalk"], capture_output=True).returncode == 0: - try: - out = subprocess.run( - ["snmpwalk", "-v2c", "-c", community, "-t", "2", ip, "1.3.6.1.2.1.1"], - capture_output=True, text=True, timeout=30 - ) - if out.returncode == 0 and out.stdout: - result["open"] = True - result["community"] = community - for line in out.stdout.splitlines(): - if "=" in line: - k, _, v = line.partition("=") - result["system"][k.strip()] = v.strip() - break - except Exception: - pass - return result - - # Detect vulnerabilities based on community string - weak = ["public", "private", "manager", "admin", "cisco", "monitor", "snmp", "test"] - if result["community"] in weak: - result["vulnerabilities"].append({ - "name": f"Weak/default SNMP community string: '{result['community']}'", - "severity": "HIGH", - "cve": "N/A" - }) - - # Heuristic checks on sysDescr - desc = result["system"].get("sysDescr", "").lower() - if "linux" in desc or "ubuntu" in desc or "debian" in desc: - result["os_guess"] = "Linux" - elif "windows" in desc: - result["os_guess"] = "Windows" - elif "cisco" in desc or "ios" in desc: - result["os_guess"] = "Cisco IOS" - result["vulnerabilities"].append({ - "name": "Cisco device exposed via SNMP", - "severity": "MEDIUM", - "cve": "N/A" - }) - - return result \ No newline at end of file + fallback=SNMPEnumerator._snmpwalk(ip,candidates) + if fallback: + result["open"]=True; result["community"]=fallback.pop("community"); result["system"]=fallback + if result["open"] and result["community"] in SNMPEnumerator.DEFAULT_COMMUNITIES: + result["vulnerabilities"].append({"name":"Default SNMP community string accepted","severity":"MEDIUM","cve":"N/A"}) + desc=str(result["system"].get("sysDescr","")).lower() + if any(t in desc for t in ("linux","ubuntu","debian")): result["os_guess"]="Linux" + elif "windows" in desc: result["os_guess"]="Windows" + elif "cisco" in desc or "ios" in desc: result["os_guess"]="Cisco IOS" + return result From 983abbae48cf4eb01dfb5c2b2d1e0e3238127dc8 Mon Sep 17 00:00:00 2001 From: ItsWanheda Date: Thu, 5 Nov 2026 13:21:03 +0330 Subject: [PATCH 2/6] fix(protocols): harden NFS RDP RTSP SMTP and service routing --- modules/network_services.py | 113 ++++--------- modules/nfs_enum.py | 316 +++++++++++++----------------------- modules/rdp_enum.py | 187 ++++++++------------- modules/rtsp_enum.py | 163 ++++++++----------- modules/smtp_enum.py | 247 +++++++++++----------------- 5 files changed, 383 insertions(+), 643 deletions(-) diff --git a/modules/network_services.py b/modules/network_services.py index f66abc5..7d56ba0 100644 --- a/modules/network_services.py +++ b/modules/network_services.py @@ -1,80 +1,39 @@ -""" -Network Services Aggregator -Single entrypoint for scanning all protocol modules. -""" -from typing import Dict, List -from concurrent.futures import ThreadPoolExecutor, as_completed - -from . import smb_enum, snmp_enum, ldap_enum, rdp_enum, smtp_enum -from . import dns_zone, nfs_enum, vnc_enum, redis_enum, mongodb_enum -from . import sip_enum, rtsp_enum, database_enum - - -# Map port -> module function -SERVICE_MAP = { - 21: ("ftp_banner", None), # Already covered in main scanner - 22: ("ssh_banner", None), - 25: ("smtp", smtp_enum.SMTPEnumerator.scan), - 53: ("dns_zone", None), # Needs domain - 110: ("pop3", None), - 139: ("smb", smb_enum.SMBEnumerator.scan), - 143: ("imap", None), - 161: ("snmp", None), # Special - needs UDP, custom call - 389: ("ldap", ldap_enum.LDAPEnumerator.scan), - 445: ("smb", smb_enum.SMBEnumerator.scan), - 514: ("syslog", None), - 554: ("rtsp", rtsp_enum.RTSPEnumerator.scan), - 636: ("ldaps", ldap_enum.LDAPEnumerator.scan), - 1433: ("mssql", database_enum.MSSQLEnumerator.scan), - 2049: ("nfs", nfs_enum.NFSEnumerator.scan), - 3306: ("mysql", database_enum.MySQLEnumerator.scan), - 3389: ("rdp", rdp_enum.RDPEnumerator.scan), - 5060: ("sip", sip_enum.SIPEnumerator.scan), - 5432: ("postgresql", database_enum.PostgreSQLEnumerator.scan), - 5900: ("vnc", vnc_enum.VNCEnumerator.scan), - 6379: ("redis", redis_enum.RedisEnumerator.scan), - 27017: ("mongodb", mongodb_enum.MongoDBEnumerator.scan), +"""Protocol-service aggregator retaining a distinct result per port.""" +from __future__ import annotations +from concurrent.futures import ThreadPoolExecutor,as_completed +from typing import Any,Dict,List +from . import database_enum,dns_zone,ldap_enum,mongodb_enum,nfs_enum,rdp_enum,redis_enum,rtsp_enum,sip_enum,smb_enum,smtp_enum,snmp_enum,vnc_enum + +SERVICE_MAP={ + 21:("ftp_banner",None),22:("ssh_banner",None),25:("smtp",smtp_enum.SMTPEnumerator.scan), + 53:("dns_zone",None),110:("pop3",None),139:("smb",smb_enum.SMBEnumerator.scan), + 143:("imap",None),161:("snmp",snmp_enum.SNMPEnumerator.scan),389:("ldap",ldap_enum.LDAPEnumerator.scan), + 445:("smb",smb_enum.SMBEnumerator.scan),514:("syslog",None),554:("rtsp",rtsp_enum.RTSPEnumerator.scan), + 636:("ldaps",ldap_enum.LDAPEnumerator.scan),1433:("mssql",database_enum.MSSQLEnumerator.scan), + 2049:("nfs",nfs_enum.NFSEnumerator.scan),3306:("mysql",database_enum.MySQLEnumerator.scan), + 3389:("rdp",rdp_enum.RDPEnumerator.scan),5060:("sip",sip_enum.SIPEnumerator.scan), + 5432:("postgresql",database_enum.PostgreSQLEnumerator.scan),5900:("vnc",vnc_enum.VNCEnumerator.scan), + 6379:("redis",redis_enum.RedisEnumerator.scan),27017:("mongodb",mongodb_enum.MongoDBEnumerator.scan) } - -def scan_port_with_service(ip: str, port: int, **kwargs) -> Dict: - """Dispatch scan to appropriate module based on port.""" - service_name, func = SERVICE_MAP.get(port, (None, None)) - if func: - try: - return func(ip, port=port, **kwargs) - except Exception as e: - return {"module": service_name, "error": str(e)} - return {"module": service_name or "unknown", "skipped": True} - - -def deep_scan(ip: str, ports: List[int] = None, max_workers: int = 5) -> Dict: - """Run all applicable service scans in parallel.""" - if ports is None: - ports = list(SERVICE_MAP.keys()) - results = {"target": ip, "scans": {}, "vulnerabilities": []} - - scan_targets = [(ip, p) for p in ports if SERVICE_MAP.get(p, (None, None))[1] is not None and p != 161] - # SNMP is UDP and requires its dedicated enumerator. - snmp_targets = [(ip, p) for p in ports if p == 161] - - with ThreadPoolExecutor(max_workers=max_workers) as executor: - futures = {} - for ip_t, port in scan_targets: - service_name, _ = SERVICE_MAP[port] - futures[executor.submit(scan_port_with_service, ip_t, port)] = service_name - - for ip_t, _ in snmp_targets: - futures[executor.submit(snmp_enum.SNMPEnumerator.scan, ip_t)] = "snmp" - +def scan_port_with_service(ip: str,port: int,**kwargs: Any)->Dict[str,Any]: + name,func=SERVICE_MAP.get(port,(None,None)) + if func is None: return {"module":name or "unknown","target":ip,"port":port,"skipped":True} + try: return func(ip,port=port,**kwargs) + except Exception as exc: return {"module":name,"target":ip,"port":port,"error":type(exc).__name__} + +def deep_scan(ip: str,ports: List[int]=None,max_workers: int=5)->Dict[str,Any]: + if isinstance(max_workers,bool) or not 1<=int(max_workers)<=32: raise ValueError("max_workers must be 1..32") + selected=list(SERVICE_MAP) if ports is None else list(dict.fromkeys(int(p) for p in ports)) + result={"target":ip,"scans":{},"vulnerabilities":[]} + targets=[p for p in selected if p in SERVICE_MAP and SERVICE_MAP[p][1] is not None] + with ThreadPoolExecutor(max_workers=int(max_workers)) as pool: + futures={pool.submit(scan_port_with_service,ip,p):p for p in targets} for future in as_completed(futures): - service_name = futures[future] - try: - r = future.result() - results["scans"][service_name] = r - if r.get("vulnerabilities"): - results["vulnerabilities"].extend(r["vulnerabilities"]) - except Exception as e: - results["scans"][service_name] = {"error": str(e)} - - return results \ No newline at end of file + port=futures[future]; name=SERVICE_MAP[port][0]; key=f"{name}:{port}" + try: row=future.result() + except Exception as exc: row={"module":name,"target":ip,"port":port,"error":type(exc).__name__} + result["scans"][key]=row + if isinstance(row,dict) and row.get("vulnerabilities"): + result["vulnerabilities"].extend(row["vulnerabilities"]) + return result diff --git a/modules/nfs_enum.py b/modules/nfs_enum.py index 187f30e..9d1b6e4 100644 --- a/modules/nfs_enum.py +++ b/modules/nfs_enum.py @@ -1,214 +1,132 @@ -""" -NFS Enumerator -- Detect NFS (2049) -- Enumerate exported shares via mountd (portmap + MOUNT) -- Try to mount anonymously -""" +"""NFS export discovery using bounded ONC RPC record and XDR parsing.""" +from __future__ import annotations +import shutil import socket import struct import subprocess -from typing import Dict, List +from typing import Any, Dict, List, Tuple +def _recv_exact(sock: socket.socket,size: int)->bytes: + data=bytearray() + while len(data)bytes: + header=struct.pack(">6I",xid,0,2,program,version,procedure) + auth_null=struct.pack(">2I",0,0) + return header+auth_null+auth_null+args + +def _rpc_tcp(sock: socket.socket,payload: bytes)->bytes: + sock.sendall(struct.pack(">I",0x80000000|len(payload))+payload) + marker=struct.unpack(">I",_recv_exact(sock,4))[0] + size=marker&0x7fffffff + if not marker&0x80000000 or size>1024*1024: raise ValueError("Invalid or oversized RPC record") + return _recv_exact(sock,size) + +def _rpc_result_offset(data: bytes)->int: + if len(data)<24: raise ValueError("Truncated RPC reply") + _,message_type,reply_status=struct.unpack_from(">3I",data,0) + if message_type!=1 or reply_status!=0: raise ValueError("RPC call was not accepted") + verifier_length=struct.unpack_from(">I",data,16)[0] + padded=(verifier_length+3)&~3 + accept_offset=20+padded + if accept_offset+4>len(data): raise ValueError("Truncated RPC verifier") + if struct.unpack_from(">I",data,accept_offset)[0]!=0: raise ValueError("RPC accept status is not SUCCESS") + return accept_offset+4 + +def _parse_portmap_dump(data: bytes)->Dict[str,Dict[str,int]]: + pos=_rpc_result_offset(data); result={} + names={100000:"portmap",100003:"nfs",100005:"mountd",100021:"nlockmgr"} + while pos+4<=len(data): + present=struct.unpack_from(">I",data,pos)[0]; pos+=4 + if present==0: break + if present!=1 or pos+16>len(data): raise ValueError("Malformed portmapper DUMP") + program,version,protocol,port=struct.unpack_from(">4I",data,pos); pos+=16 + if program in names and 0Tuple[str,int]: + if pos+4>len(data): raise ValueError("Truncated XDR string") + size=struct.unpack_from(">I",data,pos)[0]; pos+=4 + padded=(size+3)&~3 + if size>65536 or pos+padded>len(data): raise ValueError("Invalid XDR string size") + return data[pos:pos+size].decode("utf-8",errors="replace"),pos+padded +def _parse_exports(data: bytes)->List[Dict[str,Any]]: + pos=_rpc_result_offset(data); exports=[] + while pos+4<=len(data): + present=struct.unpack_from(">I",data,pos)[0]; pos+=4 + if present==0: break + if present!=1: raise ValueError("Malformed export linked list") + directory,pos=_read_xdr_string(data,pos) + groups=[] + while pos+4<=len(data): + has_group=struct.unpack_from(">I",data,pos)[0]; pos+=4 + if has_group==0: break + if has_group!=1: raise ValueError("Malformed export group list") + group,pos=_read_xdr_string(data,pos); groups.append(group) + exports.append({"path":directory,"allowed_clients":groups}) + return exports + +class NFSEnumerator: + DEFAULT_PORT=2049 @staticmethod - def check_open(ip: str, port: int = 2049, timeout: float = 3.0) -> bool: + def check_open(ip: str,port: int=2049,timeout: float=3.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def rpc_portmap_dump(ip: str, timeout: float = 5.0) -> Dict: - """Query portmapper (TCP/UDP 111) for service ports.""" - result = {"open": False, "services": {}} - # Try TCP first - for proto in ["tcp", "udp"]: - try: - if proto == "tcp": - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - else: - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.settimeout(timeout) - port = 111 - if proto == "tcp": - s.connect((ip, port)) - # RPC PORTMAP DUMP (program=100000, version=4, procedure=4=DUMP) - # Record Marking for TCP: 4 bytes big-endian length - xid = b"\x12\x34\x56\x78" - msg_type = b"\x00\x00\x00\x00" # CALL - rpc_version = b"\x00\x00\x00\x02" - program = b"\x00\x18\x6c\x40" # 100000 - version = b"\x00\x00\x00\x04" - procedure = b"\x00\x00\x00\x04" # DUMP - # Credentials (AUTH_UNIX) - flavor = b"\x00\x00\x00\x01" - length = b"\x00\x00\x00\x1c" - stamp = b"\x00\x00\x00\x00" - machinename = b"\x00\x00\x00\x00\x00\x00\x00\x00" - uid = b"\x00\x00\x00\x00" - gid = b"\x00\x00\x00\x00" - gids = b"\x00\x00\x00\x00" - # Verifier (AUTH_NULL) - v_flavor = b"\x00\x00\x00\x00" - v_length = b"\x00\x00\x00\x00" - rpc_call = (xid + msg_type + rpc_version + program + version + procedure - + flavor + length + stamp + machinename + uid + gid + gids - + v_flavor + v_length) - if proto == "tcp": - s.send(struct.pack(">I", len(rpc_call)) + rpc_call) - size = struct.unpack(">I", s.recv(4)) - data = s.recv(size) - else: - s.send(rpc_call) - data, _ = s.recvfrom(8192) - s.close() - # Crude parsing: find program numbers and ports - # Each mapping: prog(4) + ver(4) + proto(4) + port(4) - text = data.hex() - for prog_name, prog_id in [("nfs", 100003), ("mountd", 100005), - ("portmap", 100000), ("nlockmgr", 100021)]: - pattern = struct.pack(">I", prog_id).hex() - if pattern in text: - idx = text.find(pattern) - # After prog+ver+proto (12 bytes), read port - port_hex = text[idx + 24: idx + 32] - try: - port_num = int(port_hex, 16) - if port_num > 0 and port_num < 65536: - result["services"][prog_name] = port_num - except ValueError: - pass - result["open"] = True - break - except Exception: - try: - s.close() - except Exception: - pass + def rpc_portmap_dump(ip: str,timeout: float=5.0)->Dict[str,Any]: + result={"open":False,"services":{}} + try: + with socket.create_connection((ip,111),timeout=timeout) as sock: + sock.settimeout(timeout) + reply=_rpc_tcp(sock,_rpc_call(0x53535031,100000,2,4)) + result["services"]=_parse_portmap_dump(reply); result["open"]=True + except (OSError,ValueError,ConnectionError,struct.error): pass return result - @staticmethod - def mount_export(ip: str, port: int, timeout: float = 5.0) -> List[str]: - """Query MOUNTD (program 100005) for exports list.""" - exports = [] + def mount_export(ip: str,port: int,timeout: float=5.0)->List[Dict[str,Any]]: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - xid = b"\x12\x34\x56\x78" - msg_type = b"\x00\x00\x00\x00" - rpc_version = b"\x00\x00\x00\x02" - program = struct.pack(">I", 100005) - version = struct.pack(">I", 1) - procedure = struct.pack(">I", 5) # EXPORT - flavor = b"\x00\x00\x00\x01" - length = b"\x00\x00\x00\x1c" - stamp = b"\x00\x00\x00\x00" - machinename = b"\x00\x00\x00\x00\x00\x00\x00\x00" - uid = b"\x00\x00\x00\x00" - gid = b"\x00\x00\x00\x00" - gids = b"\x00\x00\x00\x00" - v_flavor = b"\x00\x00\x00\x00" - v_length = b"\x00\x00\x00\x00" - rpc_call = (xid + msg_type + rpc_version + program + version + procedure - + flavor + length + stamp + machinename + uid + gid + gids - + v_flavor + v_length) - s.send(struct.pack(">I", len(rpc_call)) + rpc_call) - size = struct.unpack(">I", s.recv(4)) - data = b"" - while len(data) < size: - data += s.recv(size - len(data)) - s.close() - # Parse: list of (dirname, list_of_groups) - offset = 0 - try: - # First: accepted reply verifier (8 bytes - AUTH_NULL) - # Then: export list - # Skip reply verifier - if data[0:4] == b"\x00\x00\x00\x01": # accepted - offset = 8 - # Skip accept_stat (4) and opaque_auth verifier (8) = 12 bytes after header - offset = 24 - # Each export: dirname (hyper string) + groups (hyper list) - while offset < len(data): - # dirname length - if offset + 4 > len(data): - break - dir_len = struct.unpack(">I", data[offset:offset + 4]) - offset += 4 - if offset + dir_len > len(data): - break - dirname = data[offset:offset + dir_len].decode("latin-1", errors="replace").strip("\x00") - offset += dir_len - if dirname: - exports.append(dirname) - # Skip groups (complex parsing - skip for now) - if offset + 4 > len(data): - break - groups_len = struct.unpack(">I", data[offset:offset + 4]) - if groups_len == 0: - offset += 4 - # Possible end of list (follows) - offset += 4 # follow (boolean/flag) - except Exception: - pass - except Exception: - pass - return exports - + with socket.create_connection((ip,port),timeout=timeout) as sock: + sock.settimeout(timeout) + reply=_rpc_tcp(sock,_rpc_call(0x53535032,100005,1,5)) + return _parse_exports(reply) + except (OSError,ValueError,ConnectionError,struct.error): return [] @staticmethod - def scan_with_showmount(ip: str) -> List[str]: - """Use showmount subprocess as fallback.""" - exports = [] - if subprocess.run(["which", "showmount"], capture_output=True).returncode == 0: - try: - out = subprocess.run( - ["showmount", "-e", ip], - capture_output=True, text=True, timeout=15 - ).stdout - for line in out.splitlines(): - line = line.strip() - if line and not line.startswith("Export list") and not line.startswith("---"): - exports.append(line.split() if line.split() else line) - except Exception: - pass + def scan_with_showmount(ip: str)->List[Dict[str,Any]]: + exe=shutil.which("showmount") + if not exe: return [] + try: + proc=subprocess.run([exe,"-e",ip],capture_output=True,text=True,timeout=15,check=False) + except (OSError,subprocess.TimeoutExpired): return [] + exports=[] + for line in proc.stdout.splitlines(): + line=line.strip() + if not line or line.lower().startswith("export list") or line.startswith("---"): continue + parts=line.split() + if parts: exports.append({"path":parts[0],"allowed_clients":parts[1:]}) return exports - @staticmethod - def scan(ip: str) -> Dict: - result = { - "module": "nfs", "target": ip, - "open": False, "exports": [], "vulnerabilities": [] - } - if not NFSEnumerator.check_open(ip): - return result - result["open"] = True - - # Try to get mountd port - portmap = NFSEnumerator.rpc_portmap_dump(ip) - mountd_port = portmap.get("services", {}).get("mountd", 0) - - if mountd_port: - result["exports"] = NFSEnumerator.mount_export(ip, mountd_port) - - if not result["exports"]: - result["exports"] = NFSEnumerator.scan_with_showmount(ip) - - if result["exports"]: - for export in result["exports"]: - if "rw" in export.lower() or "*" in export or "everyone" in export.lower(): - result["vulnerabilities"].append({ - "name": f"NFS export with permissive access: {export}", - "severity": "HIGH", - "cve": "N/A" - }) - break - - return result \ No newline at end of file + def scan(ip: str)->Dict[str,Any]: + result={"module":"nfs","target":ip,"open":False,"exports":[],"vulnerabilities":[]} + if not NFSEnumerator.check_open(ip): return result + result["open"]=True + rpc=NFSEnumerator.rpc_portmap_dump(ip) + mountd=rpc.get("services",{}).get("mountd",{}) + if isinstance(mountd,dict) and mountd.get("port") and mountd.get("protocol",6)==6: + result["exports"]=NFSEnumerator.mount_export(ip,mountd["port"]) + if not result["exports"]: result["exports"]=NFSEnumerator.scan_with_showmount(ip) + for export in result["exports"]: + if "*" in export.get("allowed_clients",[]): + result["vulnerabilities"].append({ + "name":f"Wildcard client access listed for NFS export {export.get('path')}", + "severity":"MEDIUM","cve":"N/A", + "evidence":"Mountd listed a wildcard client. Read/write permissions were not established.", + }) + return result diff --git a/modules/rdp_enum.py b/modules/rdp_enum.py index fc10c39..b513d0a 100644 --- a/modules/rdp_enum.py +++ b/modules/rdp_enum.py @@ -1,138 +1,81 @@ -""" -RDP Enumerator -- Detect RDP (3389) -- Check NLA (Network Level Authentication) -- Get server version info -- Test for BlueKeep (CVE-2019-0708) - basic check -""" +"""RDP negotiation parsing with conservative NLA and BlueKeep assessment.""" +from __future__ import annotations import socket import struct -import re -from typing import Dict +from typing import Any, Dict +PROTOCOL_RDP=0x00 +PROTOCOL_SSL=0x01 +PROTOCOL_HYBRID=0x02 +PROTOCOL_HYBRID_EX=0x08 -class RDPEnumerator: - DEFAULT_PORT = 3389 +def _connection_request(protocols: int)->bytes: + cookie=b"Cookie: mstshash:spectrascan\r\n" + negotiation=struct.pack("BBH",3,0,len(tpdu)+4)+tpdu - @staticmethod - def check_open(ip: str, port: int = 3389, timeout: float = 3.0) -> bool: - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False +def _parse_negotiation(data: bytes)->Dict[str,Any]: + result={"responds":False,"nla":None,"selected_protocol":None} + if len(data)<11 or data[0]!=3: return result + result["responds"]=True + for pos in range(4,len(data)-7): + if data[pos]==2 and data[pos+2:pos+4]==b"\x08\x00": + selected=struct.unpack_from(" Dict: - """Parse X.224 / TPKT / MCS initial connection sequence.""" - result = {"tpkt_version": None, "rdp_version": None, "nla_supported": None} + def check_open(ip: str,port: int=3389,timeout: float=3.0)->bool: try: - # TPKT header: version(1) + reserved(1) + length(2) - if len(data) < 4: - return result - result["tpkt_version"] = data - length = struct.unpack(">H", data[2:4]) - # X.224 TPDU - # Look for RDP version info later in packet - text = data.decode("latin-1", errors="replace") - # RDP Negotiation Request/Response often contains VERSION_INFO - # Look for version patterns - ver_match = re.search(rb"\x04\x00\x08\x00", data) - if ver_match: - # Could be RDP_NEG_RSP with selectedProtocol - pass - except Exception: - pass - return result - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def grab_banner(ip: str, port: int = 3389, timeout: float = 5.0) -> str: + def grab_banner(ip: str,port: int=3389,timeout: float=5.0)->str: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - # Send X.224 Connection Request - # TPKT header (4) + X.224 length (1) + X.224 type (1) + dst_ref (2) + src_ref (2) + class (1) + cookie + RDP_NEG_REQ - cookie = b"Cookie: mstshash=admin\r\n\x00" - rdp_neg = b"\x26\x00\x00\x00\x00\x00\x00\x00" # type=TYPE_RDP_NEG_REQ, flags=0, length=8, protocol=PROTOCOL_RDP (0) - # Actually use extended: PROTOCOL_SSL | PROTOCOL_HYBRID | PROTOCOL_HYBRID_EX - rdp_neg_req = struct.pack("BBH", 3, 0, len(tpkt_payload) + 4) + tpkt_payload - s.send(tpkt) - data = s.recv(4096) - s.close() - return data.hex() - except Exception as e: - return f"error: {e}" - + with socket.create_connection((ip,port),timeout=timeout) as sock: + sock.settimeout(timeout) + sock.sendall(_connection_request(PROTOCOL_RDP|PROTOCOL_SSL|PROTOCOL_HYBRID|PROTOCOL_HYBRID_EX)) + return sock.recv(4096).hex() + except OSError: return "" @staticmethod - def check_nla(ip: str, port: int = 3389, timeout: float = 5.0) -> Dict: - """Check if NLA is required by sending RDP_NEG_REQ with PROTOCOL_HYBRID.""" - result = {"responds": False, "nla_likely": False, "raw": ""} + def check_nla(ip: str,port: int=3389,timeout: float=5.0)->Dict[str,Any]: + result={"responds":False,"nla_likely":None,"raw":""} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - cookie = b"Cookie: mstshash=admin\r\n\x00" - rdp_neg_req = struct.pack("BBH", 3, 0, len(tpkt_payload) + 4) + tpkt_payload - s.send(tpkt) - data = s.recv(4096) - s.close() - result["responds"] = True - result["raw"] = data.hex() - # If server accepts HYBRID (NLA), it will reply with PROTOCOL_HYBRID (0x02) - # If it rejects/downgrades, it picks PROTOCOL_RDP (0x00) or PROTOCOL_SSL (0x01) - # Look for selectedProtocol field - if len(data) > 19: - # Find RDP_NEG_RSP: type=0x02, then flags(1), length(2), selectedProtocol(4) - if b"\x02\x00\x08\x00" in data: - idx = data.find(b"\x02\x00\x08\x00") - if idx + 8 <= len(data): - proto = struct.unpack(" Dict: - result = { - "module": "rdp", "target": ip, "port": port, - "open": False, "nla": False, "version": None, - "vulnerabilities": [] - } - if not RDPEnumerator.check_open(ip, port): - return result - result["open"] = True - - nla = RDPEnumerator.check_nla(ip, port) - result["nla"] = nla.get("nla_likely", False) - - if not result["nla"]: + def scan(ip: str,port: int=3389)->Dict[str,Any]: + result={"module":"rdp","target":ip,"port":port,"open":False,"nla":None, + "version":None,"vulnerabilities":[],"observations":[]} + if not RDPEnumerator.check_open(ip,port): return result + result["open"]=True + negotiation=RDPEnumerator.check_nla(ip,port) + result["nla"]=negotiation.get("nla_likely") + if result["nla"] is False: result["vulnerabilities"].append({ - "name": "RDP without NLA exposed - vulnerable to man-in-the-middle", - "severity": "MEDIUM", - "cve": "N/A" + "name":"RDP negotiated without Network Level Authentication","severity":"MEDIUM","cve":"N/A", + "evidence":f"Server selected protocol {negotiation.get('selected_protocol')}.", }) - - # BlueKeep heuristic: if NLA not required AND port open AND old Windows - # (proper BlueKeep detection needs to send malicious packets - we just flag potential exposure) - result["vulnerabilities"].append({ - "name": "Potential exposure to BlueKeep (CVE-2019-0708) - verify patch level", - "severity": "CRITICAL", - "cve": "CVE-2019-0708" - }) - - return result \ No newline at end of file + elif result["nla"] is True: + result["observations"].append("RDP negotiation selected an NLA-capable protocol.") + else: + result["observations"].append("NLA status could not be determined from the negotiation response.") + result["bluekeep_assessment"]={"status":"not_assessed", + "reason":"An open RDP port or disabled NLA is not evidence of BlueKeep; OS and patch-level evidence are required."} + return result diff --git a/modules/rtsp_enum.py b/modules/rtsp_enum.py index 211fbe5..d6ea940 100644 --- a/modules/rtsp_enum.py +++ b/modules/rtsp_enum.py @@ -1,108 +1,79 @@ -""" -RTSP Enumerator -- DESCRIBE request to detect RTSP services -- Parse SDP for stream info -- Detect unauthenticated streams -""" +"""RTSP DESCRIBE with correct response header and SDP extraction.""" +from __future__ import annotations import socket -import re -from typing import Dict +from typing import Any, Dict, List +def _parse_response(raw: bytes)->Dict[str,Any]: + text=raw.decode("latin-1",errors="replace") + header,sep,body=text.partition("\r\n\r\n") + lines=header.split("\r\n") + status=lines[0].split(" ",2) if lines else [] + code=int(status[1]) if len(status)>1 and status[1].isdigit() else None + headers={} + for line in lines[1:]: + name,colon,value=line.partition(":") + if colon: headers[name.strip().lower()]=value.strip() + streams=[] + for line in body.splitlines() if sep else []: + if line.startswith("m="): + parts=line[2:].split() + if len(parts)>=3: + streams.append({"type":parts[0],"port":int(parts[1]) if parts[1].isdigit() else None, + "protocol":parts[2],"formats":parts[3:]}) + return {"status_code":code,"status_line":lines[0] if lines else "", + "headers":headers,"body":body,"streams":streams,"server":headers.get("server"), + "auth_required":code==401 or "www-authenticate" in headers,"open":code is not None} class RTSPEnumerator: - DEFAULT_PORT = 554 - + DEFAULT_PORT=554 @staticmethod - def check_open(ip: str, port: int = 554, timeout: float = 3.0) -> bool: + def check_open(ip: str,port: int=554,timeout: float=3.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def describe(ip: str, port: int = 554, url: str = "/", - timeout: float = 5.0) -> Dict: - result = {"open": False, "auth_required": False, "server": None, - "sdp": None, "streams": []} - request = ( - f"DESCRIBE rtsp://{ip}:{port}{url} RTSP/1.0\r\n" - f"CSeq: 1\r\n" - f"User-Agent: SpectraScan\r\n" - f"Accept: application/sdp\r\n\r\n" - ).encode() + def describe(ip: str,port: int=554,url: str="/",timeout: float=5.0)->Dict[str,Any]: + path=url if url.startswith("/") else "/"+url + request=(f"DESCRIBE rtsp://{ip}:{port}{path} RTSP/1.0\r\n" + "CSeq: 1\r\nUser-Agent: SpectraScan\r\nAccept: application/sdp\r\n" + "Connection: close\r\n\r\n").encode("ascii",errors="replace") + result={"open":False,"auth_required":None,"server":None,"sdp":None,"streams":[],"status_code":None} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.send(request) - data = b"" - while True: - chunk = s.recv(4096) - if not chunk: - break - data += chunk - if b"\r\n\r\n" in data and len(data) > 500: - break - s.close() - text = data.decode("latin-1", errors="replace") - result["raw_status"] = text.split("\r\n", 1) if "\r\n" in text else "" - result["open"] = "RTSP/1.0" in text or "RTSP/2.0" in text - - for line in text.split("\r\n"): - if line.lower().startswith("server:"): - result["server"] = line.split(":", 1).strip() - elif line.lower().startswith("www-authenticate:"): - result["auth_required"] = True - elif line.startswith("m="): - # m=video 0 RTP/AVP 96 - parts = line[2:].split() - if parts and len(parts) > 1: - result["streams"].append({ - "type": parts, "port": parts, "protocol": parts - }) - - # Get SDP body if present - if "\r\n\r\n" in text: - sdp = text.split("\r\n\r\n", 1) - if sdp and sdp.isdigit(): - result["sdp_length"] = sdp.split("\r\n", 1) - sdp_body = sdp.split("\r\n", 1) if "\r\n" in sdp else "" - result["sdp"] = sdp_body[:500] - except Exception as e: - result["error"] = str(e) + with socket.create_connection((ip,port),timeout=timeout) as sock: + sock.settimeout(timeout); sock.sendall(request); data=bytearray() + while len(data)<65536: + chunk=sock.recv(min(4096,65536-len(data))) + if not chunk: break + data.extend(chunk) + if b"\r\n\r\n" in data: + head,_,body=bytes(data).partition(b"\r\n\r\n") + length=0 + for line in head.split(b"\r\n")[1:]: + if line.lower().startswith(b"content-length:"): + try: length=int(line.split(b":",1)[1].strip()) + except ValueError: length=0 + if len(body)>=length: break + parsed=_parse_response(bytes(data)); result.update(parsed); result["sdp"]=parsed["body"][:500] + except (OSError,ValueError) as exc: result["error"]=type(exc).__name__ return result - @staticmethod - def scan(ip: str, port: int = 554, urls: list = None) -> Dict: - result = { - "module": "rtsp", "target": ip, "port": port, - "open": False, "server": None, "auth_required": False, - "streams": [], "vulnerabilities": [] - } - if not RTSPEnumerator.check_open(ip, port): - return result - - urls = urls or ["/", "/stream", "/live", "/video", "/cam", "/h264"] - for url in urls: - resp = RTSPEnumerator.describe(ip, port, url) - if resp.get("open"): - result["open"] = True - result["server"] = resp.get("server", result["server"]) - result["auth_required"] = resp.get("auth_required", result["auth_required"]) - if resp.get("streams"): - result["streams"].extend(resp["streams"]) - result["url_works"] = url - break - - if result["open"] and not result["auth_required"]: + def scan(ip: str,port: int=554,urls: List[str]=None)->Dict[str,Any]: + result={"module":"rtsp","target":ip,"port":port,"open":False,"server":None, + "auth_required":None,"streams":[],"vulnerabilities":[]} + if not RTSPEnumerator.check_open(ip,port): return result + for path in urls or ["/","/stream","/live","/video","/cam","/h264"]: + response=RTSPEnumerator.describe(ip,port,path) + if not response.get("open"): continue + result["open"]=True; result["server"]=response.get("server") or result["server"] + if response.get("auth_required"): + result["auth_required"]=True; continue + if response.get("status_code")==200 and response.get("streams"): + result["auth_required"]=False; result["streams"].extend(response["streams"]) + result["url_works"]=path; result["sdp"]=response.get("sdp"); break + if result["auth_required"] is False and result["streams"]: result["vulnerabilities"].append({ - "name": f"RTSP stream accessible without authentication at {result.get('url_works', '/')}", - "severity": "HIGH", - "cve": "N/A" + "name":f"RTSP media description accessible without authentication at {result['url_works']}", + "severity":"HIGH","cve":"N/A", + "evidence":"Server returned RTSP 200 with SDP media sections without an authentication challenge.", }) - - return result \ No newline at end of file + return result diff --git a/modules/smtp_enum.py b/modules/smtp_enum.py index e40c4e9..456cdc5 100644 --- a/modules/smtp_enum.py +++ b/modules/smtp_enum.py @@ -1,169 +1,118 @@ -""" -SMTP Enumerator -- Banner grab -- VRFY user enumeration -- EXPN list enumeration -- Open relay test -- STARTTLS support -""" +"""SMTP probing with complete multiline replies and conservative findings.""" +from __future__ import annotations import socket -import re -from typing import Dict, List - +from typing import Any, Dict, List, Optional + +def _recv_line(sock: socket.socket,timeout: float=5.0,max_bytes: int=8192)->str: + sock.settimeout(timeout); data=bytearray() + while len(data)=max_bytes and not data.endswith(b"\n"): raise ValueError("SMTP line too long") + return data.decode("utf-8",errors="replace").rstrip("\r\n") + +def _recv_response(sock: socket.socket,timeout: float=5.0,max_lines: int=100)->List[str]: + lines=[]; expected=None + for _ in range(max_lines): + line=_recv_line(sock,timeout) + if not line: + if lines: break + raise ConnectionError("SMTP server closed connection") + lines.append(line) + if len(line)<3 or not line[:3].isdigit(): + if expected is None: break + continue + code=line[:3] + if expected is None: expected=code + if code==expected and (len(line)==3 or line[3:4]!="-"): return lines + if len(lines)>=max_lines: raise ValueError("SMTP multiline response too large") + return lines + +def _code(lines: List[str])->Optional[int]: + return int(lines[0][:3]) if lines and len(lines[0])>=3 and lines[0][:3].isdigit() else None class SMTPEnumerator: - DEFAULT_PORT = 25 - - @staticmethod - def _recv_line(sock: socket.socket, timeout: float = 5.0) -> str: - sock.settimeout(timeout) - data = b"" - while not data.endswith(b"\r\n") and not data.endswith(b"\n"): - try: - chunk = sock.recv(1024) - if not chunk: - break - data += chunk - except socket.timeout: - break - return data.decode("utf-8", errors="replace").strip() - + DEFAULT_PORT=25 + _recv_line=staticmethod(_recv_line) + _recv_response=staticmethod(_recv_response) @staticmethod - def _send(sock: socket.socket, cmd: str): - sock.send(f"{cmd}\r\n".encode()) - + def _send(sock: socket.socket,command: str)->None: + if "\r" in command or "\n" in command: raise ValueError("SMTP command contains line break") + sock.sendall(command.encode("ascii")+b"\r\n") @staticmethod - def check_open(ip: str, port: int = 25, timeout: float = 3.0) -> bool: + def check_open(ip: str,port: int=25,timeout: float=3.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - s.close() - return True - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout): return True + except OSError: return False @staticmethod - def banner(ip: str, port: int = 25, timeout: float = 5.0) -> str: + def banner(ip: str,port: int=25,timeout: float=5.0)->str: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - banner = SMTPEnumerator._recv_line(s, timeout) - s.close() - # Strip "220 " prefix - return re.sub(r"^220\s+", "", banner) - except Exception: - return "" - + with socket.create_connection((ip,port),timeout=timeout) as sock: + lines=_recv_response(sock,timeout) + return lines[0][4:].strip() if lines and lines[0].startswith("220") else "" + except (OSError,ValueError,ConnectionError): return "" + @staticmethod + def _ehlo(sock: socket.socket,timeout: float)->List[str]: + SMTPEnumerator._send(sock,"EHLO spectrascan.local") + lines=_recv_response(sock,timeout) + if _code(lines)!=250: + SMTPEnumerator._send(sock,"HELO spectrascan.local"); lines=_recv_response(sock,timeout) + return lines @staticmethod - def vrfy_users(ip: str, users: List[str], port: int = 25, timeout: float = 5.0) -> List[str]: - valid = [] + def vrfy_users(ip: str,users: List[str],port: int=25,timeout: float=5.0)->List[str]: + valid=[] try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - SMTPEnumerator._recv_line(s, timeout) # banner - SMTPEnumerator._send(s, "EHLO spectra.local") - SMTPEnumerator._recv_line(s, timeout) - - for user in users: - SMTPEnumerator._send(s, f"VRFY {user}") - resp = SMTPEnumerator._recv_line(s, timeout) - if resp.startswith("252") or resp.startswith("250"): - valid.append(user) - s.send(b"QUIT\r\n") - s.close() - except Exception: - pass + with socket.create_connection((ip,port),timeout=timeout) as sock: + _recv_response(sock,timeout); SMTPEnumerator._ehlo(sock,timeout) + for user in users: + SMTPEnumerator._send(sock,f"VRFY {user}") + if _code(_recv_response(sock,timeout)) in (250,252): valid.append(user) + SMTPEnumerator._send(sock,"QUIT"); _recv_response(sock,timeout) + except (OSError,ValueError,ConnectionError): pass return valid - @staticmethod - def check_open_relay(ip: str, port: int = 25, timeout: float = 10.0, - test_from: str = "test@spectra.local", - test_to: str = "test@googlemail.com") -> Dict: - result = {"open_relay": False, "evidence": []} + def check_open_relay(ip: str,port: int=25,timeout: float=10.0, + test_from: str="test@spectra.local",test_to: str="test@example.net")->Dict[str,Any]: + result={"open_relay":False,"evidence":[],"classification":"not_detected"} try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - SMTPEnumerator._recv_line(s, timeout) - SMTPEnumerator._send(s, "EHLO relaytest.local") - SMTPEnumerator._recv_line(s, timeout) - SMTPEnumerator._send(s, f"MAIL FROM:<{test_from}>") - resp = SMTPEnumerator._recv_line(s, timeout) - if not resp.startswith("250"): - s.close() - return result - SMTPEnumerator._send(s, f"RCPT TO:<{test_to}>") - resp = SMTPEnumerator._recv_line(s, timeout) - if resp.startswith("250"): - result["open_relay"] = True - result["evidence"].append(f"Server accepted RCPT TO:<{test_to}> from {test_from}") - s.send(b"QUIT\r\n") - s.close() - except Exception as e: - result["error"] = str(e) + with socket.create_connection((ip,port),timeout=timeout) as sock: + _recv_response(sock,timeout); SMTPEnumerator._ehlo(sock,timeout) + SMTPEnumerator._send(sock,f"MAIL FROM:<{test_from}>") + if _code(_recv_response(sock,timeout))!=250: return result + SMTPEnumerator._send(sock,f"RCPT TO:<{test_to}>") + if _code(_recv_response(sock,timeout))==250: + result["open_relay"]=True; result["classification"]="potential" + result["evidence"].append("External RCPT TO accepted without authentication; no DATA/message was sent.") + SMTPEnumerator._send(sock,"RSET"); _recv_response(sock,timeout) + SMTPEnumerator._send(sock,"QUIT"); _recv_response(sock,timeout) + except (OSError,ValueError,ConnectionError) as exc: result["error"]=type(exc).__name__ return result - @staticmethod - def check_starttls(ip: str, port: int = 25, timeout: float = 5.0) -> bool: + def check_starttls(ip: str,port: int=25,timeout: float=5.0)->bool: try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(timeout) - s.connect((ip, port)) - SMTPEnumerator._recv_line(s, timeout) - SMTPEnumerator._send(s, "EHLO spectra.local") - SMTPEnumerator._recv_line(s, timeout) - SMTPEnumerator._send(s, "STARTTLS") - resp = SMTPEnumerator._recv_line(s, timeout) - s.close() - return resp.startswith("220") - except Exception: - return False - + with socket.create_connection((ip,port),timeout=timeout) as sock: + _recv_response(sock,timeout); capabilities=SMTPEnumerator._ehlo(sock,timeout) + if not any("STARTTLS" in line.upper() for line in capabilities[1:]): return False + SMTPEnumerator._send(sock,"STARTTLS") + return _code(_recv_response(sock,timeout))==220 + except (OSError,ValueError,ConnectionError): return False @staticmethod - def scan(ip: str, port: int = 25, test_relay: bool = True, - users_to_test: List[str] = None) -> Dict: - result = { - "module": "smtp", "target": ip, "port": port, - "open": False, "banner": "", "starttls": False, - "open_relay": False, "valid_users": [], - "vulnerabilities": [] - } - if not SMTPEnumerator.check_open(ip, port): - return result - result["open"] = True - - result["banner"] = SMTPEnumerator.banner(ip, port) - result["starttls"] = SMTPEnumerator.check_starttls(ip, port) - - if users_to_test is None: - users_to_test = ["root", "admin", "postmaster", "test", "info", "mail"] - result["valid_users"] = SMTPEnumerator.vrfy_users(ip, users_to_test, port) - + def scan(ip: str,port: int=25,test_relay: bool=True,users_to_test: List[str]=None)->Dict[str,Any]: + result={"module":"smtp","target":ip,"port":port,"open":False,"banner":"","starttls":None, + "open_relay":False,"valid_users":[],"vulnerabilities":[],"observations":[]} + if not SMTPEnumerator.check_open(ip,port): return result + result["open"]=True; result["banner"]=SMTPEnumerator.banner(ip,port) + result["starttls"]=SMTPEnumerator.check_starttls(ip,port) + if not result["starttls"]: + result["observations"].append("STARTTLS was not successfully negotiated; this alone does not prove credentials are sent in plaintext.") + result["valid_users"]=SMTPEnumerator.vrfy_users(ip,users_to_test or ["root","admin","postmaster","test","info","mail"],port) if result["valid_users"]: - result["vulnerabilities"].append({ - "name": f"VRFY command enabled - {len(result['valid_users'])} users enumerated", - "severity": "MEDIUM", - "cve": "N/A" - }) - + result["vulnerabilities"].append({"name":f"SMTP VRFY disclosed {len(result['valid_users'])} user(s)","severity":"LOW","cve":"N/A"}) if test_relay: - relay = SMTPEnumerator.check_open_relay(ip, port) - result["open_relay"] = relay.get("open_relay", False) + relay=SMTPEnumerator.check_open_relay(ip,port); result["open_relay"]=relay.get("open_relay",False) if result["open_relay"]: - result["vulnerabilities"].append({ - "name": "SMTP open relay detected", - "severity": "HIGH", - "cve": "N/A" - }) - - if not result["starttls"]: - result["vulnerabilities"].append({ - "name": "STARTTLS not supported - credentials transmitted in plaintext", - "severity": "MEDIUM", - "cve": "N/A" - }) - - return result \ No newline at end of file + result["vulnerabilities"].append({"name":"Potential SMTP open relay; RCPT accepted but no message was sent", + "severity":"MEDIUM","cve":"N/A","evidence":relay.get("evidence",[])}) + return result From 2e50b4946bbf51c4c79ac08c24a643d826419fc9 Mon Sep 17 00:00:00 2001 From: ItsWanheda Date: Thu, 5 Nov 2026 13:23:00 +0330 Subject: [PATCH 3/6] fix(cli): route URL targets and protocol menu through real scanners --- SpectraScan.py | 208 ++++++++---------------------------- modules/network_services.py | 8 +- 2 files changed, 51 insertions(+), 165 deletions(-) diff --git a/SpectraScan.py b/SpectraScan.py index 68eccdb..329f9e7 100644 --- a/SpectraScan.py +++ b/SpectraScan.py @@ -7,6 +7,7 @@ import socket import concurrent.futures import argparse +import asyncio import sys import time import json @@ -4392,26 +4393,32 @@ def normalize_target(target: str) -> str: def resolve_host(hostname: str) -> str: - """Resolve a single host or IP. CIDR networks must use the network-scan path.""" + """Resolve an IP, hostname, or HTTP(S) URL to the IPv4 address used by legacy probes.""" target = normalize_target(hostname) if not target: raise ValueError("Target cannot be empty") + parsed = urllib.parse.urlsplit(target) + if parsed.scheme: + if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname: + raise ValueError("Only valid HTTP(S) URLs can be used as scan targets") + host = parsed.hostname + else: + host = target try: - return str(ipaddress.ip_address(target)) + return str(ipaddress.ip_address(host)) except ValueError: pass - if "/" in target: + if "/" in host: try: - network = ipaddress.ip_network(target, strict=False) + network = ipaddress.ip_network(host, strict=False) except ValueError: pass else: raise ValueError(f"CIDR network detected: {network}") try: - return socket.gethostbyname(target) + return socket.gethostbyname(host) except socket.gaierror as exc: - raise ValueError(f"Cannot resolve target: {target}") from exc - + raise ValueError(f"Cannot resolve target host: {host}") from exc def reverse_dns(ip: str) -> str: """Reverse DNS lookup""" try: @@ -5327,231 +5334,106 @@ def scan_network(network: str, ports: List[int] = None, **kwargs) -> List[Dict]: # ============== Protocol Module Scanner ============== class ProtocolModuleScanner: - """Stub implementation of protocol scanners. - Replace these methods with calls into the real modules in ./modules if present. - """ + """Interactive-menu adapter that dispatches to the real protocol modules.""" @staticmethod def _print_result(name: str, result: Dict): console.print(f"\n[bold cyan]--- {name} ---[/bold cyan]") - if isinstance(result, dict): - for key, value in result.items(): - console.print(f" [green]{key}:[/green] {value}") - else: - console.print(f" {result}") + console.print(json.dumps(result, indent=2, ensure_ascii=False, default=str), markup=False) @staticmethod - def _tcp_probe(ip: str, port: int, timeout: float = 5.0) -> Dict: - result = {"ip": ip, "port": port, "state": "closed", "banner": None} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(timeout) - if sock.connect_ex((ip, port)) == 0: - result["state"] = "open" - try: - sock.settimeout(2.0) - data = sock.recv(256) - if data: - result["banner"] = data.decode("utf-8", errors="ignore").strip() - except: - pass - sock.close() - except socket.timeout: - result["state"] = "filtered" - except Exception as e: - result["state"] = "error" - result["error"] = str(e) - return result + def _ip(target: str) -> str: + if not target or "/" in target: + raise ValueError("Protocol enumeration requires one authorized host") + return resolve_host(target) @staticmethod def run_smb(target: str): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, 445) + result = SMBEnumerator.scan(ProtocolModuleScanner._ip(target)) ProtocolModuleScanner._print_result("SMB Enumerator", result) return result @staticmethod def run_snmp(target: str): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, 161, timeout=3.0) - # SNMP is UDP, so do a quick UDP probe too - try: - usock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - usock.settimeout(3.0) - probe = b"\x30\x00\x00\x00\x02\x01\x00\x04\x06public\xa0\x1f\x02\x01\x00\x02\x01\x00\x30\x14" - usock.sendto(probe, (ip, 161)) - data, _ = usock.recvfrom(1024) - result["snmp_response"] = data.hex()[:100] - result["state"] = "open" - usock.close() - except socket.timeout: - result["snmp_response"] = None - except Exception as e: - result["snmp_error"] = str(e) + from modules.snmp_enum import SNMPEnumerator + result = SNMPEnumerator.scan(ProtocolModuleScanner._ip(target)) ProtocolModuleScanner._print_result("SNMP Enumerator", result) return result @staticmethod def run_ldap(target: str, port: int = 389): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, port) + result = LDAPEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("LDAP Enumerator", result) return result @staticmethod def run_rdp(target: str): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, 3389) + from modules.rdp_enum import RDPEnumerator + result = RDPEnumerator.scan(ProtocolModuleScanner._ip(target)) ProtocolModuleScanner._print_result("RDP Enumerator", result) return result @staticmethod def run_smtp(target: str, port: int = 25, test_relay: bool = True): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = {"banner": None, "open_relay": None, "error": None} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(5) - sock.connect((ip, port)) - banner = sock.recv(1024).decode("utf-8", errors="ignore").strip() - result["banner"] = banner - if test_relay: - sock.send(b"EHLO test.local\r\n") - sock.recv(1024) - sock.send(b"MAIL FROM:\r\n") - resp = sock.recv(1024).decode("utf-8", errors="ignore") - sock.send(b"RCPT TO:\r\n") - resp2 = sock.recv(1024).decode("utf-8", errors="ignore") - result["open_relay"] = "250" in resp2 - sock.send(b"QUIT\r\n") - sock.close() - except Exception as e: - result["error"] = str(e) + from modules.smtp_enum import SMTPEnumerator + result = SMTPEnumerator.scan(ProtocolModuleScanner._ip(target), port=port, test_relay=test_relay) ProtocolModuleScanner._print_result("SMTP Enumerator", result) return result @staticmethod def run_dns_zone(domain: str): - result = {"domain": domain, "records": {}} - try: - import dns.resolver - import dns.zone - import dns.query - ns_answers = dns.resolver.resolve(domain, "NS") - for ns in ns_answers: - ns_str = str(ns).rstrip(".") - try: - z = dns.zone.from_xfr(dns.query.xfr(ns_str, domain, timeout=5)) - result["records"][ns_str] = [str(n) for n in z.nodes.keys()] - except Exception as e: - result["records"][ns_str] = f"Transfer failed: {e}" - except ImportError: - result["records"]["error"] = "dnspython not installed" - except Exception as e: - result["records"]["error"] = str(e) + result = DNSZone.scan(domain) ProtocolModuleScanner._print_result("DNS Zone Transfer", result) return result @staticmethod def run_nfs(target: str): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, 2049) + from modules.nfs_enum import NFSEnumerator + result = NFSEnumerator.scan(ProtocolModuleScanner._ip(target)) ProtocolModuleScanner._print_result("NFS Enumerator", result) return result @staticmethod def run_vnc(target: str, port: int = 5900): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = ProtocolModuleScanner._tcp_probe(ip, port) + from modules.vnc_enum import VNCEnumerator + result = VNCEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("VNC Enumerator", result) return result @staticmethod def run_redis(target: str, port: int = 6379): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = {"ip": ip, "port": port} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(5) - sock.connect((ip, port)) - sock.send(b"PING\r\n") - data = sock.recv(1024).decode("utf-8", errors="ignore").strip() - result["response"] = data - result["unauth"] = "PONG" in data - sock.close() - except Exception as e: - result["error"] = str(e) + from modules.redis_enum import RedisEnumerator + result = RedisEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("Redis Enumerator", result) return result @staticmethod def run_mongodb(target: str, port: int = 27017): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = {"ip": ip, "port": port} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(5) - sock.connect((ip, port)) - # Send a minimal ismaster command - sock.close() - result["state"] = "open" - except Exception as e: - result["error"] = str(e) + from modules.mongodb_enum import MongoDBEnumerator + result = MongoDBEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("MongoDB Enumerator", result) return result @staticmethod def run_sip(target: str, port: int = 5060): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = {"ip": ip, "port": port, "state": "unknown"} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.settimeout(3.0) - sock.sendto(b"OPTIONS sip:test@" + ip.encode() + b" SIP/2.0\r\n\r\n", (ip, port)) - data, _ = sock.recvfrom(1024) - result["state"] = "open" - result["response"] = data.decode("utf-8", errors="ignore").strip()[:200] - sock.close() - except socket.timeout: - result["state"] = "open|filtered" - except Exception as e: - result["error"] = str(e) + from modules.sip_enum import SIPEnumerator + result = SIPEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("SIP Enumerator", result) return result @staticmethod def run_rtsp(target: str, port: int = 554): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - result = {"ip": ip, "port": port} - try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(5) - sock.connect((ip, port)) - sock.send(b"OPTIONS * RTSP/1.0\r\nCSeq: 1\r\n\r\n") - data = sock.recv(1024).decode("utf-8", errors="ignore").strip() - result["response"] = data[:200] - result["state"] = "open" - sock.close() - except Exception as e: - result["error"] = str(e) + from modules.rtsp_enum import RTSPEnumerator + result = RTSPEnumerator.scan(ProtocolModuleScanner._ip(target), port=port) ProtocolModuleScanner._print_result("RTSP Enumerator", result) return result @staticmethod def run_databases(target: str): - ip = target if target.replace(".", "").isdigit() else resolve_host(target) - db_ports = { - "mysql": 3306, - "postgres": 5432, - "mssql": 1433, - "oracle": 1521, - } - results = {} - for db, port in db_ports.items(): - results[db] = ProtocolModuleScanner._tcp_probe(ip, port, timeout=3.0) - for db_name, db_result in results.items(): - ProtocolModuleScanner._print_result(db_name.upper(), db_result) - return results + from modules.database_enum import scan_all_databases + result = scan_all_databases(ProtocolModuleScanner._ip(target)) + ProtocolModuleScanner._print_result("Database Enumerator", result) + return result def run_protocol_modules(): diff --git a/modules/network_services.py b/modules/network_services.py index 7d56ba0..3b48b1e 100644 --- a/modules/network_services.py +++ b/modules/network_services.py @@ -19,8 +19,12 @@ def scan_port_with_service(ip: str,port: int,**kwargs: Any)->Dict[str,Any]: name,func=SERVICE_MAP.get(port,(None,None)) if func is None: return {"module":name or "unknown","target":ip,"port":port,"skipped":True} - try: return func(ip,port=port,**kwargs) - except Exception as exc: return {"module":name,"target":ip,"port":port,"error":type(exc).__name__} + try: + if port in (161, 2049): + return func(ip, **kwargs) + return func(ip, port=port, **kwargs) + except Exception as exc: + return {"module":name,"target":ip,"port":port,"error":type(exc).__name__} def deep_scan(ip: str,ports: List[int]=None,max_workers: int=5)->Dict[str,Any]: if isinstance(max_workers,bool) or not 1<=int(max_workers)<=32: raise ValueError("max_workers must be 1..32") From 33e07fedd695bf42c65bf20e1a4d36b045c36256 Mon Sep 17 00:00:00 2001 From: ItsWanheda Date: Thu, 5 Nov 2026 13:25:22 +0330 Subject: [PATCH 4/6] test(protocols): add parser regressions and CI security coverage --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 18 +++++ README.md | 4 ++ tests/test_protocol_parsers.py | 128 +++++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 1 deletion(-) create mode 100644 tests/test_protocol_parsers.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b9d393..05aef58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,7 @@ jobs: run: python -m unittest discover -s tests -p "test_*.py" - name: Static security checks for hardened modules if: runner.os == 'Linux' - run: bandit -r modules/async_scanner.py modules/brute_forcer.py modules/vuln_scanner.py modules/report_store.py -ll + run: bandit -r modules/async_scanner.py modules/brute_forcer.py modules/vuln_scanner.py modules/report_store.py modules/snmp_enum.py modules/mongodb_enum.py modules/redis_enum.py modules/database_enum.py modules/nfs_enum.py modules/rdp_enum.py modules/rtsp_enum.py modules/smtp_enum.py modules/network_services.py -ll - name: Dependency vulnerability audit if: runner.os == 'Linux' && matrix.python-version == '3.12' run: pip-audit -r requirements.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index f6d1000..ccac53a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,24 @@ This release records the feature and hardening work present on \`main\`. The rel --- +## [2.2.4b] โ€” Stabilization candidate (unreleased) + +### Fixed +- Repair SNMP BER integer, OID, and response parsing; use cross-platform executable discovery for the optional snmpwalk fallback. +- Correct MongoDB OP_MSG framing and BSON lengths, nested documents, arrays, and boolean handling. +- Correct Redis RESP parsing and version extraction; only report unauthenticated INFO exposure when that command succeeds. +- Correct MySQL packet-length parsing and PostgreSQL SSLRequest/startup-message framing. +- Correct NFS RPC/XDR record lengths and export parsing; use PATH-based showmount discovery on Windows and POSIX. +- Parse RDP negotiation responses accurately and avoid inferring BlueKeep from an open port; parse RTSP status, headers, and SDP separately. +- Consume complete multiline SMTP responses and avoid claiming plaintext credential exposure solely because STARTTLS is unavailable. +- Route interactive protocol menu actions through their actual protocol modules and preserve per-port results for duplicate service names. +- Accept HTTP(S) URLs as legacy CLI scan targets and handle async scan exceptions without a missing import. + +### Validation +- Add protocol parser and dispatch regression tests. +- Extend Bandit checks to the modified protocol and aggregator modules. +- Release readiness depends on the complete Python 3.10โ€“3.12 Linux/Windows test matrix. + ## [Unreleased] ### Planned diff --git a/README.md b/README.md index 521dfc9..0259a13 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,10 @@ The current `main` branch contains the 2.2.0 feature set. This release builds on > **Release integrity:** this documents the `main` code state; it does not claim a GitHub Release or PyPI package has been published. +### Stabilization work + +The `fix/2.2.4b-stabilization` branch is the development track for the **2.2.4b** stabilization candidate. It is not a published release; readiness depends on the regression suite and Linux/Windows CI matrix. + ## ๐Ÿ“‘ Table of Contents - [๐ŸŽฏ Why SpectraScan?](#-why-spectrascan) diff --git a/tests/test_protocol_parsers.py b/tests/test_protocol_parsers.py new file mode 100644 index 0000000..c224e6b --- /dev/null +++ b/tests/test_protocol_parsers.py @@ -0,0 +1,128 @@ +"""Regression coverage for protocol encoders, parsers, and dispatch.""" +import io +import struct +import unittest +from unittest.mock import patch + +import SpectraScan +from modules import network_services +from modules.database_enum import MySQLEnumerator, PostgreSQLEnumerator +from modules.mongodb_enum import MongoDBEnumerator +from modules.nfs_enum import _parse_exports, _parse_portmap_dump +from modules.rdp_enum import _parse_negotiation +from modules.redis_enum import _read_resp +from modules.rtsp_enum import _parse_response +from modules.smtp_enum import _recv_response +from modules.snmp_enum import SNMPEnumerator, _decode_oid, _oid + +class FakeSocket: + def __init__(self, payload): + self.payload = bytearray(payload) + def settimeout(self, _timeout): + pass + def recv(self, size): + chunk = bytes(self.payload[:size]) + del self.payload[:size] + return chunk + +def xdr_string(value): + raw = value.encode() + return struct.pack(">I", len(raw)) + raw + (b"\x00" * ((-len(raw)) % 4)) + +class TestSNMPEncoding(unittest.TestCase): + def test_oid_uses_base128_arc_encoding(self): + encoded = _oid("1.3.6.1.4.1.8072.3.2.10") + self.assertEqual(encoded[0], 0x06) + self.assertEqual(_decode_oid(encoded[2:2 + encoded[1]]), "1.3.6.1.4.1.8072.3.2.10") + def test_integer_128_is_positive_and_canonical(self): + self.assertEqual(SNMPEnumerator._ber_encode_integer(128), b"\x02\x02\x00\x80") + def test_get_request_builds_valid_sequence(self): + packet = SNMPEnumerator._build_get_request("public", "1.3.6.1.2.1.1.1.0", 7) + self.assertEqual(packet[0], 0x30) + self.assertEqual(packet[2], 0x02) + +class TestMongoDBBson(unittest.TestCase): + def test_bool_is_encoded_as_boolean_not_int32(self): + encoded = MongoDBEnumerator._bson_encode({"enabled": True, "count": 3}) + self.assertIn(b"\x08enabled\x00\x01", encoded) + self.assertEqual(MongoDBEnumerator._parse_bson(encoded), {"enabled": True, "count": 3}) + def test_arrays_and_nested_documents_round_trip(self): + value = {"names": ["one", "two"], "meta": {"ok": True}} + self.assertEqual(MongoDBEnumerator._parse_bson(MongoDBEnumerator._bson_encode(value)), value) + def test_invalid_document_length_is_rejected(self): + with self.assertRaises(ValueError): + MongoDBEnumerator._parse_bson(b"\x04\x00\x00\x00\x00") + +class TestRedisResp(unittest.TestCase): + def test_simple_bulk_integer_and_array_responses(self): + self.assertEqual(_read_resp(io.BytesIO(b"+PONG\r\n")), "PONG") + self.assertEqual(_read_resp(io.BytesIO(b"$3\r\nfoo\r\n")), "foo") + self.assertEqual(_read_resp(io.BytesIO(b":12\r\n")), 12) + self.assertEqual(_read_resp(io.BytesIO(b"*2\r\n+one\r\n:2\r\n")), ["one", 2]) + +class TestDatabaseProtocols(unittest.TestCase): + def test_mysql_handshake_version_parsing(self): + self.assertEqual(MySQLEnumerator.parse_handshake(b"\x0a8.0.36\x00rest"), "8.0.36") + def test_postgresql_ssl_request_is_exactly_eight_bytes(self): + request = struct.pack(">II", 8, 80877103) + self.assertEqual(len(request), 8) + self.assertEqual(struct.unpack(">II", request), (8, 80877103)) + def test_postgresql_startup_message_length_matches_packet(self): + packet = PostgreSQLEnumerator.startup_message() + self.assertEqual(struct.unpack(">I", packet[:4])[0], len(packet)) + +class TestNFSXdr(unittest.TestCase): + def test_portmapper_dump_parses_mountd_tuple(self): + header = struct.pack(">6I", 1, 1, 0, 0, 0, 0) + payload = header + struct.pack(">I4I", 1, 100005, 1, 6, 20048) + struct.pack(">I", 0) + self.assertEqual(_parse_portmap_dump(payload)["mountd"]["port"], 20048) + self.assertEqual(_parse_portmap_dump(payload)["mountd"]["protocol"], 6) + def test_mountd_export_groups_are_parsed(self): + header = struct.pack(">6I", 1, 1, 0, 0, 0, 0) + payload = header + struct.pack(">I", 1) + xdr_string("/srv/share") + payload += struct.pack(">I", 1) + xdr_string("*") + struct.pack(">I", 0) + struct.pack(">I", 0) + self.assertEqual(_parse_exports(payload), [{"path": "/srv/share", "allowed_clients": ["*"]}]) + +class TestRDPAndRTSP(unittest.TestCase): + def test_rdp_hybrid_response_is_nla_capable(self): + response = b"\x03\x00\x00\x0c\x02\x00\x08\x00" + struct.pack(" Date: Thu, 5 Nov 2026 13:27:28 +0330 Subject: [PATCH 5/6] fix(protocols): tighten RDP SMTP and CLI edge cases --- SpectraScan.py | 12 +++++++++--- modules/rdp_enum.py | 2 +- modules/smtp_enum.py | 2 +- tests/test_protocol_parsers.py | 4 +++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/SpectraScan.py b/SpectraScan.py index 329f9e7..1daa7c2 100644 --- a/SpectraScan.py +++ b/SpectraScan.py @@ -4393,17 +4393,23 @@ def normalize_target(target: str) -> str: def resolve_host(hostname: str) -> str: - """Resolve an IP, hostname, or HTTP(S) URL to the IPv4 address used by legacy probes.""" + """Resolve an IP, hostname, host:port, or HTTP(S) URL for legacy IPv4 probes.""" target = normalize_target(hostname) if not target: raise ValueError("Target cannot be empty") - parsed = urllib.parse.urlsplit(target) - if parsed.scheme: + if "://" in target: + parsed = urllib.parse.urlsplit(target) if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname: raise ValueError("Only valid HTTP(S) URLs can be used as scan targets") host = parsed.hostname else: host = target + if host.startswith("[") and "]" in host: + host = host[1:host.index("]")] + elif host.count(":") == 1: + candidate, port = host.rsplit(":", 1) + if port.isdigit() and candidate: + host = candidate try: return str(ipaddress.ip_address(host)) except ValueError: diff --git a/modules/rdp_enum.py b/modules/rdp_enum.py index b513d0a..ef9cf3c 100644 --- a/modules/rdp_enum.py +++ b/modules/rdp_enum.py @@ -10,7 +10,7 @@ PROTOCOL_HYBRID_EX=0x08 def _connection_request(protocols: int)->bytes: - cookie=b"Cookie: mstshash:spectrascan\r\n" + cookie=b"Cookie: mstshash=spectrascan\r\n" negotiation=struct.pack("bool: try: with socket.create_connection((ip,port),timeout=timeout) as sock: _recv_response(sock,timeout); capabilities=SMTPEnumerator._ehlo(sock,timeout) - if not any("STARTTLS" in line.upper() for line in capabilities[1:]): return False + if not any("STARTTLS" in line.upper() for line in capabilities): return False SMTPEnumerator._send(sock,"STARTTLS") return _code(_recv_response(sock,timeout))==220 except (OSError,ValueError,ConnectionError): return False diff --git a/tests/test_protocol_parsers.py b/tests/test_protocol_parsers.py index c224e6b..5e15840 100644 --- a/tests/test_protocol_parsers.py +++ b/tests/test_protocol_parsers.py @@ -94,7 +94,7 @@ def test_rdp_ssl_response_is_not_nla(self): self.assertFalse(_parse_negotiation(response)["nla"]) def test_rtsp_headers_and_sdp_are_separate(self): raw = (b"RTSP/1.0 200 OK\r\nServer: camera-test\r\nContent-Type: application/sdp\r\n" - b"Content-Length: 25\r\n\r\nv=0\r\nm=video 5004 RTP/AVP 96\r\n") + b"Content-Length: 30\r\n\r\nv=0\r\nm=video 5004 RTP/AVP 96\r\n") parsed = _parse_response(raw) self.assertEqual(parsed["status_code"], 200) self.assertEqual(parsed["server"], "camera-test") @@ -118,6 +118,8 @@ def test_protocol_results_do_not_overwrite_same_service(self): self.assertEqual(set(result["scans"]), {"smb:139", "smb:445", "ldap:389", "ldap:636"}) def test_legacy_target_resolution_accepts_http_url(self): self.assertEqual(SpectraScan.resolve_host("https://127.0.0.1:8443/admin?q=1"), "127.0.0.1") + def test_legacy_target_resolution_accepts_bare_host_port(self): + self.assertEqual(SpectraScan.resolve_host("127.0.0.1:8080"), "127.0.0.1") def test_interactive_protocol_menu_uses_real_module_adapter(self): fake = {"module": "mongodb", "open": True} with patch("modules.mongodb_enum.MongoDBEnumerator.scan", return_value=fake) as scan: From 50af96d4a081f7754dc1e427747d90515f4ae47c Mon Sep 17 00:00:00 2001 From: ItsWanheda Date: Thu, 5 Nov 2026 13:51:56 +0330 Subject: [PATCH 6/6] docs(release): identify 2.2.4b as beta prerelease --- CHANGELOG.md | 15 +++++++++++---- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++---- SECURITY.md | 9 +++++++-- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccac53a..9bcfc6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,7 +55,11 @@ This release records the feature and hardening work present on \`main\`. The rel --- -## [2.2.4b] โ€” Stabilization candidate (unreleased) +## [2.2.4b] โ€” Beta prerelease (unreleased) + +> **Beta status:** 2.2.4b is an unreleased testing candidate on `fix/2.2.4b-stabilization`. It is not an official release artifact and is not recommended for production use. The stable `main` line remains 2.2.0. + +This beta concentrates on protocol wire-format correctness, evidence-based detection, CLI dispatch, and cross-platform regression coverage. No GitHub Release, tag, or PyPI distribution has been published for this candidate. ### Fixed - Repair SNMP BER integer, OID, and response parsing; use cross-platform executable discovery for the optional snmpwalk fallback. @@ -68,10 +72,13 @@ This release records the feature and hardening work present on \`main\`. The rel - Route interactive protocol menu actions through their actual protocol modules and preserve per-port results for duplicate service names. - Accept HTTP(S) URLs as legacy CLI scan targets and handle async scan exceptions without a missing import. -### Validation -- Add protocol parser and dispatch regression tests. +### Beta validation +- Add protocol parser and dispatch regression tests; the complete automated suite passes (48 tests). - Extend Bandit checks to the modified protocol and aggregator modules. -- Release readiness depends on the complete Python 3.10โ€“3.12 Linux/Windows test matrix. +- The six-job Linux/Windows matrix passes on Python 3.10, 3.11, and 3.12. +- Bandit at `-ll` reports zero medium/high findings; seven low-severity findings remain. +- The dependency audit passes on the Linux Python 3.12 job. +- CI validates automated coverage and static checks, not live interoperability with every real-world service. Continue authorized lab validation before treating the beta as production-ready. ## [Unreleased] diff --git a/README.md b/README.md index 0259a13..14ac05e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Python Platform - Status + Status Black PRs Welcome

@@ -33,15 +33,56 @@ --- -## ๐Ÿ“ฆ Current release: 2.2.0 +## ๐Ÿ“ฆ Current stable release: 2.2.0 The current `main` branch contains the 2.2.0 feature set. This release builds on 2.1.0 with an additive async TCP scanner, bounded optional NVD CVE correlation, stricter CLI validation, bounded CIDR scans, safer credential-checking defaults, and more reliable report exports. See [CHANGELOG.md](CHANGELOG.md) for detailed release notes and [SECURITY.md](SECURITY.md) for supported versions and vulnerability reporting. > **Release integrity:** this documents the `main` code state; it does not claim a GitHub Release or PyPI package has been published. -### Stabilization work +### ๐Ÿงช Beta channel: 2.2.4b Beta -The `fix/2.2.4b-stabilization` branch is the development track for the **2.2.4b** stabilization candidate. It is not a published release; readiness depends on the regression suite and Linux/Windows CI matrix. +> โš ๏ธ **Pre-release software โ€” testing only.** The `fix/2.2.4b-stabilization` branch is a beta candidate, not a stable release. It may still contain defects or incomplete protocol coverage. Do not use it as your only security control or as the basis for production decisions. + +The current `main` branch remains the stable 2.2.0 line. The **2.2.4b Beta** is a separate pre-release track focused on protocol correctness, more conservative service detection, CLI routing, and cross-platform reliability. + +**Beta scope** +- Corrected SNMP BER, MongoDB OP_MSG/BSON, Redis RESP, MySQL/PostgreSQL framing, and NFS RPC/XDR handling. +- More evidence-based RDP, RTSP, and SMTP results, including removal of unsupported vulnerability conclusions. +- Fixed URL target handling, protocol-menu dispatch, async error handling, and per-port aggregation. +- Added protocol regression coverage and a Linux/Windows CI matrix. + +**Validation recorded for this beta branch** +- โœ… Six CI jobs passed: Linux and Windows with Python 3.10, 3.11, and 3.12. +- โœ… The automated test suite passed (48 tests). +- โœ… Bandit at the configured `-ll` threshold reported no medium- or high-severity findings; seven low-severity findings remain. +- โœ… The dependency audit passed on the Linux Python 3.12 job. + +These checks validate the automated test and static-analysis scope; they do **not** replace live interoperability testing against every supported service or guarantee that every target will be detected correctly. Validate results in an authorized lab and review findings before acting on them. + +**Try the beta from source** + +```bash +git clone https://github.com/ItsWanheda/SpectraScan.git +cd SpectraScan +git fetch origin +git switch --track origin/fix/2.2.4b-stabilization +python -m venv .venv +``` + +Activate the virtual environment, install dependencies, and run the regression suite: + +```bash +# Linux / macOS +source .venv/bin/activate + +# Windows PowerShell +.\.venv\Scripts\Activate.ps1 + +python -m pip install -r requirements.txt +python -m unittest discover -s tests -p "test_*.py" +``` + +**Distribution status:** this beta exists on the feature branch only. No official GitHub Release, version tag, or PyPI package has been published for 2.2.4b. The stable release remains 2.2.0 until a final release is explicitly published. ## ๐Ÿ“‘ Table of Contents diff --git a/SECURITY.md b/SECURITY.md index f1e4f74..2c89890 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,11 +8,16 @@ This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Th | Version line | Security support | Notes | |---|---|---| -| **2.2.x** | โœ… Current | Preferred line; security fixes and compatible patches | +| **2.2.x (stable)** | โœ… Current | Stable line; the current `main` branch documents 2.2.0 | +| **2.2.4b Beta** | ๐Ÿงช Preview only | Unreleased branch candidate; testing only, not a supported production release | | **2.1.x** | โš ๏ธ Best effort | Upgrade to 2.2.x where possible | | **2.0.x and earlier** | โŒ Unsupported | Upgrade before relying on security fixes | -Only versions explicitly published as releases should be treated as official release artifacts. The version documented on \`main\` may be ahead of a tagged release. +Only versions explicitly published as releases should be treated as official release artifacts. The version documented on `main` may be ahead of a tagged release. + +### Beta and other pre-release builds + +The **2.2.4b Beta** is available only from the `fix/2.2.4b-stabilization` development branch. It has passed the documented automated Linux/Windows Python 3.10โ€“3.12 CI matrix, but that does not establish complete protocol interoperability or production readiness. Treat it as preview software: test only in authorized, controlled environments, expect defects, and do not rely on it as the sole protection for production assets. Beta builds do not receive the same support commitment as published stable releases. ## Reporting a vulnerability