Skip to content

depthcharge

CommandInfo dataclass

Information about a Depthcharge command.

Attributes:

Name Type Description
name str

Name of the command.

brief str

Brief summary of the command.

help str

Detailed help text for the command.

dangerous bool

Whether the command is considered dangerous.

categories List[str]

Categories assigned to the command.

Source code in wintermute/backends/depthcharge.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
@dataclass
class CommandInfo:
    """Information about a Depthcharge command.

    Attributes:
        name (str): Name of the command.
        brief (str): Brief summary of the command.
        help (str): Detailed help text for the command.
        dangerous (bool): Whether the command is considered dangerous.
        categories (List[str]): Categories assigned to the command.
    """

    name: str
    brief: str = ""
    help: str = ""
    dangerous: bool = False
    categories: List[str] = None  # type: ignore[assignment]

    def to_dict(self) -> Dict[Any, Any]:
        d = asdict(self)
        if d.get("categories") is None:
            d["categories"] = []
        return d

CommandRecord dataclass

A record of a Depthcharge command with metadata.

Attributes:

Name Type Description
name str

Name of the command.

summary str

Brief summary of the command.

usage List[str]

List of usage lines for the command.

details str

Detailed help text for the command.

categories List[str]

Categories assigned to the command.

danger DangerInfo

Danger assessment of the command.

Source code in wintermute/backends/depthcharge.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@dataclass
class CommandRecord:
    """A record of a Depthcharge command with metadata.

    Attributes:
        name (str): Name of the command.
        summary (str): Brief summary of the command.
        usage (List[str]): List of usage lines for the command.
        details (str): Detailed help text for the command.
        categories (List[str]): Categories assigned to the command.
        danger (DangerInfo): Danger assessment of the command.
    """

    name: str
    summary: str
    usage: List[str]
    details: str
    categories: List[str]
    danger: DangerInfo

    def to_dict(self) -> Dict[str, Any]:
        d = asdict(self)
        d["danger"] = self.danger.to_dict()
        return d

DangerInfo dataclass

Information about the danger level of a command.

Attributes:

Name Type Description
severity int

Severity level of the command (0 = safe-ish, higher = riskier).

tags List[str]

List of tags categorizing the danger.

reason str

Short explanation of the danger assessment.

Source code in wintermute/backends/depthcharge.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
@dataclass
class DangerInfo:
    """Information about the danger level of a command.

    Attributes:
        severity (int): Severity level of the command (0 = safe-ish, higher = riskier).
        tags (List[str]): List of tags categorizing the danger.
        reason (str): Short explanation of the danger assessment.
    """

    severity: int = 0  # 0 = safe-ish, higher = riskier
    tags: List[str] = field(default_factory=list)  # e.g., ["mem-write", "flash"]
    reason: str = ""  # short explanation

    def to_dict(self) -> Dict[str, Any]:
        d = asdict(self)
        if d["tags"] is None:
            d["tags"] = []
        return d

DepthchargePeripheralAgent

Runs Depthcharge tasks for a provided Peripheral-like object and attaches your Vulnerability objects with ReproductionSteps.

Example

from wintermute.backends.depthcharge import DepthchargePeripheralAgent from wintermute.core import Operation, Device from wintermute.findings import ReproductionStep, Risk, Vulnerability from wintermute.peripherals import UART op = Operation() dev = Device(hostname="test1", architecture="aarch64") test1 = UART(baudrate=115200, comPort="/dev/ttyUSB0") test1.to_dict() dca = DepthchargePeripheralAgent(test1, arch="aarch64") f = dca.catalog_commands_and_flag() [] Expected U-Boot prompt: U-Boot> [] Using default payload base address: ${loadaddr} + 32MiB [] Retrieving command list via "help" [] Reading environment via "printenv" [] Depthcharge payload base (0x01000000) + payload offset (0x02000000) => 0x03000000 [] Version: U-Boot 2022.01 (Jan 10 2022 - 18:46:34 +0000) [] Enumerating available MemoryWriter implementations... [] Available: CpMemoryWriter [] Available: CRC32MemoryWriter [] Excluded: I2CMemoryWriter - Command "i2c" required but not detected. [] Excluded: LoadbMemoryWriter - Host program "ckermit" required but not found in PATH. [] Available: LoadxMemoryWriter [] Available: LoadyMemoryWriter [] Available: MmMemoryWriter [] Available: MwMemoryWriter [] Available: NmMemoryWriter [] Enumerating available MemoryReader implementations... [!] Excluded: CpCrashMemoryReader - Operation requires crash or reboot, but opt-in not specified. [] Available: CRC32MemoryReader [!] Excluded: GoMemoryReader - Payload deployment+execution opt-in not specified [] Excluded: I2CMemoryReader - Command "i2c" required but not detected. [] Available: ItestMemoryReader [] Available: MdMemoryReader [] Available: MmMemoryReader [] Available: SetexprMemoryReader [] Enumerating available Executor implementations... [!] Excluded: GoExecutor - Payload deployment+execution opt-in not specified [] Enumerating available RegisterReader implementations... [!] Excluded: CpCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: CRC32CrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: FDTCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: ItestCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: MdCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: MmCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: NmCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] Excluded: SetexprCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified. [!] No default RegisterReader available. Running runner.commands(detailed=True) to get help output [] Retrieving detailed command info via "help" Parsed 93 commands from help output

Source code in wintermute/backends/depthcharge.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
class DepthchargePeripheralAgent:
    """
    Runs Depthcharge tasks for a provided Peripheral-like object and
    attaches your Vulnerability objects with ReproductionSteps.

    Example:
        >>> from wintermute.backends.depthcharge import DepthchargePeripheralAgent
        >>> from wintermute.core import Operation, Device
        >>> from wintermute.findings import ReproductionStep, Risk, Vulnerability
        >>> from wintermute.peripherals import UART
        >>> op = Operation()
        >>> dev = Device(hostname="test1", architecture="aarch64")
        >>> test1 = UART(baudrate=115200, comPort="/dev/ttyUSB0")
        >>> test1.to_dict()
        >>> dca = DepthchargePeripheralAgent(test1, arch="aarch64")
        >>> f = dca.catalog_commands_and_flag()
        [*] Expected U-Boot prompt: U-Boot>
        [*] Using default payload base address: ${loadaddr} + 32MiB
        [*] Retrieving command list via "help"
        [*] Reading environment via "printenv"
        [*] Depthcharge payload base (0x01000000) + payload offset (0x02000000) => 0x03000000
        [*] Version: U-Boot 2022.01 (Jan 10 2022 - 18:46:34 +0000)
        [*] Enumerating available MemoryWriter implementations...
        [*]   Available: CpMemoryWriter
        [*]   Available: CRC32MemoryWriter
        [*]   Excluded:  I2CMemoryWriter - Command "i2c" required but not detected.
        [*]   Excluded:  LoadbMemoryWriter - Host program "ckermit" required but not found in PATH.
        [*]   Available: LoadxMemoryWriter
        [*]   Available: LoadyMemoryWriter
        [*]   Available: MmMemoryWriter
        [*]   Available: MwMemoryWriter
        [*]   Available: NmMemoryWriter
        [*] Enumerating available MemoryReader implementations...
        [!]   Excluded:  CpCrashMemoryReader - Operation requires crash or reboot, but opt-in not specified.
        [*]   Available: CRC32MemoryReader
        [!]   Excluded:  GoMemoryReader - Payload deployment+execution opt-in not specified
        [*]   Excluded:  I2CMemoryReader - Command "i2c" required but not detected.
        [*]   Available: ItestMemoryReader
        [*]   Available: MdMemoryReader
        [*]   Available: MmMemoryReader
        [*]   Available: SetexprMemoryReader
        [*] Enumerating available Executor implementations...
        [!]   Excluded:  GoExecutor - Payload deployment+execution opt-in not specified
        [*] Enumerating available RegisterReader implementations...
        [!]   Excluded:  CpCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  CRC32CrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  FDTCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  ItestCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  MdCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  MmCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  NmCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!]   Excluded:  SetexprCrashRegisterReader - Operation requires crash or reboot, but opt-in not specified.
        [!] No default RegisterReader available.
        Running runner.commands(detailed=True) to get help output
        [*] Retrieving detailed command info via "help"
        Parsed 93 commands from help output
    """

    def __init__(
        self,
        peripheral: PeripheralLike,
        default_timeout: float = 2.0,
        arch: Optional[str] = None,
    ) -> None:
        self.peripheral: PeripheralLike = peripheral
        self.device: str = getattr(peripheral, "device_path", "/dev/ttyUSB0:115200")
        self.workspace: Path = Path(getattr(peripheral, "workspace", "./wm_workspace"))
        self.timeout: float = default_timeout
        self.arch: Optional[str] = arch
        self.artifacts: Path = self.workspace / "artifacts"
        self.artifacts.mkdir(parents=True, exist_ok=True)
        logger.info(
            f"Initialized DepthchargePeripheralAgent for device {self.device} with arch {self.arch}"
        )

    def _run(self, runner: Any, cmd: str) -> str:
        fn = getattr(runner, "run_cmd", None) or getattr(runner, "run_command", None)
        if fn is None:
            raise RuntimeError("No run_cmd/run_command on Depthcharge object")
        out = fn(cmd)
        return str(out) if out is not None else ""

    # ---- Catalog commands + attach vuln -------------------------------------
    def catalog_commands_and_flag(self, addVulns: bool = True) -> Dict[str, Any]:
        """Catalog U-Boot commands via Depthcharge and attach vulnerability if dangerous commands found.

        Arguments:
            addVulns (bool): Whether to attach vulnerabilities for dangerous commands.
        """
        logger.debug(f"[Depthcharge] Cataloging commands ({self.device})")

        with _open_dc_context(self.device, self.timeout, self.arch) as dc:
            runner: Any = getattr(dc, "console", dc)
            try:
                if hasattr(runner, "interrupt"):
                    runner.interrupt()
            except Exception:
                pass

            try:
                # help_out = self._run(runner, "help")
                print("Running runner.commands(detailed=True) to get help output")
                help_out = dc.commands(detailed=True)
            except Exception:
                help_out = {}  # ""

        parsed = _parse_commands(help_out)
        print(f"Parsed {len(parsed)} commands from help output")
        logger.info(f"[Depthcharge] Parsed {len(parsed)} commands from help output")

        top = sorted(parsed, key=lambda r: r.danger.severity, reverse=True)[:15]
        for r in top:
            sev = r.danger.severity
            logger.info(
                f"  - {r.name:10s}  sev={sev:2d}  tags={','.join(r.danger.tags)}  :: {r.summary}"
            )

        out_path = self.artifacts / "command_catalog.json"
        out_path.write_text(
            json.dumps(
                {
                    "device": self.device,
                    "commands": [r.to_dict() for r in parsed],
                },
                indent=2,
            ),
            encoding="utf-8",
        )
        logger.debug(f"[Depthcharge] Saved command catalog to {str(out_path)}")

        if addVulns and any(r.danger.severity >= 1 for r in parsed):
            repro = _make_repro_step(
                title="Enumerate U-Boot commands via console",
                description="Run depthcharge-inspect and verify the configuration created for commands.",
                tool="depthcharge-inspect",
                action="retrieve command catalog",
                confidence=8,
                arguments=[
                    f"--device={self.device}",
                    f" --arch={self.arch}",
                    f"-c f{self.peripheral.name}.conf",
                ],
                vulnOutput=None,
            )
            v = _make_user_vuln(
                title="Dangerous U-Boot commands are exposed",
                description=(
                    "The following commands were reported by 'help' and categorized as dangerous: "
                    + ", ".join(
                        sorted(set([r.name for r in parsed if r.danger.severity >= 1]))
                    )
                ),
                threat=(
                    "Presence of memory, storage-write, network fetch, and execution commands may allow "
                    "firmware tampering, data exfiltration, or arbitrary code execution via the console."
                ),
                severity="High",
                mitigation_desc=(
                    "Remove unneeded commands at build time (CONFIG_*), restrict/disable UART in production, "
                    "and enforce verified/FIT boot so untrusted payloads cannot execute."
                ),
                reproduction_steps=[repro],
                verified=True,
            )
            if v not in self.peripheral.vulnerabilities:
                self.peripheral.vulnerabilities.append(v)
            logger.debug("[Depthcharge] Attached vulnerability: Dangerous commands")
        else:
            logger.debug("[Depthcharge] No dangerous commands identified.")

        info: Dict[str, Any] = {
            "device": self.device,
            "artifact": str(out_path),
            "total_commands": len(parsed),
            "dangerous_commands": sum(1 for r in parsed if r.danger.severity >= 1),
        }
        logger.info("[Depthcharge] Command cataloging complete: %s", info)

        return info

    # ---- Dump memory via API + attach vuln ----------------------------------
    def dump_memory_and_attach_vuln(
        self,
        address: int,
        length: int,
        filename: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Dump memory via Depthcharge API and attach vulnerability if successful.

        Arguments:
            address (int): Start address to dump.
            length (int): Number of bytes to dump.
            filename (Optional[str]): Optional filename for the dump artifact.
        """
        if filename is None:
            filename = f"memory_dump_{address:08X}_{length}.bin"
        out_path: Path = self.artifacts / filename
        out_path.parent.mkdir(parents=True, exist_ok=True)

        logger.debug("Opening Depthcharge context to dump memory...")
        with _open_dc_context(self.device, self.timeout, self.arch) as dc:
            # Warm up command table (optional, but surfaces issues early)
            try:
                _ = dc.commands(detailed=False)
            except Exception as e:
                logger.debug("commands(detailed=False) failed (continuing): %s", e)

            wrote_file = False

            # 1) Prefer the high-level file writer (returns None on success)
            if hasattr(dc, "read_memory_to_file"):
                try:
                    dc.read_memory_to_file(address, length, str(out_path))
                    wrote_file = out_path.exists() and out_path.stat().st_size > 0
                    if not wrote_file:
                        logger.warning(
                            "read_memory_to_file completed but no file/empty file at %s",
                            out_path,
                        )
                except Exception as e:
                    logger.debug("read_memory_to_file failed: %s", e)

            # 2) Fallback: read bytes, then write ourselves
            if not wrote_file:
                try:
                    if hasattr(dc, "read_memory"):
                        data: bytes = dc.read_memory(address, length)
                        out_path.write_bytes(data)
                        wrote_file = True
                    else:
                        logger.debug(
                            "Context has no read_memory method; skipping byte-read fallback."
                        )
                except Exception as e:
                    logger.debug("read_memory fallback failed: %s", e)

            if not wrote_file:
                raise RuntimeError("No working Depthcharge memory-read helper found.")

        # Build artifact info using the actual file on disk
        actual_size = out_path.stat().st_size
        info: Dict[str, Any] = {
            "device": self.device,
            "address": hex(address),
            "length_requested": length,
            "artifact": str(out_path),
            "size": actual_size,
        }

        # Optional but useful
        try:
            info["sha256"] = _sha256_file(out_path)
        except Exception as e:
            logger.debug("sha256 calc failed: %s", e)

        (self.artifacts / "dump_info.json").write_text(
            json.dumps(info, indent=2), encoding="utf-8"
        )
        logger.info("Memory dump complete: %s (%d bytes)", out_path, actual_size)

        # Vulnerability (your classes) + reproduction step
        repro = _make_repro_step(
            title="Dump memory via Depthcharge API",
            description="Read memory from target address range using Depthcharge context.",
            tool="depthcharge",
            action="read-memory",
            confidence=9,
            arguments=[
                f"--device={self.device}",
                f"--address={hex(address)}",
                f"--length={length}",
            ],
            vulnOutput=f"Dumped {length} bytes from {hex(address)} to {str(out_path)}",
        )
        v = _make_user_vuln(
            title="Raw memory dumping is possible via U-Boot console",
            description=f"Successfully dumped {length} bytes from {hex(address)} into {str(out_path)}.",
            threat=(
                "Reading arbitrary memory from the bootloader can expose sensitive material "
                "(keys, credentials, firmware, configuration) for offline analysis or tampering."
            ),
            severity="Medium",
            mitigation_desc=(
                "Restrict console access; gate memory primitives behind authentication; ensure secrets "
                "are not resident in readable regions; adopt verified boot to resist tampering."
            ),
            reproduction_steps=[repro],
        )
        if v not in self.peripheral.vulnerabilities:
            self.peripheral.vulnerabilities.append(v)
        logger.debug("[Depthcharge] Attached vulnerability: Memory dump permitted")

        return info

catalog_commands_and_flag(addVulns=True)

Catalog U-Boot commands via Depthcharge and attach vulnerability if dangerous commands found.

Parameters:

Name Type Description Default
addVulns bool

Whether to attach vulnerabilities for dangerous commands.

True
Source code in wintermute/backends/depthcharge.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
def catalog_commands_and_flag(self, addVulns: bool = True) -> Dict[str, Any]:
    """Catalog U-Boot commands via Depthcharge and attach vulnerability if dangerous commands found.

    Arguments:
        addVulns (bool): Whether to attach vulnerabilities for dangerous commands.
    """
    logger.debug(f"[Depthcharge] Cataloging commands ({self.device})")

    with _open_dc_context(self.device, self.timeout, self.arch) as dc:
        runner: Any = getattr(dc, "console", dc)
        try:
            if hasattr(runner, "interrupt"):
                runner.interrupt()
        except Exception:
            pass

        try:
            # help_out = self._run(runner, "help")
            print("Running runner.commands(detailed=True) to get help output")
            help_out = dc.commands(detailed=True)
        except Exception:
            help_out = {}  # ""

    parsed = _parse_commands(help_out)
    print(f"Parsed {len(parsed)} commands from help output")
    logger.info(f"[Depthcharge] Parsed {len(parsed)} commands from help output")

    top = sorted(parsed, key=lambda r: r.danger.severity, reverse=True)[:15]
    for r in top:
        sev = r.danger.severity
        logger.info(
            f"  - {r.name:10s}  sev={sev:2d}  tags={','.join(r.danger.tags)}  :: {r.summary}"
        )

    out_path = self.artifacts / "command_catalog.json"
    out_path.write_text(
        json.dumps(
            {
                "device": self.device,
                "commands": [r.to_dict() for r in parsed],
            },
            indent=2,
        ),
        encoding="utf-8",
    )
    logger.debug(f"[Depthcharge] Saved command catalog to {str(out_path)}")

    if addVulns and any(r.danger.severity >= 1 for r in parsed):
        repro = _make_repro_step(
            title="Enumerate U-Boot commands via console",
            description="Run depthcharge-inspect and verify the configuration created for commands.",
            tool="depthcharge-inspect",
            action="retrieve command catalog",
            confidence=8,
            arguments=[
                f"--device={self.device}",
                f" --arch={self.arch}",
                f"-c f{self.peripheral.name}.conf",
            ],
            vulnOutput=None,
        )
        v = _make_user_vuln(
            title="Dangerous U-Boot commands are exposed",
            description=(
                "The following commands were reported by 'help' and categorized as dangerous: "
                + ", ".join(
                    sorted(set([r.name for r in parsed if r.danger.severity >= 1]))
                )
            ),
            threat=(
                "Presence of memory, storage-write, network fetch, and execution commands may allow "
                "firmware tampering, data exfiltration, or arbitrary code execution via the console."
            ),
            severity="High",
            mitigation_desc=(
                "Remove unneeded commands at build time (CONFIG_*), restrict/disable UART in production, "
                "and enforce verified/FIT boot so untrusted payloads cannot execute."
            ),
            reproduction_steps=[repro],
            verified=True,
        )
        if v not in self.peripheral.vulnerabilities:
            self.peripheral.vulnerabilities.append(v)
        logger.debug("[Depthcharge] Attached vulnerability: Dangerous commands")
    else:
        logger.debug("[Depthcharge] No dangerous commands identified.")

    info: Dict[str, Any] = {
        "device": self.device,
        "artifact": str(out_path),
        "total_commands": len(parsed),
        "dangerous_commands": sum(1 for r in parsed if r.danger.severity >= 1),
    }
    logger.info("[Depthcharge] Command cataloging complete: %s", info)

    return info

dump_memory_and_attach_vuln(address, length, filename=None)

Dump memory via Depthcharge API and attach vulnerability if successful.

Parameters:

Name Type Description Default
address int

Start address to dump.

required
length int

Number of bytes to dump.

required
filename Optional[str]

Optional filename for the dump artifact.

None
Source code in wintermute/backends/depthcharge.py
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
def dump_memory_and_attach_vuln(
    self,
    address: int,
    length: int,
    filename: Optional[str] = None,
) -> Dict[str, Any]:
    """Dump memory via Depthcharge API and attach vulnerability if successful.

    Arguments:
        address (int): Start address to dump.
        length (int): Number of bytes to dump.
        filename (Optional[str]): Optional filename for the dump artifact.
    """
    if filename is None:
        filename = f"memory_dump_{address:08X}_{length}.bin"
    out_path: Path = self.artifacts / filename
    out_path.parent.mkdir(parents=True, exist_ok=True)

    logger.debug("Opening Depthcharge context to dump memory...")
    with _open_dc_context(self.device, self.timeout, self.arch) as dc:
        # Warm up command table (optional, but surfaces issues early)
        try:
            _ = dc.commands(detailed=False)
        except Exception as e:
            logger.debug("commands(detailed=False) failed (continuing): %s", e)

        wrote_file = False

        # 1) Prefer the high-level file writer (returns None on success)
        if hasattr(dc, "read_memory_to_file"):
            try:
                dc.read_memory_to_file(address, length, str(out_path))
                wrote_file = out_path.exists() and out_path.stat().st_size > 0
                if not wrote_file:
                    logger.warning(
                        "read_memory_to_file completed but no file/empty file at %s",
                        out_path,
                    )
            except Exception as e:
                logger.debug("read_memory_to_file failed: %s", e)

        # 2) Fallback: read bytes, then write ourselves
        if not wrote_file:
            try:
                if hasattr(dc, "read_memory"):
                    data: bytes = dc.read_memory(address, length)
                    out_path.write_bytes(data)
                    wrote_file = True
                else:
                    logger.debug(
                        "Context has no read_memory method; skipping byte-read fallback."
                    )
            except Exception as e:
                logger.debug("read_memory fallback failed: %s", e)

        if not wrote_file:
            raise RuntimeError("No working Depthcharge memory-read helper found.")

    # Build artifact info using the actual file on disk
    actual_size = out_path.stat().st_size
    info: Dict[str, Any] = {
        "device": self.device,
        "address": hex(address),
        "length_requested": length,
        "artifact": str(out_path),
        "size": actual_size,
    }

    # Optional but useful
    try:
        info["sha256"] = _sha256_file(out_path)
    except Exception as e:
        logger.debug("sha256 calc failed: %s", e)

    (self.artifacts / "dump_info.json").write_text(
        json.dumps(info, indent=2), encoding="utf-8"
    )
    logger.info("Memory dump complete: %s (%d bytes)", out_path, actual_size)

    # Vulnerability (your classes) + reproduction step
    repro = _make_repro_step(
        title="Dump memory via Depthcharge API",
        description="Read memory from target address range using Depthcharge context.",
        tool="depthcharge",
        action="read-memory",
        confidence=9,
        arguments=[
            f"--device={self.device}",
            f"--address={hex(address)}",
            f"--length={length}",
        ],
        vulnOutput=f"Dumped {length} bytes from {hex(address)} to {str(out_path)}",
    )
    v = _make_user_vuln(
        title="Raw memory dumping is possible via U-Boot console",
        description=f"Successfully dumped {length} bytes from {hex(address)} into {str(out_path)}.",
        threat=(
            "Reading arbitrary memory from the bootloader can expose sensitive material "
            "(keys, credentials, firmware, configuration) for offline analysis or tampering."
        ),
        severity="Medium",
        mitigation_desc=(
            "Restrict console access; gate memory primitives behind authentication; ensure secrets "
            "are not resident in readable regions; adopt verified boot to resist tampering."
        ),
        reproduction_steps=[repro],
    )
    if v not in self.peripheral.vulnerabilities:
        self.peripheral.vulnerabilities.append(v)
    logger.debug("[Depthcharge] Attached vulnerability: Memory dump permitted")

    return info

PeripheralLike

Bases: Protocol

A minimal Protocol for Wintermute Peripheral-like objects.

Attributes:

Name Type Description
device_path str

Device connection string (e.g., COM port or /dev path).

workspace str

Path to the workspace directory.

name str

Name of the peripheral/device.

vulnerabilities List[Any]

List to store found vulnerabilities.

Source code in wintermute/backends/depthcharge.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@runtime_checkable
class PeripheralLike(Protocol):
    """A minimal Protocol for Wintermute Peripheral-like objects.

    Attributes:
        device_path (str): Device connection string (e.g., COM port or /dev path).
        workspace (str): Path to the workspace directory.
        name (str): Name of the peripheral/device.
        vulnerabilities (List[Any]): List to store found vulnerabilities.
    """

    device_path: str
    workspace: str
    name: str
    vulnerabilities: List[Any]

    def add_vulnerability(self, v: Any) -> None: ...
    def log_info(self, msg: str) -> None: ...