Never enough about cameras: Firmware keys hidden under the rug

Alexandru Lazar (Security Researcher · B Defender)

DEF CON 33 · Day 1 · Main Stage

Overview

In this DEF CON talk, Alexandru Lazar, a Security Researcher at B Defender, delves into the often-overlooked security posture of IP cameras, specifically focusing on devices from Dahua Technology. The presentation highlights a critical investigation into how to extract and decrypt firmware from these widely deployed devices, ultimately uncovering two distinct vulnerabilities that could lead to remote code execution. Lazar underscores the pressing relevance of this research, noting that despite advancements, countless webcams remain exposed to the internet, making them prime targets for botnets, espionage, and ransomware attacks. The talk serves as a stark reminder that even seemingly innocuous IoT devices can harbor significant security flaws, with far-reaching implications for both individual privacy and national security.

Watch on YouTube

Visual summary for Never enough about cameras: Firmware keys hidden under the rug by Alexandru Lazar
Visual summary for Never enough about cameras: Firmware keys hidden under the rug by Alexandru Lazar

Key moments

  1. 0:00 Introduction: Why security cameras are critical targets
  2. 1:10 Methods for acquiring camera firmware: easy and hardware
  3. 2:20 Challenges: Encrypted firmware and custom compression
  4. 3:50 Reversing the bootloader: Loading U-boot into Ghidra
  5. 4:50 Decryption process discovered: four key steps
  6. 5:40 Deriving the 16-byte firmware key using SHA-256
  7. 7:50 Identifying AES algorithm and key expansion

Never enough about cameras: Firmware keys hidden under the rug

Speakers: Alexandru Lazar, Security Researcher, B Defender

Conference: DEF CON

YouTube: https://www.youtube.com/watch?v=N4Cnso2Vbmw

Overview

In this DEF CON talk, Alexandru Lazar, a Security Researcher at B Defender, delves into the often-overlooked security posture of IP cameras, specifically focusing on devices from Dahua Technology. The presentation highlights a critical investigation into how to extract and decrypt firmware from these widely deployed devices, ultimately uncovering two distinct vulnerabilities that could lead to remote code execution. Lazar underscores the pressing relevance of this research, noting that despite advancements, countless webcams remain exposed to the internet, making them prime targets for botnets, espionage, and ransomware attacks. The talk serves as a stark reminder that even seemingly innocuous IoT devices can harbor significant security flaws, with far-reaching implications for both individual privacy and national security.

The motivation behind this deep dive stems from real-world incidents, including recent military reports of security cameras being compromised to track logistics, and cases where ransomware gangs leveraged camera access to pivot into target networks. These scenarios emphasize the urgent need for a thorough understanding of the security mechanisms—or lack thereof—within these devices. Lazar’s work provides a comprehensive technical breakdown, from the initial challenges of firmware acquisition and reverse engineering a custom encryption scheme to the intricate process of identifying and exploiting critical buffer overflows. The findings not only expose specific weaknesses in Dahua devices but also offer broader insights into the common pitfalls in embedded device security.

Background

▶ Watch: Introduction: Why security cameras are critical targets (0:00)

The proliferation of Internet of Things (IoT) devices, particularly security cameras, has inadvertently created a vast attack surface. As Lazar points out, it's 2025, and a significant number of webcams are still directly exposed to the internet, often running outdated firmware with known, easily exploitable vulnerabilities. This makes them ideal candidates for inclusion in botnets, as evidenced by large-scale DDoS attacks leveraging compromised IoT devices. Beyond botnets, more sophisticated threats loom, such as state-sponsored espionage tracking logistical movements or ransomware groups exploiting cameras as initial access points into corporate networks. Understanding and mitigating these risks begins with examining the software that runs on these devices: their firmware.

Obtaining firmware is the foundational step for security analysis. Lazar outlines several methods, categorized into "easy" and "hardware" approaches. The easy methods include downloading firmware directly from a vendor's website, extracting it via a UART shell if available, or intercepting an over-the-air update. For devices where these methods fail, the "hardware way" involves direct memory reading, often requiring physical access to the device. In the case of Dahua devices examined—three cameras and an XVR—Lazar's team found a mix: some firmware was readily available online, while for one camera, they had to desolder the flash chip and use a Bus Pirate to read its contents. This process involved consulting the chip's datasheet for pinouts and developing a custom Python script, as generic tools like Flash ROM proved ineffective for the specific chip brand.

Once the firmware binaries were acquired, the next challenge was extracting the file system. Standard tools like Binwalk worked for some devices, but others presented a significant hurdle. These files, despite suggestive names like web.squatchfs, only revealed U-image headers when analyzed by Binwalk. Their high entropy suggested compression or encryption. While zib signatures were initially detected—often false alarms—extracting these "false alarms" revealed readable strings, filenames, and even JavaScript code, indicating a custom, possibly light, obfuscation rather than strong encryption. Further investigation revealed a custom compression scheme where the standard PK (Zip file signature) was replaced with DH (presumably for Dahua), and the presence of U-image headers on file system files, which is highly unusual. This pointed towards a non-standard approach to firmware packaging and protection, necessitating a deeper dive into the device's bootloader.

Key Findings

▶ Watch: Challenges: Encrypted firmware and custom compression (2:20)

Alexandru Lazar's investigation into Dahua IP camera firmware yielded several critical findings, illuminating both the custom protection mechanisms employed by the vendor and significant vulnerabilities within their implementation.

  1. Custom Firmware Encryption/Compression Scheme: A primary discovery was Dahua's use of a proprietary, multi-stage encryption and compression scheme for its firmware and file systems. This was characterized by unusual U-image headers on file system components, high entropy files, and a custom signature (DH instead of PK) replacing standard Zip headers. The team successfully reverse-engineered this scheme, identifying it as AES-256 CBC with a unique key derivation process and a custom IV generation.
  1. Partial Decryption Flaw: A significant flaw in Dahua's decryption implementation was uncovered. During the in-place decryption process, specific blocks of data were intentionally or unintentionally skipped. This explained why initial Binwalk scans revealed fragmented strings and code within supposedly encrypted sections. The 0x200 hex (512 bytes) block size for decryption was not consistently applied, with the offset being incremented by more than 0x200 hex at certain points, leaving some blocks untouched and unencrypted in the final output.
  1. Two Remote Code Execution Vulnerabilities: The core contribution of the research was the identification and successful exploitation of two distinct vulnerabilities, both leading to remote code execution (RCE) and ultimately root access on affected Dahua devices:
  • HTTP Header Overflow (RPC2 upload file with name): This unauthenticated vulnerability affected the HTTP service. An incorrect parsing of the CC header within the RPC2 upload file with name handler allowed for an overflow of 0x34 bytes into the BSS section. This overflow corrupted a pointer within a HTTP session structure, which, when triggered by a token expiration check, allowed for the overwrite of a function pointer. By replacing this pointer with a call to system(), arbitrary commands could be executed.
  • ONVIF Stack-based Buffer Overflow (get capabilities): This second RCE was found in the ONVIF service, specifically within the unauthenticated get capabilities and get service capabilities endpoints. By imitating an IPv6 address format (enclosing the host header in square brackets), a size check for the Host header was bypassed. This led to a classical stack-based buffer overflow, allowing control over seven registers (R4-R11) and enabling the construction of a sophisticated ROP chain despite significant constraints (single null byte in payload, non-position independent code, no memory leak).
  1. Novel Exploitation Techniques for Embedded Systems: Lazar demonstrated innovative approaches to exploitation in constrained environments:
  • Crash-based Structure Reconstruction: Lacking a debugger, the team leveraged the device's TX pin output (which printed registers on crash) to iteratively reconstruct complex C structures in memory, byte by byte, through a series of controlled crashes.
  • Same-Epilog ROP Gadget Search: For the stack-based overflow, a critical challenge was the inability to build a multi-gadget ROP chain due to null bytes in low-address code. The solution involved searching for a specific ROP gadget that not only performed a desired action (e.g., writing to memory) but also had the exact same function epilog as the calling function. This ensured the stack pointer was restored correctly, allowing the program to continue execution after the gadget, preserving the payload in memory for subsequent execution.

These findings collectively paint a detailed picture of the security landscape of Dahua cameras, from their custom firmware protections to the exploitable flaws within their network services, offering valuable lessons for both manufacturers and security researchers in the IoT domain.

Technical Deep Dive

▶ Watch: Reversing the bootloader: Loading U-boot into Ghidra (3:50)

The technical journey began with the challenge of firmware extraction. For devices where firmware was not online, physical access was required to desolder the flash chip. A Bus Pirate was used as the hardware reader, with a custom Python script developed due to compatibility issues with standard tools like Flash ROM for the specific chip.

Initial analysis of the extracted firmware with Binwalk revealed U-image headers but failed to fully extract file systems, indicating custom obfuscation. The presence of zib signatures, despite being "false alarms," yielded readable strings and JavaScript upon extraction, suggesting a weak or partial encryption. Crucially, the standard PK zip signature was replaced with DH, hinting at a Dahua-specific format. This necessitated reverse-engineering the U-boot bootloader, which was unencrypted and found within the same firmware archive.

The U-boot binary was loaded into Ghidra, configured for R64 architecture on little endian (specifically for Dahua XVRs) with a base address of zero. The reverse engineering process started by looking for constants, particularly the AES substitution box (S-box), given the suspicion of encryption. Tracing references to the S-box led to functions with suggestive names like uboot encrypt file and firmware get key.

The decryption process was deduced to occur in four main steps:

  1. Firmware Key Generation: Hard-coded bytes were copied into a buffer, with the first six bytes dynamically replaced by the processor name, making the key device-type specific. Three functions, identified as SHA-256 hashing functions (deduced by plugging constants into tools like ChatGPT and verifying), generated a 32-byte hash. This hash was then truncated to 16 bytes by XORing the first half with the last half to form the final firmware key.
  2. Key Factors (File System): For the file system decryption, an empty buffer was used as a parameter. The actual keying material for this stage involved bitwise operations on hard-coded buffers. By recognizing patterns matching AES t-tables and loops iterating 10, 12, or 14 times, the researchers identified this as the AES key expansion part.
  3. AES Mode of Operation Determination: A function with five parameters (key size, input, output, flag, IV) was identified. The Initialization Vector (IV) was created in a loop, consisting of 16 characters incremented from 0x20 to 0x30 and 0x23 to 0x33. The plaintext was derived from two hard-coded 32-byte buffers that were added, divided, and cast to bytes. The resulting 32-byte plaintext was encrypted, and the last 16 bytes of its ciphertext were concatenated with the firmware key from step 1, forming a 32-byte AES key. By observing the cipher-text chaining (XORing with plaintext, calling block function, resulting ciphertext becoming new IV), the mode of operation was confirmed as AES-256 CBC.
  4. Setting Flags and Decryption Execution: This step, not present on all devices, involved a function with either five or seven parameters. It performed in-place decryption, where input and output addresses were the same. The decryption operated on 0x200 hex (512-byte) blocks. A critical flaw was identified here: while the IV started at zero and incremented, the offset added to the input pointer was sometimes incremented by more than 0x200 hex. This caused some blocks to be skipped, explaining why partially intelligible data was found in "encrypted" regions. With the key, IV, algorithm (AES-256 CBC), and input (extracted from the U-image header's size field), the file system was successfully decrypted, enabling Binwalk to function correctly.

With the file system accessible, the attack surface was mapped. The primary binary, named Sonia or Challenge, handled all network services. An initial nmap scan would only reveal three open ports (HTTP, RTSP, DHAP). However, deeper analysis of the binary revealed that multiple protocols (10-16, including UPnP, websocket, RTSP over HTTP) were multiplexed on these same ports, using regular expressions to parse incoming packets and dispatch them to the correct handler. While most handlers were authenticated, a few unauthenticated ones presented opportunities.

Vulnerability 1: HTTP Header Overflow (RPC2 upload file with name)

This vulnerability was found in an unauthenticated HTTP handler. The RPC2 upload file with name function was not problematic for its file upload capability (which was restricted to MP3s with fixed paths), but rather for its incorrect parsing of the CC HTTP header. The code used standard strncpy functions but failed to correctly specify the buffer size, instead using the string length. This allowed 0x34 bytes from the CC header to overflow into the BSS section, overwriting a pointer within a HTTP session-related structure.

The program would crash when attempting to check token expiration, which involved a function pointer stored in the overwritten structure. The exploitation strategy was to replace this cleanup function pointer with a call to system(). Lacking a debugger, Lazar leveraged the device's TX pin, which printed register states upon crashes. By iteratively sending crafted payloads and observing crash messages, he meticulously reconstructed the memory layout of the HTTP session structure, one pointer at a time. Once the function pointer was accurately located and overwritten with the address of system(), the next challenge was providing a payload. Since the camera's kernel prevented unsigned binaries, the team exploited the LD_PRELOAD privilege escalation trick. A custom shared library, compiled using a specifically configured buildroot toolchain (hard floating point and CIBC were crucial), was downloaded via TFTP, and LD_PRELOAD was used to execute it, granting root access.

Vulnerability 2: ONVIF Stack-based Buffer Overflow (get capabilities)

The second RCE was located in the ONVIF service, an IP camera-specific protocol. The get capabilities and get service capabilities endpoints were unauthenticated and vulnerable. They parsed the Host header to display available endpoints. If the Host header did not contain a square bracket (typical for IPv6 addresses), a size check of 64 bytes was applied. However, if a square bracket was present (e.g., Host: [::1]), this size check was skipped entirely, leading to a classical stack-based buffer overflow when the Host header was copied to the stack.

Exploitation was challenging due to several factors:

  • Control over registers R4-R11.
  • The strncpy function would terminate the payload with a single null byte, severely limiting ROP chain construction.
  • The camera's code was not position independent, and its base address was low, containing null bytes, further restricting ROP gadgets. This effectively limited ROP chains to a single gadget.
  • No memory leak was available to determine library addresses dynamically.

To overcome the single-gadget limitation and the absence of a direct payload, Lazar devised an ingenious approach: instead of a system() gadget, he sought a gadget that could write the payload into memory. The critical insight was that this gadget needed to have the same epilog as the caller function. This ensured that after the gadget executed its store instruction (e.g., store R7 to R5), the stack pointer would be correctly restored, allowing the program to continue execution without crashing and preserving the written payload in a writable section (like BSS, which resided at higher addresses without null bytes). Using Ghidra's instruction search window, about 15-60 such gadgets were found. A suitable gadget, storing 4 bytes at a time, was selected. By sending 10-15 requests, the full LD_PRELOAD payload (downloaded via TFTP) was written into the BSS section. Finally, a subsequent request would trigger the system gadget, pointing to the newly written payload in BSS via R6, again achieving root.

Demo / Proof of Concept

▶ Watch: Deriving the 16-byte firmware key using SHA-256 (5:40)

Due to technical difficulties with the screen during the live presentation, a visual demonstration of the exploits was not possible. However, Alexandru Lazar confidently stated that root access was achieved on the target devices through both vulnerabilities. The intended proof of concept would have involved showcasing the successful execution of arbitrary commands with root privileges, likely demonstrating the download and execution of the custom shared library via TFTP and LD_PRELOAD to gain a shell. This outcome served as a tangible validation of the reverse engineering efforts and the efficacy of the developed exploitation techniques.

Defensive Implications

▶ Watch: Identifying AES algorithm and key expansion (7:50)

The research by Alexandru Lazar provides crucial insights for both manufacturers and network defenders regarding the security of IoT cameras.

For Manufacturers (specifically Dahua and similar vendors):

  • Avoid Custom Encryption/Obfuscation: Custom security schemes are often weaker than industry-standard, well-vetted cryptographic implementations. The custom DH compression and AES-256 CBC with a custom IV and key derivation were ultimately reverse-engineered. Vendors should adhere to standard, robust cryptographic libraries and protocols.
  • Comprehensive Input Validation: The HTTP header overflow and the ONVIF stack-based buffer overflow both stemmed from inadequate input validation, particularly for HTTP headers. All input, regardless of its perceived criticality, must be rigorously validated for length, format, and content to prevent buffer overflows and other injection attacks.
  • Implement ASLR and Position Independent Code (PIC): The lack of position independent code significantly aided exploitation, especially for the stack-based buffer overflow. Implementing Address Space Layout Randomization (ASLR) and compiling binaries as PIC would make ROP chain construction much more difficult and less reliable, as gadget addresses would be randomized.
  • Enforce Authentication on All Sensitive Handlers: The discovery of unauthenticated handlers, even for seemingly innocuous functions like RPC2 upload file with name or get capabilities, created critical attack vectors. Every network service and endpoint should be protected by robust authentication and authorization mechanisms.
  • Secure Coding Practices: Fundamental flaws like incorrect strncpy usage (not using the buffer's size) highlight a need for improved secure coding training and automated static/dynamic analysis in the development pipeline.
  • Positive Vulnerability Disclosure Response: Dahua's response to the disclosure was commendable, using PGP, responding promptly, fixing the issues, and providing a list of affected devices. This level of transparency and collaboration is vital for effective vulnerability remediation across the IoT ecosystem.

For Users and Network Administrators:

  • Do Not Expose IoT Devices Directly to the Internet: This is the most critical defense. Cameras should be placed behind a firewall, ideally isolated on a separate VLAN, and accessed only via a VPN or secure proxy, not directly.
  • Regular Firmware Updates: Promptly apply firmware updates released by vendors. The fixes for these vulnerabilities would be delivered through such updates.
  • Network Segmentation: Isolate IoT devices on dedicated VLANs or subnets. This limits their ability to interact with critical internal networks even if compromised, preventing pivot attacks like those seen in ransomware incidents.
  • Monitor Network Traffic: Be vigilant for unusual network activity originating from IoT devices, such as unexpected TFTP downloads, as observed in the LD_PRELOAD exploit chain.
  • Understand Device Risks: Recognize that even common, seemingly simple devices like security cameras can pose significant security risks if not properly secured and managed. Assume IoT devices are vulnerable and plan defenses accordingly.

Key Takeaways

  • IoT devices, particularly IP cameras, remain highly attractive targets for attackers due to widespread internet exposure and often-lax security.
  • Custom encryption or obfuscation schemes implemented by vendors are frequently vulnerable to reverse engineering and can introduce critical flaws, as seen with Dahua's AES-256 CBC implementation.
  • Thorough input validation is paramount for all network services; even seemingly minor flaws in HTTP header parsing can lead to severe vulnerabilities like buffer overflows and remote code execution.
  • Exploiting embedded systems in the absence of debuggers is challenging but feasible through creative techniques, such as crash-based memory structure reconstruction and specialized ROP gadget searches (e.g., matching function epilogs).
  • Post-exploitation techniques like LD_PRELOAD can be highly effective on embedded Linux systems, allowing for code execution even when the kernel restricts unsigned binaries.
  • Effective vulnerability disclosure and vendor cooperation are crucial for the timely remediation of widespread security flaws in the IoT landscape.

About the Speaker(s)

Alexandru Lazar is a Security Researcher at B Defender. His work focuses on uncovering vulnerabilities in various systems, with a particular emphasis on embedded devices and IoT security. His research, as demonstrated in this talk, highlights a deep understanding of reverse engineering, exploit development, and the practical implications of security flaws in widely deployed consumer and enterprise technologies.

Reviews

Dr. Zero (Offensive Security Researcher) — STRONG ACCEPT

Solid embedded security research with genuine technical depth: full firmware decryption chain reverse-engineered from scratch, two unauthenticated RCEs developed under real constraints, and a clever same-epilog ROP technique I haven't seen documented this cleanly before. The demo failing on stage hurts, but the work stands on its own.

Heather Calloway (CISO) — WEAK

Technically rigorous exploit research on Dahua IP cameras with real-world relevance buried under craft admiration. The defensive section exists but reads like an afterthought — the operational and governance implications for the organizations actually running these devices at scale are never addressed.

→ Top-rated talks at DEF CON 33

All talks from DEF CON 33