I-reverse engineering ang isang home router gamit ang binwalk. Nagtitiwala ka ba sa software ng iyong router?

I-reverse engineering ang isang home router gamit ang binwalk. Nagtitiwala ka ba sa software ng iyong router?

Ilang araw ang nakalipas, nagpasya akong i-reverse engineer ang firmware ng aking router gamit ang binwalk.

Binili ko ang sarili ko TP-Link Archer C7 home router. Hindi ang pinakamahusay na router, ngunit sapat na para sa aking mga pangangailangan.

Sa tuwing bibili ako ng bagong router, nag-i-install ako OpenWRT. Para saan? Bilang isang patakaran, ang mga tagagawa ay hindi masyadong nagmamalasakit sa pagsuporta sa kanilang mga router at sa paglipas ng panahon ang software ay nagiging lipas na, ang mga kahinaan ay lilitaw, at iba pa, sa pangkalahatan, nakuha mo ang ideya. Samakatuwid, mas gusto ko ang OpenWRT firmware, na mahusay na sinusuportahan ng open-source na komunidad.

Ang pagkakaroon ng pag-download ng OpenWRT, ako rin na-download ang pinakabagong imahe ng firmware sa ilalim ng aking bagong Archer C7 mula sa opisyal na website at nagpasyang pag-aralan ito. Puro katuwaan at usapan tungkol sa binwalk.

Ano ang binwalk?

Binwalk ay isang open source tool para sa pagsusuri, reverse engineering at firmware image extraction.

Nilikha noong 2010 ni Craig Heffner, ang binwalk ay maaaring mag-scan ng mga imahe ng firmware at maghanap ng mga file, tukuyin at i-extract ang mga imahe ng file system, executable code, compressed archive, bootloader at kernels, mga format ng file gaya ng JPEG at PDF, at marami pang iba.

Maaari mong gamitin ang binwalk para i-reverse engineer ang firmware para maunawaan kung paano ito gumagana. Maghanap ng mga binary file para sa mga kahinaan, mag-extract ng mga file, at maghanap ng mga backdoor o digital na certificate. Maaari mo ring mahanap opcodes para sa isang grupo ng iba't ibang mga CPU.

Maaari kang mag-extract ng mga imahe ng filesystem upang maghanap ng mga partikular na file ng password (passwd, shadow, atbp.) at subukang sirain ang mga hash ng password. Maaari kang magsagawa ng binary parsing sa pagitan ng dalawa o higit pang mga file. Maaari kang magsagawa ng pagsusuri sa entropy sa data upang maghanap ng naka-compress na data o naka-encode na mga susi sa pag-encrypt. Ang lahat ng ito nang hindi kinakailangang i-access ang source code.

Sa pangkalahatan, nandiyan ang lahat ng kailangan mo :)

Paano gumagana ang binwalk?

Ang pangunahing tampok ng binwalk ay ang signature scan nito. Maaaring i-scan ng Binwalk ang imahe ng firmware upang maghanap ng iba't ibang mga built-in na uri ng file at file system.

Alam mo ba ang command line utility file?

file /bin/bash
/bin/bash: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=12f73d7a8e226c663034529c8dd20efec22dde54, stripped

Koponan filetumitingin sa header ng file at naghahanap ng signature (magic number) para matukoy ang uri ng file. Halimbawa, kung ang file ay nagsisimula sa pagkakasunud-sunod ng mga byte 0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A, alam nitong PNG file ito. Naka-on Wikipedia Mayroong isang listahan ng mga karaniwang file signature.

Ang Binwalk ay gumagana sa parehong paraan. Ngunit sa halip na maghanap ng mga lagda lamang sa simula ng file, i-scan ng binwalk ang buong file. Bukod pa rito, maaaring i-extract ng binwalk ang mga file na makikita sa larawan.

Tools file ΠΈ binwalk gamitin ang library libmagic upang matukoy ang mga lagda ng file. Pero binwalk Bukod pa rito ay sumusuporta sa isang listahan ng mga custom na magic signature para maghanap ng mga naka-compress/zip na file, firmware header, Linux kernel, bootloader, filesystem at iba pa.

Magsaya tayo?

Pag-install ng Binwalk

Sinusuportahan ang Binwalk sa maraming platform kabilang ang Linux, OSX, FreeBSD at Windows.

Upang i-install ang pinakabagong bersyon ng binwalk maaari mong i-download ang source code at sumunod mga tagubilin sa pag-install o mabilis na gabay, magagamit sa website ng proyekto.

Ang Binwalk ay may maraming iba't ibang mga parameter:

$ binwalk

Binwalk v2.2.0
Craig Heffner, ReFirmLabs
https://github.com/ReFirmLabs/binwalk

Usage: binwalk [OPTIONS] [FILE1] [FILE2] [FILE3] ...

Signature Scan Options:
    -B, --signature              Scan target file(s) for common file signatures
    -R, --raw=<str>              Scan target file(s) for the specified sequence of bytes
    -A, --opcodes                Scan target file(s) for common executable opcode signatures
    -m, --magic=<file>           Specify a custom magic file to use
    -b, --dumb                   Disable smart signature keywords
    -I, --invalid                Show results marked as invalid
    -x, --exclude=<str>          Exclude results that match <str>
    -y, --include=<str>          Only show results that match <str>

Extraction Options:
    -e, --extract                Automatically extract known file types
    -D, --dd=<type:ext:cmd>      Extract <type> signatures, give the files an extension of <ext>, and execute <cmd>
    -M, --matryoshka             Recursively scan extracted files
    -d, --depth=<int>            Limit matryoshka recursion depth (default: 8 levels deep)
    -C, --directory=<str>        Extract files/folders to a custom directory (default: current working directory)
    -j, --size=<int>             Limit the size of each extracted file
    -n, --count=<int>            Limit the number of extracted files
    -r, --rm                     Delete carved files after extraction
    -z, --carve                  Carve data from files, but don't execute extraction utilities
    -V, --subdirs                Extract into sub-directories named by the offset

Entropy Options:
    -E, --entropy                Calculate file entropy
    -F, --fast                   Use faster, but less detailed, entropy analysis
    -J, --save                   Save plot as a PNG
    -Q, --nlegend                Omit the legend from the entropy plot graph
    -N, --nplot                  Do not generate an entropy plot graph
    -H, --high=<float>           Set the rising edge entropy trigger threshold (default: 0.95)
    -L, --low=<float>            Set the falling edge entropy trigger threshold (default: 0.85)

Binary Diffing Options:
    -W, --hexdump                Perform a hexdump / diff of a file or files
    -G, --green                  Only show lines containing bytes that are the same among all files
    -i, --red                    Only show lines containing bytes that are different among all files
    -U, --blue                   Only show lines containing bytes that are different among some files
    -u, --similar                Only display lines that are the same between all files
    -w, --terse                  Diff all files, but only display a hex dump of the first file

Raw Compression Options:
    -X, --deflate                Scan for raw deflate compression streams
    -Z, --lzma                   Scan for raw LZMA compression streams
    -P, --partial                Perform a superficial, but faster, scan
    -S, --stop                   Stop after the first result

General Options:
    -l, --length=<int>           Number of bytes to scan
    -o, --offset=<int>           Start scan at this file offset
    -O, --base=<int>             Add a base address to all printed offsets
    -K, --block=<int>            Set file block size
    -g, --swap=<int>             Reverse every n bytes before scanning
    -f, --log=<file>             Log results to file
    -c, --csv                    Log results to file in CSV format
    -t, --term                   Format output to fit the terminal window
    -q, --quiet                  Suppress output to stdout
    -v, --verbose                Enable verbose output
    -h, --help                   Show help output
    -a, --finclude=<str>         Only scan files whose names match this regex
    -p, --fexclude=<str>         Do not scan files whose names match this regex
    -s, --status=<int>           Enable the status server on the specified port

Pag-scan ng larawan

Magsimula tayo sa pamamagitan ng paghahanap ng mga lagda ng file sa loob ng larawan (larawan mula sa site TP-Link).

Pagpapatakbo ng binwalk gamit ang --signature parameter:

$ binwalk --signature --term archer-c7.bin

DECIMAL       HEXADECIMAL     DESCRIPTION
------------------------------------------------------------------------------------------
21876         0x5574          U-Boot version string, "U-Boot 1.1.4-g4480d5f9-dirty (May
                              20 2019 - 18:45:16)"
21940         0x55B4          CRC32 polynomial table, big endian
23232         0x5AC0          uImage header, header size: 64 bytes, header CRC:
                              0x386C2BD5, created: 2019-05-20 10:45:17, image size:
                              41162 bytes, Data Address: 0x80010000, Entry Point:
                              0x80010000, data CRC: 0xC9CD1E38, OS: Linux, CPU: MIPS,
                              image type: Firmware Image, compression type: lzma, image
                              name: "u-boot image"
23296         0x5B00          LZMA compressed data, properties: 0x5D, dictionary size:
                              8388608 bytes, uncompressed size: 97476 bytes
64968         0xFDC8          XML document, version: "1.0"
78448         0x13270         uImage header, header size: 64 bytes, header CRC:
                              0x78A267FF, created: 2019-07-26 07:46:14, image size:
                              1088500 bytes, Data Address: 0x80060000, Entry Point:
                              0x80060000, data CRC: 0xBB9D4F94, OS: Linux, CPU: MIPS,
                              image type: Multi-File Image, compression type: lzma,
                              image name: "MIPS OpenWrt Linux-3.3.8"
78520         0x132B8         LZMA compressed data, properties: 0x6D, dictionary size:
                              8388608 bytes, uncompressed size: 3164228 bytes
1167013       0x11CEA5        Squashfs filesystem, little endian, version 4.0,
                              compression:xz, size: 14388306 bytes, 2541 inodes,
                              blocksize: 65536 bytes, created: 2019-07-26 07:51:38
15555328      0xED5B00        gzip compressed data, from Unix, last modified: 2019-07-26
                              07:51:41

Ngayon ay mayroon kaming maraming impormasyon tungkol sa larawang ito.

Mga gamit ng larawan submarino bilang isang bootloader (header ng imahe sa 0x5AC0 at isang naka-compress na bootloader na imahe sa 0x5B00). Batay sa uImage header sa 0x13270, alam namin na ang arkitektura ng processor ay MIPS at ang Linux kernel ay bersyon 3.3.8. At base sa larawang makikita sa address 0x11CEA5, makikita natin yan rootfs ay isang file system squashfs.

I-extract natin ngayon ang bootloader (U-Boot) gamit ang command dd:

$ dd if=archer-c7.bin of=u-boot.bin.lzma bs=1 skip=23296 count=41162
41162+0 records in
41162+0 records out
41162 bytes (41 kB, 40 KiB) copied, 0,0939608 s, 438 kB/s

Dahil ang imahe ay naka-compress gamit ang LZMA, kailangan nating i-decompress ito:

$ unlzma u-boot.bin.lzma

Ngayon ay mayroon na tayong U-Boot na imahe:

$ ls -l u-boot.bin
-rw-rw-r-- 1 sprado sprado 97476 Fev  5 08:48 u-boot.bin

Paano ang tungkol sa paghahanap ng default na halaga para sa bootargs?

$ strings u-boot.bin | grep bootargs
bootargs
bootargs=console=ttyS0,115200 board=AP152 rootfstype=squashfs init=/etc/preinit mtdparts=spi0.0:128k(factory-uboot),192k(u-boot),64k(ART),1536k(uImage),14464k@0x1e0000(rootfs) mem=128M

Variable ng U-Boot Environment bootargs ginamit upang ipasa ang mga parameter sa Linux kernel. At mula sa itaas, mayroon kaming mas mahusay na pag-unawa sa flash memory ng device.

Paano ang tungkol sa pag-extract ng Linux kernel image?

$ dd if=archer-c7.bin of=uImage bs=1 skip=78448 count=1088572
1088572+0 records in
1088572+0 records out
1088572 bytes (1,1 MB, 1,0 MiB) copied, 1,68628 s, 646 kB/s

Maaari naming suriin na ang imahe ay matagumpay na nakuha gamit ang command file:

$ file uImage
uImage: u-boot legacy uImage, MIPS OpenWrt Linux-3.3.8, Linux/MIPS, Multi-File Image (lzma), 1088500 bytes, Fri Jul 26 07:46:14 2019, Load Address: 0x80060000, Entry Point: 0x80060000, Header CRC: 0x78A267FF, Data CRC: 0xBB9D4F94

Ang format ng uImage file ay karaniwang isang Linux kernel image na may karagdagang header. Alisin natin ang header na ito para makuha ang panghuling imahe ng kernel ng Linux:

$ dd if=uImage of=Image.lzma bs=1 skip=72
1088500+0 records in
1088500+0 records out
1088500 bytes (1,1 MB, 1,0 MiB) copied, 1,65603 s, 657 kB/s

Naka-compress ang larawan, kaya i-unpack natin ito:

$ unlzma Image.lzma

Ngayon ay mayroon na kaming Linux kernel image:

$ ls -la Image
-rw-rw-r-- 1 sprado sprado 3164228 Fev  5 10:51 Image

Ano ang maaari nating gawin sa imahe ng kernel? Maaari naming, halimbawa, gumawa ng string na paghahanap sa larawan at hanapin ang bersyon ng Linux kernel at alamin ang tungkol sa kapaligiran na ginamit sa pagbuo ng kernel:

$ strings Image | grep "Linux version"
Linux version 3.3.8 (leo@leo-MS-7529) (gcc version 4.6.3 20120201 (prerelease) (Linaro GCC 4.6-2012.02) ) #1 Mon May 20 18:53:02 CST 2019

Kahit na ang firmware ay inilabas noong nakaraang taon (2019), habang isinusulat ko ang artikulong ito ay gumagamit ito ng lumang bersyon ng Linux kernel (3.3.8) na inilabas noong 2012, na pinagsama-sama sa isang napakalumang bersyon ng GCC (4.6) mula noong 2012. !
(approx. transl. pinagkakatiwalaan mo pa rin ba ang iyong mga router sa opisina at sa bahay?)

May opsyon --opcodes maaari rin nating gamitin ang binwalk upang maghanap ng mga tagubilin sa makina at matukoy ang arkitektura ng processor ng imahe:

$ binwalk --opcodes Image
DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
2400          0x960           MIPS instructions, function epilogue
2572          0xA0C           MIPS instructions, function epilogue
2828          0xB0C           MIPS instructions, function epilogue

Paano ang root file system? Sa halip na manu-manong i-extract ang larawan, gamitin natin ang opsyon binwalk --extract:

$ binwalk --extract --quiet archer-c7.bin

Ang kumpletong root filesystem ay makukuha sa isang subdirectory:

$ cd _archer-c7.bin.extracted/squashfs-root/

$ ls
bin  dev  etc  lib  mnt  overlay  proc  rom  root  sbin  sys  tmp  usr  var  www

$ cat etc/banner
     MM           NM                    MMMMMMM          M       M
   $MMMMM        MMMMM                MMMMMMMMMMM      MMM     MMM
  MMMMMMMM     MM MMMMM.              MMMMM:MMMMMM:   MMMM   MMMMM
MMMM= MMMMMM  MMM   MMMM       MMMMM   MMMM  MMMMMM   MMMM  MMMMM'
MMMM=  MMMMM MMMM    MM       MMMMM    MMMM    MMMM   MMMMNMMMMM
MMMM=   MMMM  MMMMM          MMMMM     MMMM    MMMM   MMMMMMMM
MMMM=   MMMM   MMMMMM       MMMMM      MMMM    MMMM   MMMMMMMMM
MMMM=   MMMM     MMMMM,    NMMMMMMMM   MMMM    MMMM   MMMMMMMMMMM
MMMM=   MMMM      MMMMMM   MMMMMMMM    MMMM    MMMM   MMMM  MMMMMM
MMMM=   MMMM   MM    MMMM    MMMM      MMMM    MMMM   MMMM    MMMM
MMMM$ ,MMMMM  MMMMM  MMMM    MMM       MMMM   MMMMM   MMMM    MMMM
  MMMMMMM:      MMMMMMM     M         MMMMMMMMMMMM  MMMMMMM MMMMMMM
    MMMMMM       MMMMN     M           MMMMMMMMM      MMMM    MMMM
     MMMM          M                    MMMMMMM        M       M
       M
 ---------------------------------------------------------------
   For those about to rock... (%C, %R)
 ---------------------------------------------------------------

Ngayon ay maaari tayong gumawa ng maraming iba't ibang mga bagay.

Maaari kaming maghanap ng mga configuration file, password hash, cryptographic key at digital certificate. Maaari naming pag-aralan ang mga binary file para sa pag-troubleshoot at mga kahinaan.

May qemu ΠΈ chroot maaari pa rin nating patakbuhin (gayahin) ang isang maipapatupad mula sa imahe:

$ ls
bin  dev  etc  lib  mnt  overlay  proc  rom  root  sbin  sys  tmp  usr  var  www

$ cp /usr/bin/qemu-mips-static .

$ sudo chroot . ./qemu-mips-static bin/busybox
BusyBox v1.19.4 (2019-05-20 18:13:49 CST) multi-call binary.
Copyright (C) 1998-2011 Erik Andersen, Rob Landley, Denys Vlasenko
and others. Licensed under GPLv2.
See source distribution for full notice.

Usage: busybox [function] [arguments]...
   or: busybox --list[-full]
   or: function [arguments]...

    BusyBox is a multi-call binary that combines many common Unix
    utilities into a single executable.  Most people will create a
    link to busybox for each function they wish to use and BusyBox
    will act like whatever it was invoked as.

Currently defined functions:
    [, [[, addgroup, adduser, arping, ash, awk, basename, cat, chgrp, chmod, chown, chroot, clear, cmp, cp, crond, crontab, cut, date, dd, delgroup, deluser, dirname, dmesg, echo, egrep, env, expr, false,
    fgrep, find, free, fsync, grep, gunzip, gzip, halt, head, hexdump, hostid, id, ifconfig, init, insmod, kill, killall, klogd, ln, lock, logger, ls, lsmod, mac_addr, md5sum, mkdir, mkfifo, mknod, mktemp,
    mount, mv, nice, passwd, pgrep, pidof, ping, ping6, pivot_root, poweroff, printf, ps, pwd, readlink, reboot, reset, rm, rmdir, rmmod, route, sed, seq, sh, sleep, sort, start-stop-daemon, strings,
    switch_root, sync, sysctl, tail, tar, tee, telnet, test, tftp, time, top, touch, tr, traceroute, true, udhcpc, umount, uname, uniq, uptime, vconfig, vi, watchdog, wc, wget, which, xargs, yes, zcat

Malaki! Ngunit pakitandaan na ang bersyon ng BusyBox ay 1.19.4. Ito ay isang napakalumang bersyon ng BusyBox, inilabas noong Abril 2012.

Kaya't ang TP-Link ay naglabas ng imahe ng firmware sa 2019 gamit ang software (GCC toolchain, kernel, BusyBox, atbp.) mula 2012!

Ngayon naiintindihan mo na ba kung bakit palagi kong ini-install ang OpenWRT sa aking mga router?

Hindi lamang yan

Ang Binwalk ay maaari ding magsagawa ng pagsusuri sa entropy, mag-print ng hilaw na data ng entropy, at bumuo ng mga entropy graph. Karaniwan, ang mas malaking entropy ay sinusunod kapag ang mga byte sa imahe ay random. Ito ay maaaring mangahulugan na ang larawan ay naglalaman ng isang naka-encrypt, naka-compress, o na-obfuscate na file. Hardcore encryption key? Bakit hindi.

I-reverse engineering ang isang home router gamit ang binwalk. Nagtitiwala ka ba sa software ng iyong router?

Maaari rin nating gamitin ang parameter --raw upang makahanap ng custom na raw byte na sequence sa isang larawan o parameter --hexdump upang magsagawa ng hex dump na naghahambing ng dalawa o higit pang mga input file.

Mga custom na lagda maaaring idagdag sa binwalk alinman sa pamamagitan ng custom na signature file na tinukoy sa command line gamit ang parameter --magic, o sa pamamagitan ng pagdaragdag sa kanila sa direktoryo $ HOME / .config / binwalk / magic.

Makakahanap ka ng higit pang impormasyon tungkol sa binwalk sa opisyal na dokumentasyon.

extension ng binwalk

Doon API binwalk, na ipinatupad bilang isang Python module na maaaring gamitin ng anumang script ng Python upang magsagawa ng isang binwalk scan, at ang binwalk command line utility ay maaaring halos ganap na madoble gamit ang dalawang linya lamang ng Python code!

import binwalk
binwalk.scan()

Gamit ang Python API maaari ka ring lumikha Mga plugin ng Python upang i-configure at palawakin ang binwalk.

Mayroon din IDA plugin at bersyon ng ulap Binwalk Pro.

Kaya bakit hindi mo i-download ang imahe ng firmware mula sa Internet at subukan ang binwalk? Ipinapangako ko na magiging masaya ka :)

Pinagmulan: www.habr.com

Magdagdag ng komento