Перейти к основному содержимому
Firmware Analysis: Unpacking SquashFS/JFFS2 with Binwalk
Урок 5 из 9

Firmware Analysis: Unpacking SquashFS/JFFS2 with Binwalk

Carve and unpack embedded filesystems such as SquashFS and JFFS2 from raw firmware images using Binwalk and unsquashfs, then audit the extracted rootfs for hardcoded secrets and insecure services.

Продвинутый 30 мин IoT и встраиваемые
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Interpret Binwalk signature scans and entropy plots to map partitions inside a firmware image
  • Carve and unpack SquashFS and JFFS2 filesystems safely without falling prey to symlink traversal
  • Audit an extracted Linux root filesystem for hardcoded credentials, private keys, and risky startup scripts using firmwalker and manual checks
  • Explain common vendor packing variations and remediation controls for embedded filesystems

Рекомендуется заранее: IoT Architecture, Embedded Linux & Microcontroller BasicsFirmware Extraction: OTA Captures, Flash Dumps & Bootloaders

#Why this matters

A raw flash dump or downloaded .bin update is rarely a single file; it is usually a container holding a bootloader, a kernel image, one or more compressed filesystems, and configuration blocks concatenated together. Before you can inspect web scripts or reverse engineer native daemons, you must locate each partition and unpack its filesystem into a readable directory tree.

Once unpacked, an embedded Linux root filesystem (rootfs) often reveals critical security flaws in minutes: shared TLS private keys baked into every manufactured unit, factory root passwords in /etc/shadow, or boot scripts launching telnet and unauthenticated diagnostic services.

#Mapping the image with Binwalk

The first step after verifying your firmware hash is scanning for known headers with binwalk. Binwalk searches the binary for magic bytes belonging to bootloaders, compression streams (LZMA, gzip, XZ), kernels (uImage), and filesystems (SquashFS, CramFS, JFFS2, UBIFS).

Scanning an extracted router firmware image
$ binwalk router_v3.bin

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
0             0x0             uImage header, header size: 64 bytes, load address: 0x80000000, image name: "MIPS OpenWrt Linux"
64            0x40            LZMA compressed data, properties: 0x6D, dictionary size: 8388608 bytes
1572864       0x180000        Squashfs filesystem, little endian, version 4.0, compression:xz, size: 6815744 bytes, 1248 inodes
8519680       0x820000        JFFS2 filesystem, little endian

Notice what this table tells you immediately:

  • Offset 0x0 holds the Linux kernel wrapped in a U-Boot uImage header, compressed with LZMA starting at 0x40.
  • Offset 0x180000 (1572864 bytes) starts a little-endian SquashFS 4.0 root filesystem compressed with XZ.
  • Offset 0x820000 holds a JFFS2 partition, typically mounted as a writable overlay for user settings and logs.
  1. Raw imagebinwalk signature + entropy scan
  2. Carvedd or binwalk -e at exact offsets
  3. Unpackunsquashfs (SquashFS) / jefferson (JFFS2)
  4. Auditfirmwalker + manual /etc and CGI review

Automatic extraction (binwalk -e router_v3.bin) handles standard layouts quickly, and recent Binwalk versions isolate extractors under a non-privileged account (such as --run-as=nobody when invoked with elevated privileges). Still, automated extraction can produce false positives on random byte sequences inside code, so knowing how to carve manually is essential.

#Manual carving and filesystem unpacking

Filesystem Typical role Magic / signature Standard unpacking tool
SquashFS Read-only rootfs hsqs (LE) or sqsh (BE) unsquashfs (or sasquatch for custom headers)
JFFS2 Writable config overlay 0x1985 node marker jefferson
UBIFS Large NAND flash volumes UBI# eraseblock header ubireader_extract_files

#Carving and unpacking SquashFS

Using the exact decimal offset reported by binwalk (1572864), carve the SquashFS partition with dd and inspect or extract it with unsquashfs:

Carving SquashFS with dd and extracting with unsquashfs
$ dd if=router_v3.bin of=rootfs.squashfs bs=1 skip=1572864 count=6815744 status=none
$ unsquashfs -s rootfs.squashfs
Found a valid SQUASHFS 4:0 superblock on rootfs.squashfs.
Compression used xz
$ unsquashfs -d rootfs_out rootfs.squashfs
Parallel unsquashfs: Using 4 processors
1182 inodes (1294 blocks) to write
created 964 files
created 112 directories
created 106 symlinks

