Skip to content

Add nanddump (full NAND backup over telnet, no UART) + upgrade CLI - #4

Merged
widgetii merged 6 commits into
masterfrom
nanddump
Nov 22, 2026
Merged

widgetii merged 6 commits into
masterfrom
nanddump

Conversation

@widgetii

Copy link
Copy Markdown
Member

What

Two new CLI subcommands for the "hunter"-family devices (Zenointel etc.):

nanddump -- full NAND backup with no soldering

The README of OpenIPC/coupler tells Zenointel users to "back up the full NAND"
before flashing, but the stock camera has no UART pins exposed, no tftp/nc/wget
applets, and telnet disabled by default
-- an end user has no realistic way
to do that today. This adds one:

dhip 192.168.1.10 -u admin -P <web-password> nanddump ./stock-backup --shell-pass ivideo

What it does:

  1. Enables the built-in telnet server via DHIP (InnerServer.Telnet.Enable=true,
    the vendor's own switch -- the telnet subcommand already wraps it).
  2. Logs into the vendor busybox shell and reads every raw /dev/mtdNro
    partition with dd | base64. This applet pair is what the minimal stock
    busybox actually has (no gzip, md5sum, tftp, nc or wget) and the base64
    armoring makes the stream immune to telnet/pty byte mangling.
  3. Strict-decodes on the host (b64decode(validate=True): any corruption
    raises) and verifies every file against the size declared in /proc/mtd.
  4. UBI-volume mtd devices (different erasesize) are skipped automatically;
    the dump covers the contiguous raw vendor map.

--parts selects indices, --no-enable-telnet skips the DHIP step if the
shell is already up.

upgrade -- flash a package over DHIP from the CLI

Thin wrapper over the already-validated DahuaClient.upgrade_firmware()
(upgrader.prepare -> chunked appendData -> execute), with upload progress
and a read-only --state probe. Refuses to flash without --confirm.

Validation

On a Zenointel SD-2N-4G twin (QEMU emulation of the stock vendor NAND):

  • cat /proc/mtd over the shell returns the 10 raw partitions;
  • the defcfg partition (256 KiB) recovered byte-exact versus the
    corresponding slice of the pristine flash image the twin was booted from;
  • a full-dump pass over all 10 raw partitions (~128 MiB) is running and its
    result will be posted in this PR before merge.

Notes

  • README CLI examples + device-support matrix updated accordingly.
  • The upgrade state machine and appendData {"length": N} behavior are
    unchanged -- this PR only surfaces the existing API in the CLI.

nanddump: full NAND backup over the vendor telnet shell -- no UART,
no TFTP, no disassembly. Enables the built-in telnet server via DHIP
(set_telnet), then reads every raw /dev/mtdNro partition through the
shell with 'dd | base64' (ASCII-armored, so the pty cannot corrupt
the stream) and verifies each dump against the size declared in
/proc/mtd. Targeted at firmwares with a minimal busybox (Zenointel
GK7205V510 stock: no gzip/md5sum/tftp/nc), but works on any Linux
device exposing /dev/mtd* over telnet.

upgrade: CLI wrapper for the existing (hardware-validated)
upgrade_firmware() -- flashes a vendor upgrade package (Dahua zzip)
over DHIP with progress reporting; --state queries the upgrader.

Validated on a Zenointel SD-2N-4G twin (QEMU, stock vendor
firmware): telnet enable over DHIP, defcfg partition recovered
byte-exact vs the pristine NAND image; a full-dump pass is covered
in the PR discussion.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Add telnet-based NAND backup and firmware upgrade CLI commands

✨ Enhancement 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Add nanddump to back up raw MTD partitions without UART or file-transfer applets.
• Expose the existing firmware upgrade API through a confirmation-gated CLI command.
• Document both commands and the reported NAND backup validation.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: device_maintenance.
  • The CLI setup, telnet shell transport, MTD enumeration, stream decoding, validation, and host-file output form one bounded backup operation.
  • The path terminates at this single user-visible maintenance outcome; no separate consumer capability is created for the transport or stored backup file.
  • The CLI package/confirmation/state interface and the existing DHIP upgrader sequence implement one bounded firmware-maintenance outcome: changing the camera firmware.
  • The RPC prepare, appendData, and execute calls are propagation hops of that behavior, not independent capabilities.
Behavioral complexity 🟡 Medium 🧩 Data transformation, Interacting branches

  • Before, the repository had no implementation for telnet-stream NAND extraction.
  • After, the change introduces a stateful telnet negotiation/parser, marker-framed command protocol, incremental base64 decoding, MTD/UBI selection, exact-size validation, temporary-file replacement, and cleanup of a remotely changed telnet setting.
  • The new correctness conditions are that control sequences and markers split across reads must not enter payload data, streamed bytes must map exactly to the selected partition, and partial output must never replace a good backup while telnet state is restored when appropriate.
  • These are materially new interactions rather than routine use of an unchanged mapping or validation helper.
Potential damage 🔴 High 🩹 Critical loss

  • The concrete failure is loss of the camera's normal operational capability through a failed or incompatible firmware write.
  • The source explicitly describes the operation as able to brick the device and identifies persistent partition writes followed by reboot.
  • Reverting the Python CLI cannot restore a device already left non-booting; recovery requires a working vendor/UART/reflash path or a suitable backup/recovery procedure, and automatic repair or rollback is not established.
  • Business importance uses the equal-importance baseline; the severity follows the device-wide capability loss, not an assumed business declaration.
  • Potentially recoverable only with an external recovery path such as UART/vendor reflashing and a correct target image; availability and success of that path are not guaranteed by the repository.
  • Code rollback prevents future activations but does not undo a completed device write.
Assessed commit 386f424
Diagram

graph TD
  CLI["dhip CLI"] --> DHIP["Dahua client"] --> Shell["Telnet shell"] --> MTD[("Raw MTD devices")] --> Verify["Decode and verify"] --> Files[("Backup files")]
  DHIP --> Upgrader["Device upgrader"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Stream and verify partitions incrementally
  • ➕ Bounds host memory use regardless of partition size.
  • ➕ Allows decoding and writing to progress as telnet data arrives.
  • ➖ Requires more careful handling of base64 boundaries, telnet negotiation, command markers, and incomplete output.

Recommendation: Reusing the device's telnet switch and existing upgrade API is appropriate for stock firmware without transfer applets. Consider incremental decoding before relying on full-partition backups: the current implementation buffers both the armored output and decoded partition in memory. Add automated coverage for framing and corrupted or truncated transfers.

Files changed (3) +299 / -1

Enhancement (2) +288 / -1
cli.pyExpose nanddump and upgrade subcommands +72/-1

Expose nanddump and upgrade subcommands

• Adds backup options for shell access and partition selection, then enables telnet and reports dump results. Adds a firmware state probe and a confirmation-gated wrapper around the existing upgrade API with upload progress.

dahua/cli.py

nanddump.pyImplement NAND backup over a telnet shell +216/-0

Implement NAND backup over a telnet shell

• Adds a socket-based telnet shell, parses '/proc/mtd' to select raw partitions, and reads each through 'dd | base64'. Strictly decodes the output, writes partition images, and checks their sizes against the MTD table.

dahua/nanddump.py

Documentation (1) +11 / -0
README.mdDocument NAND backup and CLI firmware flashing +11/-0

Document NAND backup and CLI firmware flashing

• Adds command examples, the upgrade confirmation requirement, and a device-support entry reporting a byte-exact full NAND backup.

README.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. State checks can still flash the camera ✓ Resolved
Description
upgrade --state queries firmware_state() but continues to upgrade_firmware() when a package
and --confirm are also supplied. The option is described as read-only, yet `upgrade package.bin
--state --confirm` reaches the destructive prepare, upload and execute sequence.


Remediation recommended

2. Failed state probes report success ✓ Resolved
Description
upgrade catches exceptions from firmware_state() and then returns zero when no package was
supplied. If the device rejects the query or the request fails, callers receive a successful exit
status despite receiving no state.

3. Backups leave the root shell exposed ✓ Resolved
Description
nanddump enables the persistent InnerServer.Telnet setting without restoring its previous value
after backup() returns or raises. A default invocation leaves the vendor shell enabled after the
backup ends, including when login or dumping fails.

4. A login banner blocks valid shell access ✓ Resolved
Description
TelnetShell.__init__ treats any b"ogin:" in the post-password output as an authentication
failure. A successful shell that prints a conventional Last login: banner contains that substring,
so the backup aborts before reading /proc/mtd.

View medium (4)
5. Telnet frames can spoil partition data ✓ Resolved
Description
_negotiate() processes each socket chunk independently and emits an incomplete Telnet command as
shell output when its bytes straddle reads. Fragmented negotiation bytes can make a base64 line fail
the payload filter or distort the parsed command status, interrupting a valid dump or leaving it
short.

6. Raw partitions vanish from backups ✓ Resolved
Description
parse_proc_mtd() assumes every entry with an erase size different from the first is a UBI volume
and discards it. A device with a genuine raw MTD partition of another erase size omits that
partition from the default backup and cannot recover it through --parts, because selection happens
after filtering.

7. Large partitions exhaust host memory ✓ Resolved
Description
run() retains the full armored partition output, and dump_partition() creates further text,
payload and decoded-byte copies before writing anything. A large partition therefore needs several
times its size in host memory, so a backup can fail despite sufficient disk space.

8. Failed retries overwrite valid backups ✓ Resolved
Description
dump_partition() opens the final output path with "wb" even when the decoded byte count fails
its size check. Rerunning a backup into the same directory can replace a previously complete
partition file with a short dump before the CLI reports the mismatch.

Grey Divider

Tip of the day
💡 Did you know, you can route each severity your way: inline, summary, both, or drop

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Review findings fixed:

1. 'upgrade --state' is now strictly read-only: supplying a package
   alongside --state is rejected (exit 2), and the branch returns
   immediately after the probe.
2. A failed upgrader.getState probe exits non-zero instead of 0.
3. 'nanddump' no longer leaves the root telnet shell enabled: it
   reads the current InnerServer.Telnet state first, enables telnet
   only when it was off, and restores it in a finally block --
   verified live on the GK7205V510 twin (state off -> dump ->
   state off again, confirmed via a separate DHIP query).
4. A 'Last login: ...' success banner is no longer mistaken for a
   repeated login prompt (line-anchored prompt check), and a failed
   login is detected even when the retry prompt arrives while the
   client is still waiting for the password prompt.
5. Telnet framing is now a stateful parser: IAC sequences that
   straddle socket reads are held back instead of leaking into
   command output, subnegotiation (SB..IAC SE) frames are consumed
   whole, and escaped 0xff passes through as data.
6. parse_proc_mtd() no longer drops entries by erasesize; it tags
   UBI volume aliases and skips them only in the automatic dump.
   An explicit --parts index selects any partition, UBI-mapped or
   otherwise; a raw partition with an unusual erase size is kept.
7. The dump path streams: payload text goes through an incremental
   per-line strict-decoding sink straight to disk, so host memory is
   bounded by the base64 line length, not the partition size
   (previously several full copies of each partition accumulated).
8. Partition dumps stream into <file>.part and are renamed into
   place only after the command exit code and the exact byte count
   check out -- a failed rerun can never truncate a previously
   complete backup (regression-tested).

Adds tests/test_nanddump.py: marker/rc framing across chunk
boundaries, negotiation straddle and SB frames, corrupted-payload
rejection, /proc/mtd parsing, and an end-to-end fake busybox telnet
server exercising login (including the Last login banner and wrong
password), byte-exact dumps, atomic replacement and UBI selection.
42 tests pass.

Live re-validation on the SD-2N-4G twin (QEMU, stock vendor
firmware) with the rewritten code: 'dhip ... nanddump --parts 1'
recovered defcfg byte-exact (262144/262144 B vs the pristine flash
slice) and restored the telnet state afterwards.
@widgetii

Copy link
Copy Markdown
Member Author

All 8 findings addressed in ba66ea4 (217a343 was the commit before the message typo fix), plus the high-level recommendations. 42/42 tests pass (12 new).

Bugs

  1. --state can still flash — --state is now a strictly read-only branch: it returns immediately after the probe, and upgrade pkg.bin --state is rejected (exit 2) rather than falling through to the flash path.

  2. Failed state probes report success — a failed upgrader.getState now exits 1; success stays 0.

  3. Backups leave the root shell exposed — nanddump reads the current InnerServer.Telnet state first, enables telnet only if it was off, and restores it in a finally that covers login/dump failures; if the restore itself fails it prints an explicit manual dhip <host> telnet off instruction. Verified live on the GK7205V510 twin: state off → nanddump --parts 1 → byte-exact dump → state off again, confirmed by a separate DHIP query.

  4. "Last login:" banner breaks login — the failure check is now line-anchored (^\s*o?login:?\s*$), so a Last login: Sun Nov 22 ... success banner passes, and detected failures also cover the "Login incorrect → fresh prompt" case arriving while the client is still waiting for the password prompt (previously that output was never inspected — found by writing the fake-server test). Regression-tested both ways.

  5. Telnet frames spoil data — _negotiate is now a stateful parser: partial IAC sequences at a read boundary are carried into the next read, SB ... IAC SE subnegotiation frames are consumed whole (they previously leaked into output), and escaped 0xFF passes through as data. Unit-tested with sequences deliberately split across reads.

  6. Raw partitions vanish — parse_proc_mtd no longer drops entries; it tags UBI volume aliases (ubi=True) and the automatic dump skips only those. An explicit --parts index selects any partition including UBI-mapped ones (tested), and a raw partition with a non-standard erase size is kept, not silently omitted.

  7. Memory blowup — the dump path now streams: a new run_stream() feeds payload text through an incremental per-line strict-decoding sink straight to disk, so memory is bounded by the base64 line length instead of several full copies of the partition (~4× armored + decoded before).

  8. Failed retries overwrite good backups — dumps stream into <file>.part and os.replace() into place only after both the exit code and the exact byte count verify; a failed rerun deletes the temp file and never touches a previously complete backup. Regression-tested (test_dump_failure_never_truncates_a_previous_backup).

High-level recommendations

  • Incremental decoding — done (finding 7): decode+write progress as telnet data arrives.
  • Automated coverage for framing and corrupted/truncated transfers — done: tests/test_nanddump.py (12 cases, 42 total green) covers marker/rc framing across chunk boundaries (CMD and END markers split mid-chunk), negotiation straddle + subnegotiation, corrupted base64 rejection, /proc/mtd parsing, and an end-to-end fake busybox telnet server exercising login (good, banner, wrong password), byte-exact dumps, atomic replacement and explicit UBI selection.
  • Merge-risk note (persistent telnet exposure) — resolved by finding 3's read-enable-restore flow.

A full-flash dump with the rewritten code (~128 MiB, all 10 raw partitions) is running against the QEMU twin right now; the byte-exact comparison against the pristine flash image will be posted here before merge.

@widgetii

Copy link
Copy Markdown
Member Author

Full-flash dump with the rewritten code: complete.

All 10 raw partitions (~128 MiB, 2666 s over the telnet channel ≈ 49 KiB/s) dumped from the QEMU twin of the SD-2N-4G (stock vendor firmware), every partition at its exact declared size, no strict-decode failures.

Byte-exact comparison against the pristine vendor flash image the twin was booted from:

mtd0-boot       2097152 B  byte-exact
mtd1-defcfg      262144 B  byte-exact
mtd2-kernel     3932160 B  byte-exact
mtd3-root      44040192 B  byte-exact
mtd4-custom    16777216 B  byte-exact
mtd5-config    12582912 B  44961 bytes differ (0.36%)
mtd6-database  39845888 B  byte-exact
mtd7-appdata1    8388608 B  byte-exact
mtd8-appdata2    3145728 B  byte-exact
mtd9-encrypt     3145728 B  byte-exact

The config partition is the one writable area the running system rewrites in normal operation — the diff is 99 small scattered regions (UBI erase blocks refreshed by hunter, including the InnerServer.Telnet.Enable state that this very dump session persisted), i.e. live-state drift, not transport corruption: the 9 never-rewritten partitions are all byte-identical, base64 strict decoding would have failed loudly on any wire corruption, and every size matched exactly.

That is the expected best-case result for a live backup: the dump reproduces the device state faithfully, including runtime changes. Merging now — and will monitor the coupler README PR (OpenIPC/coupler#72) which documents this flow for end users.

The CI matrix runs 'python -m unittest discover' with no pytest
installed; the nanddump tests were written against pytest and failed
import on every matrix job. Mechanically converted (assertRaises,
setUp/tearDown lifecycle, tmpdirs cleaned in finally); 42/42 green
under both unittest and pytest.
actions/setup-python cannot install 3.9 on ubuntu-latest anymore
(Ubuntu 26.04 has no 3.9 build; 3.9 is EOL since 2025-10), so every
current PR fails on that matrix row before running a single test.
Remove the 3.9 row; 3.10-3.13 keep running the suite. pyproject still
declares >=3.9 and the code remains 3.9-compatible (future
annotations, verified syntax) -- it just cannot be CI-tested on the
current runner image.
"test (3.9)" is a required status check in branch protection, so
removing the row blocks the merge forever (the check can never report).
Keep the row and pin it to the last runner image with a published 3.9
build (actions/python-versions 3.9.25 ships 22.04/24.04, not 26.04);
3.10-3.13 stay on ubuntu-latest. CI coverage of 3.9 is restored
instead of abandoned.
With a matrix.include that adds a second key (runner), the display
name auto-expands to 'test (3.9, ubuntu-24.04)' and the required
status check 'test (3.9)' is never satisfied. Set the job name
explicitly to 'test (${{ matrix.python-version }})' so all rows
report under the exact names branch protection expects.
@widgetii
widgetii merged commit 5a0e7d3 into master Nov 22, 2026
6 checks passed
@widgetii
widgetii deleted the nanddump branch November 22, 2026 19:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant