diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bcfc6b..36e9b9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [2.2.4] โ Stable release preparation (2026-11-07)
+
+> **Release status:** This branch prepares the 2.2.4 stable release. The version becomes an official published artifact when the release PR is merged and the corresponding GitHub tag/release is created.
+
+### Security
+
+- Validate SNMPv2c response version, request ID, community string, response PDU boundaries, and requested OID before accepting returned values.
+- Require MongoDB OP_MSG `responseTo` to equal the outstanding request ID; reject zero and every other mismatched value.
+- Remove the unsupported medium-severity RDP finding for disabled NLA. NLA negotiation without HYBRID/HYBRID_EX is retained as a configuration observation, not a confirmed vulnerability.
+- Keep BlueKeep status explicitly unassessed unless product, OS, and patch-level evidence is available.
+
+### Fixed
+
+- Enforce exact TPKT length, X.224 Connection Confirm type/length, and RDP negotiation structure before reporting a server response or NLA capability.
+- Validate RTSP status-line syntax and header structure; reject duplicate headers, malformed or oversized Content-Length values, and body-length mismatches.
+- Enforce SMTP multiline reply grammar, consistent three-digit status codes, valid terminating lines, and explicit failure for incomplete responses.
+
+### Tests
+
+- Add regression coverage for SNMP request-ID/community mismatches.
+- Add RDP malformed TPKT and negotiation-length cases.
+- Add MongoDB response-correlation tests for matching and zero/mismatched `responseTo` values.
+- Add RTSP malformed status, duplicate Content-Length, and declared-body-length tests.
+- Add SMTP inconsistent-code, malformed-line, and unterminated multiline-response tests.
+
+### Documentation
+
+- Replace the stale 2.2.0/Beta status in the README with the 2.2.4 stable-release target and its protocol/security changes.
+- Align supported-version guidance with the 2.2.4 release line.
+- Add a canonical `VERSION` file containing `2.2.4`.
+
+---
+
## [2.2.0] โ 2026-10-22
This release records the feature and hardening work present on \`main\`. The release number follows Semantic Versioning: 2.2.0 is a backward-compatible minor release after 2.1.0.
@@ -57,7 +90,7 @@ This release records the feature and hardening work present on \`main\`. The rel
## [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.
+> **Historical beta note:** At the time this prerelease was prepared, 2.2.4b was an unreleased testing candidate on `fix/2.2.4b-stabilization`; it was superseded by the 2.2.4 stable-release work documented above.
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.
diff --git a/README.md b/README.md
index 14ac05e..d8f4653 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
-
+
@@ -33,56 +33,36 @@
---
-## ๐ฆ Current stable release: 2.2.0
+## ๐ฆ Current stable release: 2.2.4
-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.
+**Version:** `2.2.4` ยท **Release line:** Stable ยท **Python:** 3.10โ3.12 CI target
-> **Release integrity:** this documents the `main` code state; it does not claim a GitHub Release or PyPI package has been published.
+SpectraScan 2.2.4 consolidates the 2.2.4b protocol-stabilization work and adds strict response validation for SNMP, RDP, MongoDB, RTSP, and SMTP. This release hardens packet correlation and framing, rejects malformed protocol responses, and keeps configuration observations separate from confirmed vulnerabilities.
-### ๐งช Beta channel: 2.2.4b Beta
+> **Release publication:** This branch prepares the 2.2.4 stable release. The official release artifact and version tag should be considered published only after the release PR is merged and the GitHub Release is created.
-> โ ๏ธ **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.
+### ๐ 2.2.4 security and protocol hardening
-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.
+- **SNMP:** validate SNMPv2c version, response request ID, community string, PDU framing, and the requested OID before accepting a response.
+- **RDP:** validate TPKT declared length, X.224 Connection Confirm framing, and the exact negotiation structure before deriving NLA status.
+- **MongoDB:** require the server's `responseTo` field to match the outstanding request ID; zero is no longer accepted as a wildcard.
+- **RDP findings:** report disabled NLA as a configuration observation, not as a medium-severity vulnerability by itself. BlueKeep remains unassessed without OS and patch-level evidence.
+- **RTSP:** reject malformed status/header framing, duplicate headers, invalid or oversized Content-Length values, and bodies whose received length does not match the declaration.
+- **SMTP:** reject malformed multiline replies, inconsistent status codes, and replies that end before a valid terminating line.
-**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 and regression coverage
-**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.
+The release adds regression cases for mismatched SNMP request IDs and communities, malformed RDP TPKT/X.224 lengths, MongoDB response correlation, RTSP Content-Length and status handling, and malformed or unterminated SMTP multiline replies.
-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:
+Run the complete local suite with:
```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.
+CI results and any remaining limitations are recorded in the pull request. Automated tests do not replace live interoperability checks against every implementation of these protocols.
+
+See [CHANGELOG.md](CHANGELOG.md) for the complete 2.2.4 notes and [SECURITY.md](SECURITY.md) for supported-version and reporting guidance.
## ๐ Table of Contents
diff --git a/SECURITY.md b/SECURITY.md
index 2c89890..dbfe150 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -4,20 +4,16 @@ SpectraScan is a network reconnaissance and security-assessment toolkit. Its act
## Supported versions
-This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The current \`main\` branch documents version 2.2.0. A supported version does not mean every optional module is free of defects; apply updates and validate findings before acting on them.
+This project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The current release line is **2.2.4 (stable)**. A supported version does not mean every optional module is free of defects; apply updates and validate findings before acting on them.
| Version line | Security support | Notes |
|---|---|---|
-| **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.2.4 (stable)** | โ
Current | Current stable release line |
+| **2.2.x** | โ ๏ธ Best effort | Upgrade to the latest 2.2.x release for current fixes |
+| **2.1.x** | โ ๏ธ Best effort | Upgrade to 2.2.4 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.
-
-### 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.
+Only versions explicitly published as GitHub Releases should be treated as official release artifacts. This branch prepares version 2.2.4; the release becomes published when the release PR is merged and its GitHub tag/release is created.
## Reporting a vulnerability
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..530cdd9
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+2.2.4
diff --git a/modules/mongodb_enum.py b/modules/mongodb_enum.py
index c408f97..3437c19 100644
--- a/modules/mongodb_enum.py
+++ b/modules/mongodb_enum.py
@@ -30,7 +30,7 @@ def _send_op_msg(sock: socket.socket,doc: bytes,request_id: int=1)->bytes:
response_length,_,response_to,opcode=struct.unpack("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")
+ if response_to != 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:]
diff --git a/modules/rdp_enum.py b/modules/rdp_enum.py
index ef9cf3c..e962b86 100644
--- a/modules/rdp_enum.py
+++ b/modules/rdp_enum.py
@@ -17,19 +17,57 @@ def _connection_request(protocols: int)->bytes:
tpdu=bytes([len(body)])+body
return struct.pack(">BBH",3,0,len(tpdu)+4)+tpdu
+def _recv_tpkt(sock: socket.socket, max_size: int=4096)->bytes:
+ header=bytearray()
+ while len(header)<4:
+ chunk=sock.recv(4-len(header))
+ if not chunk:
+ return b""
+ header.extend(chunk)
+ if header[0]!=3 or header[1]!=0:
+ return bytes(header)
+ declared=struct.unpack_from(">H",header,2)[0]
+ if declared<4 or declared>max_size:
+ return bytes(header)
+ packet=header
+ while len(packet)Dict[str,Any]:
result={"responds":False,"nla":None,"selected_protocol":None}
- if len(data)<11 or data[0]!=3: return result
+ # TPKT: version 3, reserved 0, and an exact 16-bit packet length.
+ if len(data)<4 or data[0]!=3 or data[1]!=0:
+ return result
+ declared=struct.unpack_from(">H",data,2)[0]
+ if declared!=len(data) or declared<12:
+ return result
+ # X.224 Connection Confirm (LI=6, code=0xD0, refs, class).
+ li=data[4]
+ if li!=6 or li!=len(data[5:]) - 8 or data[5]!=0xD0:
+ return result
+ negotiation_offset=5+li
+ if len(data)!=negotiation_offset+8:
+ return result
+ packet_type,flags,packet_length=struct.unpack_from("Dict[str,Any]:
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))
- data=sock.recv(4096)
+ data=_recv_tpkt(sock)
parsed=_parse_negotiation(data); result.update(parsed)
result["nla_likely"]=parsed.get("nla"); result["raw"]=data.hex()[:256]
except (OSError,ConnectionError) as exc: result["error"]=type(exc).__name__
@@ -68,10 +106,9 @@ def scan(ip: str,port: int=3389)->Dict[str,Any]:
negotiation=RDPEnumerator.check_nla(ip,port)
result["nla"]=negotiation.get("nla_likely")
if result["nla"] is False:
- result["vulnerabilities"].append({
- "name":"RDP negotiated without Network Level Authentication","severity":"MEDIUM","cve":"N/A",
- "evidence":f"Server selected protocol {negotiation.get('selected_protocol')}.",
- })
+ result["observations"].append(
+ "The server did not negotiate NLA for this connection request. This is a configuration observation, not a confirmed vulnerability."
+ )
elif result["nla"] is True:
result["observations"].append("RDP negotiation selected an NLA-capable protocol.")
else:
diff --git a/modules/rtsp_enum.py b/modules/rtsp_enum.py
index d6ea940..2bcc4ee 100644
--- a/modules/rtsp_enum.py
+++ b/modules/rtsp_enum.py
@@ -1,28 +1,55 @@
"""RTSP DESCRIBE with correct response header and SDP extraction."""
from __future__ import annotations
-import socket
+import re, socket
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
+ if b"\r\n\r\n" not in raw:
+ raise ValueError("RTSP response is missing the header terminator")
+ header,_,body=raw.partition(b"\r\n\r\n")
+ try:
+ lines=header.decode("latin-1").split("\r\n")
+ except UnicodeDecodeError as exc:
+ raise ValueError("Invalid RTSP headers") from exc
+ if not lines or not re.fullmatch(r"RTSP/1\.[0-9] [1-5][0-9]{2}(?: .*)?",lines[0]):
+ raise ValueError("Malformed RTSP status line")
+ code=int(lines[0].split(" ",2)[1])
headers={}
+ content_length=None
for line in lines[1:]:
+ if not line or line[0] in " \t":
+ raise ValueError("Malformed RTSP header line")
name,colon,value=line.partition(":")
- if colon: headers[name.strip().lower()]=value.strip()
+ if not colon or not name.strip():
+ raise ValueError("Malformed RTSP header")
+ key=name.strip().lower()
+ if key in headers:
+ raise ValueError("Duplicate RTSP header")
+ value=value.strip()
+ headers[key]=value
+ if key=="content-length":
+ if not value.isdigit():
+ raise ValueError("Invalid RTSP Content-Length")
+ content_length=int(value)
+ if content_length>65536:
+ raise ValueError("RTSP body exceeds parser limit")
+ if content_length is not None and len(body)!=content_length:
+ raise ValueError("RTSP Content-Length does not match received body")
+ body_text=body.decode("latin-1")
streams=[]
- for line in body.splitlines() if sep else []:
+ for line in body_text.splitlines():
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}
+ if len(parts)<3:
+ raise ValueError("Malformed SDP media line")
+ port_text=parts[1].split("/",1)[0]
+ if not port_text.isdigit():
+ raise ValueError("Invalid SDP media port")
+ streams.append({"type":parts[0],"port":int(port_text),
+ "protocol":parts[2],"formats":parts[3:]})
+ return {"status_code":code,"status_line":lines[0],
+ "headers":headers,"body":body_text,"streams":streams,"server":headers.get("server"),
+ "auth_required":code==401 or "www-authenticate" in headers,"open":True}
class RTSPEnumerator:
DEFAULT_PORT=554
diff --git a/modules/smtp_enum.py b/modules/smtp_enum.py
index 3c5d683..2ca428f 100644
--- a/modules/smtp_enum.py
+++ b/modules/smtp_enum.py
@@ -10,7 +10,11 @@ def _recv_line(sock: socket.socket,timeout: float=5.0,max_bytes: int=8192)->str:
if not part: break
data.extend(part)
if data.endswith(b"\n"): break
- if len(data)>=max_bytes and not data.endswith(b"\n"): raise ValueError("SMTP line too long")
+ if len(data)>=max_bytes and not data.endswith(b"\r\n"): raise ValueError("SMTP line too long")
+ if not data:
+ raise ConnectionError("SMTP server closed connection")
+ if not data.endswith(b"\r\n"):
+ raise ValueError("SMTP response line is not CRLF terminated")
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]:
@@ -18,17 +22,18 @@ def _recv_response(sock: socket.socket,timeout: float=5.0,max_lines: int=100)->L
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
+ raise ConnectionError("SMTP server closed before response terminator")
+ if len(line)<3 or not line[:3].isdigit() or (len(line)>3 and line[3] not in " -"):
+ raise ValueError("Malformed SMTP response line")
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
+ if expected is None:
+ expected=code
+ elif code!=expected:
+ raise ValueError("Inconsistent SMTP status code in multiline response")
+ lines.append(line)
+ if len(line)==3 or line[3:4]==" ":
+ return lines
+ raise ValueError("SMTP multiline response too large or missing final line")
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
diff --git a/modules/snmp_enum.py b/modules/snmp_enum.py
index 154ea48..ab24afe 100644
--- a/modules/snmp_enum.py
+++ b/modules/snmp_enum.py
@@ -69,18 +69,28 @@ def _decode_value(tag: int, raw: bytes) -> str:
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:
+def _parse_response(data: bytes, expected_oid: Optional[str]=None, expected_request_id: Optional[int]=None, expected_community: 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)
+ version_tag,version,pos=_read_tlv(msg,0)
+ if version_tag!=2 or int.from_bytes(version,"big",signed=True)!=1:
+ raise SNMPError("unsupported SNMP version")
+ community_tag,community,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)
+ if expected_community is not None and community!=expected_community.encode("utf-8"):
+ raise SNMPError("SNMP community mismatch")
+ pdu_tag,pdu,pdu_end=_read_tlv(msg,pos)
+ if pdu_tag!=162 or pdu_end!=len(msg): raise SNMPError("expected complete GetResponse PDU")
+ request_tag,request_raw,pos=_read_tlv(pdu,0)
+ if request_tag!=2: raise SNMPError("invalid SNMP request identifier")
+ request_id=int.from_bytes(request_raw,"big",signed=True)
+ if expected_request_id is not None and request_id!=expected_request_id:
+ raise SNMPError("SNMP request identifier mismatch")
status_tag,status,pos=_read_tlv(pdu,pos)
- _,_,pos=_read_tlv(pdu,pos)
- list_tag,bindings,_=_read_tlv(pdu,pos)
+ index_tag,index,pos=_read_tlv(pdu,pos)
+ if index_tag!=2: raise SNMPError("invalid SNMP error index")
+ list_tag,bindings,bindings_end=_read_tlv(pdu,pos)
+ if bindings_end!=len(pdu): raise SNMPError("trailing data in SNMP response PDU")
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)
@@ -114,11 +124,12 @@ def _build_get_request(community: str, oid: str, request_id: Optional[int]=None)
def query(ip: str, community: str, oid: str, timeout: float=3.0) -> Optional[str]:
try:
family=socket.AF_INET6 if ":" in ip else socket.AF_INET
+ request_id=random.randint(1,2**31-1)
with socket.socket(family,socket.SOCK_DGRAM) as sock:
sock.settimeout(timeout)
- sock.sendto(SNMPEnumerator._build_get_request(community,oid),(ip,161))
+ sock.sendto(SNMPEnumerator._build_get_request(community,oid,request_id),(ip,161))
data,_=sock.recvfrom(65535)
- value=_parse_response(data,oid)
+ value=_parse_response(data,oid,request_id,community)
return None if value.startswith("noSuch") or value=="NULL" else value
except (OSError,SNMPError,ValueError): return None
diff --git a/tests/test_protocol_parsers.py b/tests/test_protocol_parsers.py
index 5e15840..10a0532 100644
--- a/tests/test_protocol_parsers.py
+++ b/tests/test_protocol_parsers.py
@@ -9,17 +9,19 @@
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.rdp_enum import RDPEnumerator, _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
+from modules.snmp_enum import SNMPEnumerator, SNMPError, _decode_oid, _integer, _oid, _parse_response as _parse_snmp_response, _tlv
class FakeSocket:
def __init__(self, payload):
self.payload = bytearray(payload)
def settimeout(self, _timeout):
pass
+ def sendall(self, _data):
+ pass
def recv(self, size):
chunk = bytes(self.payload[:size])
del self.payload[:size]
@@ -29,6 +31,19 @@ def xdr_string(value):
raw = value.encode()
return struct.pack(">I", len(raw)) + raw + (b"\x00" * ((-len(raw)) % 4))
+def build_snmp_response(request_id=7, community="public", oid="1.3.6.1.2.1.1.1.0"):
+ binding = _tlv(0x30, _oid(oid) + _tlv(0x04, b"test-agent"))
+ bindings = _tlv(0x30, binding)
+ pdu = _tlv(0xA2, _integer(request_id) + _integer(0) + _integer(0) + bindings)
+ return _tlv(0x30, _integer(1) + _tlv(0x04, community.encode()) + pdu)
+
+
+def build_rdp_confirm(selected_protocol):
+ x224 = b"\x06\xd0\x00\x00\x00\x00\x00"
+ negotiation = struct.pack("H", len(payload) + 4) + payload
+
class TestSNMPEncoding(unittest.TestCase):
def test_oid_uses_base128_arc_encoding(self):
encoded = _oid("1.3.6.1.4.1.8072.3.2.10")
@@ -41,6 +56,14 @@ def test_get_request_builds_valid_sequence(self):
self.assertEqual(packet[0], 0x30)
self.assertEqual(packet[2], 0x02)
+ def test_response_requires_matching_request_id_and_community(self):
+ response = build_snmp_response()
+ self.assertEqual(_parse_snmp_response(response, expected_request_id=7, expected_community="public"), "test-agent")
+ with self.assertRaises(SNMPError):
+ _parse_snmp_response(response, expected_request_id=8, expected_community="public")
+ with self.assertRaises(SNMPError):
+ _parse_snmp_response(response, expected_request_id=7, expected_community="private")
+
class TestMongoDBBson(unittest.TestCase):
def test_bool_is_encoded_as_boolean_not_int32(self):
encoded = MongoDBEnumerator._bson_encode({"enabled": True, "count": 3})
@@ -53,6 +76,15 @@ def test_invalid_document_length_is_rejected(self):
with self.assertRaises(ValueError):
MongoDBEnumerator._parse_bson(b"\x04\x00\x00\x00\x00")
+ def test_op_msg_requires_exact_response_to_correlation(self):
+ document = MongoDBEnumerator._bson_encode({"ok": 1})
+ payload = struct.pack("H", len(packet) + 1) + packet[4:]
+ self.assertFalse(_parse_negotiation(malformed)["responds"])
+ malformed = packet[:-8] + struct.pack("H", len(malformed)) + malformed[4:]
+ self.assertFalse(_parse_negotiation(malformed)["responds"])
def test_rtsp_headers_and_sdp_are_separate(self):
+ body = b"v=0\r\nm=video 5004 RTP/AVP 96\r\n"
raw = (b"RTSP/1.0 200 OK\r\nServer: camera-test\r\nContent-Type: application/sdp\r\n"
- b"Content-Length: 30\r\n\r\nv=0\r\nm=video 5004 RTP/AVP 96\r\n")
+ + f"Content-Length: {len(body)}".encode() + b"\r\n\r\n" + body)
parsed = _parse_response(raw)
self.assertEqual(parsed["status_code"], 200)
self.assertEqual(parsed["server"], "camera-test")
self.assertEqual(parsed["streams"][0]["port"], 5004)
self.assertEqual(parsed["streams"][0]["type"], "video")
+ def test_rtsp_rejects_malformed_status_and_content_length(self):
+ with self.assertRaises(ValueError):
+ _parse_response(b"RTSP/1.0 200OK\r\n\r\n")
+ with self.assertRaises(ValueError):
+ _parse_response(b"RTSP/1.0 200 OK\r\nContent-Length: 8\r\n\r\nshort")
+ with self.assertRaises(ValueError):
+ _parse_response(b"RTSP/1.0 200 OK\r\nContent-Length: 0\r\ncontent-length: 0\r\n\r\n")
class TestSMTPResponses(unittest.TestCase):
def test_multiline_ehlo_is_consumed_until_final_code_line(self):
@@ -109,6 +164,16 @@ def test_multiline_ehlo_is_consumed_until_final_code_line(self):
self.assertTrue(any("STARTTLS" in line for line in response))
self.assertEqual(_recv_response(sock), ["220 Ready"])
+ def test_malformed_multiline_and_inconsistent_codes_are_rejected(self):
+ with self.assertRaises(ValueError):
+ _recv_response(FakeSocket(b"250-first\r\n550 final\r\n"))
+ with self.assertRaises(ConnectionError):
+ _recv_response(FakeSocket(b"250-first\r\n250-final\r\n"))
+ with self.assertRaises(ValueError):
+ _recv_response(FakeSocket(b"25x malformed\r\n"))
+ with self.assertRaises(ValueError):
+ _recv_response(FakeSocket(b"250 OK"))
+
class TestDispatchAndCli(unittest.TestCase):
def test_protocol_results_do_not_overwrite_same_service(self):
fake = lambda _ip, port: {"port": port}