If unsquashfs rejects an image that binwalk clearly labeled as SquashFS, check for vendor customizations. Some manufacturers alter the four-byte magic string (for instance replacing hsqs with a vendor tag) or use non-standard LZMA dictionary parameters. In those cases, tools like sasquatch (which patches common vendor variants) or restoring the standard hsqs header in a hex copy unlocks extraction.

#Handling JFFS2 and UBIFS partitions

Unlike SquashFS, JFFS2 has no central superblock; it consists of linked nodes tagged with 0x1985 across flash eraseblocks. Standard Linux mount requires an MTD block device (mtdram), whereas jefferson parses JFFS2 nodes directly in user space into a folder. Similarly, modern NAND devices wrap UBIFS inside UBI wear-leveling headers (UBI#), which ubireader_extract_files unpacks cleanly without kernel modules.

#Auditing the unpacked filesystem

Once you have rootfs_out/, resist the urge to open random binaries immediately. Start with a structured configuration and secret sweep.

Automated scripts like firmwalker scan an extracted rootfs against curated checklists: /etc/shadow, /etc/passwd, SSL/TLS .pem and .key files, SSH host keys, database files, shell scripts, common embedded servers (lighttpd, uhttpd, goahead, dropbear), and embedded IP addresses or URLs.

Complement automated scans with targeted manual checks across four high-value areas:

  1. Boot and service startup: read /etc/inittab and /etc/init.d/* (or /etc/rc.d/*). These scripts show every daemon launched at boot, the flags passed to web servers, and whether debug shells (telnetd, UART getty) run unconditionally.
  2. Accounts and hashes: inspect /etc/passwd and /etc/shadow. Look for default password hashes shared across all devices, empty password fields, or extra UID 0 accounts.
  3. Keys and certificates: search for private keys (BEGIN RSA PRIVATE KEY, BEGIN EC PRIVATE KEY), .p12 bundles, and hardcoded API tokens in /etc, /www, or /usr/share.
  4. Web and CGI handlers: inspect /www or /srv/www for shell/Lua CGI scripts that pass QUERY_STRING or form fields straight into system(), eval, or backticks.
Manual triage commands inside an extracted rootfs
$ cd rootfs_out
$ cat etc/shadow
root:$1$aBcDeFgH$9kLmNoPqRsTuVwXyZ01234:18200:0:99999:7:::
support:$1$99887766$A1B2C3D4E5F6G7H8I9J0K1:18200:0:99999:7:::
$ find . -type f \( -name "*.key" -o -name "*.pem" \)
./etc/uhttpd.key
./etc/uhttpd.crt
$ grep -rnE "(password|api_key|telnetd)" etc/ www/ 2>/dev/null | head -n 5
etc/init.d/rcS:42:/usr/sbin/telnetd -l /bin/sh &
www/cgi-bin/diag.sh:11:ping -c 1 "$TARGET_HOST"

Notice two major findings from just three commands: etc/shadow contains an MD5-crypt ($1$) support account alongside root, and etc/init.d/rcS starts telnetd directly with /bin/sh, bypassing authentication entirely.

#Common mistakes and defence

  • Extracting as root on a production workstation: always extract inside an unprivileged sandbox or VM so crafted SquashFS device nodes or symlinks cannot touch host files.
  • Trusting false-positive Binwalk signatures: Binwalk matches short magic patterns inside compiled machine code; verify alignment, plausible sizes, and entropy transitions before carving.
  • Missing writable overlays: credentials, Wi-Fi PSKs, and runtime configs often live in the JFFS2 or UBIFS data partition rather than the read-only SquashFS rootfs.
  • Vendor hardening checklist: generate unique per-device TLS keys at provisioning rather than baking .key files into SquashFS, disable telnetd and factory debug hooks in release builds, and avoid shell-script CGI wrappers that interpolate unsanitized inputs.

#Summary

Unpacking firmware requires mapping partition offsets with binwalk, carving filesystems cleanly with dd, and extracting formats such as SquashFS (unsquashfs) and JFFS2 (jefferson) inside an unprivileged sandbox. Once unpacked, combining automated sweeps (firmwalker) with manual inspection of /etc/init.d, /etc/shadow, keys, and CGI scripts quickly exposes hardcoded secrets, backdoor shells, and unsafe services.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания