Skip to main content

Boot Analysis

Overview​

The boot analysis examines the start phase of a firmware image. It works only on the extracted root filesystem and does not boot the firmware. It answers three questions:

  1. Which init system is used? (e.g. BusyBox init, systemd, SysV-Init)
  2. Which start scripts or units run during boot?
  3. Which binaries are started by them and which libraries do these binaries need?

The tool is registered as boot-analysis and depends on the extractor (binwalk), so it always runs after the firmware has been extracted.

Position in the pipeline​

PropertyValue
Tool name (DB, Redis)boot-analysis
Dependencybinwalk (extractor)
Redis queuequeue_boot-analysis
Worker processes2
Timeout900 seconds for one image
Containersrc/boot-analysis/Dockerfile_boot-analysis (contains file, readelf and QEMU user mode)
Inputroot filesystem found by the extractor (rootfs_path in extractor-output.json)
Outputboot-analysis-output.txt (log), boot-analysis-output.txt.result.json / .summary.json (result for the UI), boot-analysis-output.json (raw result), table boot_analysis_results

Directory structure​

All files are located in src/boot-analysis/.

PathPurpose
boot_analysis_tool.pyWorker entry point. Receives tasks from Redis, starts boot_analysis.py as a subprocess, stores the result in the database and reports the status back to the executor.
boot_analysis.pyAnalysis pipeline: find the root filesystem, detect the init system, run the matching analyzer, write the JSON result. Can also be called from the command line.
detect/detect_init.pyHeuristic detection of the init system and of the root filesystem inside the extraction folder.
analyze/analyze.pyDispatcher that calls the analyzer for the detected init system.
analyze/busybox.pyBusyBox init (including OpenWrt/procd, DD-WRT and Buildroot images).
analyze/sysvinit.pySysV-Init with Debian-style (/etc/rcN.d) or Red Hat-style (/etc/rc.d/rcN.d) runlevel directories.
analyze/systemd.pysystemd units and targets.
analyze/openrc.pyOpenRC runlevels.
analyze/runit.pyrunit stages and supervised services.
analyze/upstart.pyUpstart jobs in /etc/init/*.conf.
analyze/custom.pyFallback for images with their own init entry point (/init, /rc.local, ...).
utils/tools.pyShell script analysis: list start scripts, follow sourced scripts, extract and resolve executable names, parse inittab.
utils/binary_dependency_analyzer.pyStatic (readelf) and runtime (QEMU + strace) library dependencies of a binary.
utils/resolve_symlink.pyResolves symlinks of a binary.
utils/data_types.pyResult data classes BootAnalysisReturnObject and AnalyzedBinaryObject.
manual_test.pyDebug helper: runs only the BusyBox analyzer on a root filesystem.
statistics/init_statistics.pyOne-off script that detected the init systems of all AVM images in the downloads folder (results in statistics/scan_results_*.json).

In the container, worker_manager.py, tool_registry.py, firmware_orm/ and analysis_tool_set/utils.py from src/ are copied next to these files. analysis_tool_set is copied as a package, because boot-analysis has its own utils/ package, which would hide a plain utils.py.

Flow​

  1. Task received (boot_analysis_tool.handle_task): The worker reads the task from queue_boot-analysis. start_tool_output() writes a header to boot-analysis-output.txt and removes old result files.
  2. Subprocess (boot_analysis_tool.run_tool): boot_analysis.py <image_id> <image_path> <json_path> is started with a timeout of 900 seconds. Its stdout and stderr are appended to boot-analysis-output.txt.
  3. Root filesystem (boot_analysis.run_tool): get_rootfs_path() reads rootfs_path from extractor-output.json in the task folder. If the file or the field is missing, <image folder>/extracted is used.
  4. Detection (detect_init.scan_and_detect): Walks through the folder from step 3 and collects every directory that contains etc, bin, sbin, usr or var. For each candidate the init system is detected. The first candidate with a known init system is used as root path.
  5. Analysis (analyze.run_tool): The analyzer for the detected init system is called. Each analyzer returns a BootAnalysisReturnObject or "failure".
  6. Result: boot_analysis.py writes the object as JSON to boot-analysis-output.json. boot_analysis_tool.py reads it and stores one row in boot_analysis_results (store_unique_results, an identical row is not stored twice). finish_tool_output() writes the result for the UI (summary, metrics init system, root filesystem, default target, sysinit script, one item per field) and the status success is reported to the executor together with finding_count and status_message, see analysis results.

If no init system is found, an analyzer fails or no JSON file is written, the task status is failure (timeout after 900 seconds). fail_tool_output() writes the reason and the traceback to boot-analysis-output.txt; the reason is the last line printed by boot_analysis.py, e.g. Analysis failed: No boot analysis result for image 42: Init system could not be detected.

Init system detection​

detect_init_system() checks the heuristics in a fixed order. More specific checks come first, because many images contain several of the files (e.g. OpenWrt images also have an inittab). The first match wins.

OrderResultRule
1systemd/lib/systemd/system or /etc/systemd/system exists
2openrc/sbin/openrc-init, /etc/runlevels or /etc/conf.d exists
3upstart/etc/init/*.conf with start on and stop on
4runit/etc/runit exists, or /sbin/runit-init, /sbin/runit or /usr/bin/sv exists and is not a link to BusyBox (BusyBox also provides sv and runsv, which embedded systems use with a normal BusyBox init)
5busyboxprocd (OpenWrt): /sbin/procd, /etc/preinit mentions procd, or /etc/openwrt_release and /etc/init.d
6busybox/etc/inittab and (/sbin/init links to busybox, /bin/busybox exists or inittab contains a BusyBox-style rcS entry)
7sysvinit/etc/inittab and /etc/init.d/ or /etc/rc.d/
8custom/init, /rc.local or /etc/rc.local exists

If nothing matches, the result is unknown and the analysis stops.

Analyzers​

All analyzers fill the same result object. The fields targets, script_dependency_tree and binary_dependency_tree have a slightly different meaning for each init system.

AnalyzerEntry pointTargetsValue stored as init_system
BusyBoxsysinit entry in /etc/inittab (e.g. /etc/init.d/rcS)Executable start scripts in /etc/init.d (pattern taken from the rcS loop, default S*, with fallback patterns). /sbin/init is analyzed in addition.openwrt, ddwrt, buildroot or busybox (firmware variant, see below)
SysV-Initsysinit entry in /etc/inittabScripts in the runlevel directories 0 to 6sysvinit
systemdDefault target (default.target or a target that describes itself as default)All .target files; starting at the default target, all services with WantedBy=/RequiredBy= are followed (breadth first) and their After, Wants and Requires are resolvedsystemd, plus default_target
OpenRC/sbin/openrc-init or similarScripts enabled in the runlevels boot and defaultopenrc
runit/sbin/runit-init or /sbin/runit, stage 1 /etc/runit/1 as sysinit_scriptThe stage scripts /etc/runit/1 to 3 and the run, finish and log/run scripts of all enabled services (see below)runit, plus the runlevel (e.g. default) as default_target
Upstart/sbin/initAll /etc/init/*.conf jobs, with their start on condition and exec commandupstart
Custom/etc/inittab or /init, /rc.local, ...Scripts in /etc/init.d and the init entry point itselfcustom

The BusyBox analyzer reports the firmware variant instead of busybox:

ValueCondition
openwrt/etc/openwrt_release exists
ddwrt/etc/preinit exists
buildroot/etc/init.d exists
busyboxnone of the above

runit​

runit starts in three stages: /etc/runit/1 sets up the system, /etc/runit/2 starts runsvdir, which starts and supervises all services, and /etc/runit/3 shuts the system down. Every service is a directory with a run script. The enabled services are the entries of the directory that runsvdir watches, usually symlinks to /etc/sv/<name>. The analyzer looks for this directory in this order:

  1. the directory passed to runsvdir in /etc/runit/2, if it exists in the image (on Void Linux it is /run/runit/runsvdir/current, which is only created at boot),
  2. /etc/runit/runsvdir/current, /etc/runit/runsvdir/default (Void Linux), /etc/service (Debian), /var/service, /service,
  3. if none of them has services: all services in /etc/sv.

Service links are usually absolute (/etc/sv/sshd). The analyzer resolves them inside the root filesystem (resolve_in_rootfs()), never on the container filesystem. The found scripts are analyzed with the shell script analysis below, the runit init binary with the binary analysis. Tested with the root filesystem of the Void Linux container image (ghcr.io/void-linux/void-glibc-full): runlevel default, 3 stage scripts and the agetty service scripts. No firmware image in the test-firmware registry uses runit.

Shell script analysis​

BusyBox, SysV-Init, OpenRC, runit and Custom use the shell script analysis in utils/tools.py:

  1. Start scripts: list_startup_scripts() lists the executable files in the init directory that match the pattern.
  2. Sourced scripts: For each script, find_referenced_scripts() searches for . /path and source /path. Found scripts are queued as well (breadth first, each script only once).
  3. Executables: extract_executables_from_script() collects all words that are plain names or contain a /. Shell keywords and built-ins such as if, echo or export are ignored.
  4. Resolution: resolve_executables() keeps only the names that exist as executable files in the firmware. Absolute paths are checked directly. Plain names are searched in bin, sbin, usr/bin, usr/sbin, usr/local/bin, usr/local/sbin, opt/bin and opt/sbin (first match wins), because the $PATH of the firmware cannot be read reliably.
  5. Binary analysis: Every resolved executable is analyzed as described below.

Binary analysis​

binary_dependency_analyzer.analyze_binary() analyzes one executable:

  1. Symlinks are resolved (e.g. /sbin/init → bin/busybox).
  2. file checks whether it is an ELF binary. Scripts and other files get empty dependency lists.
  3. Static dependencies: The NEEDED entries from readelf -d.
  4. Runtime dependencies: The binary is started with the QEMU user-mode emulator that matches its architecture (MIPS, ARM, AArch64, PowerPC, x86, little or big endian) and -strace, with the root filesystem as library path (-L). All .so files that appear in the trace within 5 seconds are recorded.
caution

The runtime analysis executes binaries from the firmware (emulated, inside the boot-analysis container). The container should therefore not get more permissions or volumes than it needs.

Output​

boot-analysis-output.json​

The serialized BootAnalysisReturnObject (utils/data_types.py):

FieldTypeContent
root_pathstrRoot filesystem that was analyzed
init_systemstrDetected init system (see analyzer table)
init_filestr or nullConfiguration or binary the boot starts from (e.g. /etc/inittab)
sysinit_scriptstr or nullFirst script that is run (e.g. /etc/init.d/rcS)
targetslistStart scripts, units or jobs that run during boot
script_dependency_treedictScript/unit → list of executables or units it uses
binary_dependency_treedictExecutable → AnalyzedBinaryObject (name, path, static_dependencies, runtime_dependencies)
default_targetstr or nullOnly systemd: the default target

Example (Belkin RT1800, OpenWrt, shortened):

{
"root_path": ".../3670048-23038626.squashfs_v4_le_extract",
"init_system": "openwrt",
"init_file": ".../etc/inittab",
"sysinit_script": ".../etc/rcS",
"targets": [".../etc/init.d/firmware.sh"],
"script_dependency_tree": {".../etc/init.d/firmware.sh": ["sh"]},
"binary_dependency_tree": {
"sh": {"name": "sh", "path": "bin/busybox", "static_dependencies": ["libgcc_s.so.1", "libc.so"], "runtime_dependencies": ["libgcc_s.so.1"]},
"/sbin/init": {"name": "/sbin/init", "path": "bin/busybox", "static_dependencies": ["libgcc_s.so.1", "libc.so"], "runtime_dependencies": ["libgcc_s.so.1"]}
},
"default_target": null
}

Database​

boot_analysis_tool.py stores one row per run in boot_analysis_results: root_path, init_system, sysinit_script, default_target and targets (comma-separated). The dependency trees are only stored in the JSON file.

Log file​

boot-analysis-output.txt contains the output of boot_analysis.py (detected root path and init system, the steps of the analyzer), the final line Result: <status>. <summary> and, on failure, the reason and the traceback. Next to it, boot-analysis-output.txt.result.json holds the result shown in the UI and boot-analysis-output.txt.summary.json the same without the items.

Running it manually​

All steps can be run on their own on an extracted root filesystem, e.g. inside the boot-analysis container (cd /app/boot_analysis):

# Detect root filesystem and init system
python detect/detect_init.py /path/to/extracted

# Complete pipeline as used by the worker
python boot_analysis.py <image_id> /path/to/image.bin /path/to/boot-analysis-output.json

# Only the analyzer for a given init system
python -m analyze.analyze /path/to/rootfs busybox

# Dependencies of single binaries
python -m utils.binary_dependency_analyzer /path/to/rootfs /path/to/rootfs/bin/busybox

The analyzer and the dependency analyzer must be started as modules (python -m). Started as a file (python analyze/analyze.py), their imports fail.

boot_analysis.py uses the same root filesystem lookup as the worker: it looks for extractor-output.json in the folder of the given output file.

Tests​

FileCovers
tests/unit/test_boot_analysis_detect.pyOrder of the init system heuristics (table above), finding a nested root filesystem
tests/unit/test_boot_analysis_runit.pyrunit analyzer (Void and Debian layout, fallback to /etc/sv), symlink resolution inside the root filesystem, runit detection with BusyBox applets
tests/unit/test_boot_analysis_rootfs.pyRoot filesystem from extractor-output.json, fallback to extracted/, import of get_rootfs_path from the analysis_tool_set package
tests/integration/test_tools.py (test_boot_analysis_*)Tool registration, storing results (also with long paths), failure when no init system is found

Known limitations​

These points were found while writing this documentation (tested on images from the test-firmware package registry, see Testing Pipeline):

  • Absolute symlinks are resolved outside the firmware. resolve_symlink.resolve() and tools.resolve_path_link() follow an absolute link target (e.g. /sbin/init → /bin/sh) on the container filesystem instead of inside the root filesystem. Then the binary of the container is analyzed, or the dependencies stay empty if the target does not exist in the container. Relative links (../bin/busybox) work. (#270)
  • The executable extraction is a word-based heuristic. Arguments or file names in scripts can be taken as executables if a file with that name exists in a bin directory.
  • The runtime dependencies only contain libraries that the binary opens in the first 5 seconds of emulation.
  • The extractor currently produces empty files for some CramFS images (e.g. Belkin F5D8630), so the binary analysis finds no dependencies there. (#269)
  • manual_test.py only covers BusyBox. statistics/init_statistics.py is hard-coded to AVM.