Ingegneria inversa di un router di casa cù binwalk. Avete fiducia in u software di u vostru router?

Ingegneria inversa di un router di casa cù binwalk. Avete fiducia in u software di u vostru router?

Uni pochi ghjorni fà, aghju decisu di ingegneria inversa u firmware di u mo router utilizendu binwalk.

Mi compru Router di casa TP-Link Archer C7. Ùn hè micca u megliu router, ma abbastanza per i mo bisogni.

Ogni volta chì compru un novu router, aghju installatu openwrt. Perchè? In regula, i pruduttori ùn importa micca assai di sustene i so routers è cù u tempu u software diventa obsoletu, i vulnerabili appariscenu, è cusì, in generale, avete l'idea. Per quessa, aghju preferitu u firmware OpenWRT, chì hè ben supportatu da a cumunità open-source.

Dopu avè scaricatu OpenWRT, aghju ancu scaricatu l'ultima immagine di firmware sottu u mo novu Archer C7 da u situ ufficiale è decisu di analizà. Puramente per piacè è parlà di binwalk.

Cosa hè binwalk?

Binwalk hè un strumentu open source per l'analisi, l'ingenieria inversa è l'estrazione di l'imagine di firmware.

Creatu in u 2010 da Craig Heffner, binwalk pò scansà l'imaghjini di firmware è truvà i fugliali, identificà è estrae l'imaghjini di u sistema di fugliali, codice eseguibile, archivi compressi, bootloaders è kernels, formati di fugliale cum'è JPEG è PDF, è assai di più.

Pudete aduprà binwalk per ingegneria inversa u firmware per capisce cumu funziona. Cercate i file binari per vulnerabilità, estrae i fugliali, è cercate backdoors o certificati digitale. Pudete ancu truvà opcodes per una mansa di CPU diverse.

Pudete estrattà l'imàgine di u sistema di filesystem per circà i schedarii di password specifichi (passwd, ombra, etc.) è pruvate à rompe l'hash di password. Pudete fà analisi binariu trà dui o più schedari. Pudete fà l'analisi di l'entropia nantu à e dati per circà dati cumpressi o chjave di criptografia codificata. Tuttu chistu senza bisognu di accede à u codice fonte.

In generale, tuttu ciò chì avete bisognu hè quì :)

Cumu funziona binwalk?

A funzione principale di binwalk hè a so scansione di firma. Binwalk pò scansà l'imaghjini di firmware per circà diversi tipi di schedari integrati è sistemi di schedari.

Sapete l'utilità di linea di cumanda 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

squadra filefighja l'intestazione di u schedariu è cerca una firma (numaru magicu) per determinà u tipu di schedariu. Per esempiu, se u schedariu principia cù a sequenza di bytes 0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A, sà chì hè un schedariu PNG. On Wikipedia Ci hè una lista di firme di schedari cumuni.

Binwalk funziona u listessu modu. Ma invece di circà signatures solu à l'iniziu di u schedariu, binwalk scansarà tuttu u schedariu. Inoltre, binwalk pò estrattà i schedari truvati in l'imaghjini.

Ferramenti file и binwalk aduprà a biblioteca libmagic per identificà e firme di file. Ma binwalk supporta in più una lista di firme magiche persunalizate per circà i fugliali compressi / zippati, intestazioni di firmware, kernels Linux, bootloaders, sistemi di fugliale è cusì.

Divertimu un pocu ?

Installazione di binwalk

Binwalk hè supportatu in parechje piattaforme cumprese Linux, OSX, FreeBSD è Windows.

Per installà l'ultima versione di binwalk pudete scaricate u codice fonte è seguitate instructions d'installazione o guida rapida, dispunibule nantu à u situ web di u prugettu.

Binwalk hà parechji parametri diffirenti:

$ 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

Scanning di l'imaghjini

Cuminciamu per circà e firme di u schedariu in l'imaghjini (imagine da u situ TP-Link).

Esecuzione di binwalk cù u paràmetru --signature:

$ 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

Avà avemu assai infurmazione nantu à sta imagine.

Usi di l'imagine Sottumarinu cum'è un bootloader (intestazione di l'imagine at 0x5AC0 è una maghjina di bootloader compressa à 0x5B00). Basatu nantu à l'intestazione uImage à 0x13270, sapemu chì l'architettura di u processatore hè MIPS è u kernel Linux hè a versione 3.3.8. È basatu annantu à l'imaghjini truvati à l'indirizzu 0x11CEA5, pudemu vede chì rootfs hè un sistema di schedari squashfs.

Avà estrattemu u bootloader (U-Boot) cù u cumandimu 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

Siccomu l'imaghjini hè cumpressu cù LZMA, avemu bisognu di decompressa:

$ unlzma u-boot.bin.lzma

Avà avemu una immagine U-Boot:

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

Cumu truvà u valore predeterminatu per 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

Variabile d'ambiente U-Boot bootargs utilizatu per passà i parametri à u kernel Linux. È da quì sopra, avemu un megliu capiscenu di a memoria flash di u dispusitivu.

Chì ne dite di estrazione di l'imaghjini di u kernel Linux?

$ 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

Pudemu verificà chì l'imaghjini hè stata estratta cù successu cù u cumandimu 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

U furmatu di u schedariu uImage hè basicamente una maghjina di u kernel Linux cù un capu supplementu. Sguassemu questu header per uttene l'immagine finale di u kernel 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

L'imaghjina hè cumpressa, allora sbulicemu:

$ unlzma Image.lzma

Avà avemu una maghjina di kernel Linux:

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

Chì pudemu fà cù l'imaghjini di u kernel? Puderemu, per esempiu, fà una ricerca di stringa in l'imaghjini è truvà a versione di u kernel Linux è amparà nantu à l'ambiente utilizatu per custruisce u 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

Ancu s'è u firmware hè statu liberatu l'annu passatu (2019), cum'è scrivu stu articulu, usa una versione antica di u kernel Linux (3.3.8) liberata in 2012, cumpilata cù una versione assai antica di GCC (4.6) ancu da 2012. !
(circa trad., avete sempre fiducia in i vostri routers in l'uffiziu è in casa?)

Cù opzione --opcodes Pudemu ancu aduprà binwalk per circà l'istruzzioni di a macchina è determinà l'architettura di processore di l'imaghjini:

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

Chì ci hè di u sistema di fugliale radicali? Invece di estrae l'imaghjini manualmente, usemu l'opzione binwalk --extract:

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

U sistema di schedarii radicali cumpletu serà estratto à un 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)
 ---------------------------------------------------------------

Avà pudemu fà assai cose diverse.

Pudemu cercà i schedarii di cunfigurazione, password hash, chjavi criptografichi è certificati digitale. Pudemu analizà i schedarii binari per risolve i prublemi e vulnerabilità.

Cù l'aiutu di Quale hè и chroot pudemu ancu eseguisce (emulate) un eseguibile da l'imaghjini:

$ 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

Perfettu! Ma per piacè nutate chì a versione di BusyBox hè 1.19.4. Questa hè una versione assai antica di BusyBox, publicatu in aprile 2012.

Allora TP-Link libera una maghjina di firmware in 2019 utilizendu software (GCC toolchain, kernel, BusyBox, etc.) da 2012!

Avà capite perchè aghju sempre installatu OpenWRT in i mo routers?

Ùn hè micca tuttu

Binwalk pò ancu fà analisi di entropia, stampà dati di entropia cruda è generà grafici di entropia. Di genere, l'entropia più grande hè osservata quandu i bytes in l'imaghjini sò casuali. Questu puderia significà chì l'imaghjini cuntene un schedariu criptatu, cumpressu o offuscatu. Chjave di crittografia hardcore? Perchè nò.

Ingegneria inversa di un router di casa cù binwalk. Avete fiducia in u software di u vostru router?

Pudemu ancu aduprà u paràmetru --raw per truvà una sequenza di byte cruda persunalizata in una maghjina o paràmetru --hexdump per fà un dump hex paragunendu dui o più file di input.

Firme persunalizate pò esse aghjuntu à binwalk sia attraversu un schedariu di firma persunalizatu specificatu nantu à a linea di cummanda utilizendu u paràmetru --magic, o aghjunghjendu à u cartulare $ HOME / .config / binwalk / magic.

Pudete truvà più infurmazione nantu à binwalk à documentazione ufficiale.

estensione binwalk

Ci hè API binwalk, implementatu cum'è un modulu Python chì pò esse utilizatu da qualsiasi script Python per realizà programaticamente una scansione binwalk, è l'utilità di linea di cumanda binwalk pò esse quasi cumpletamente duplicata cù solu duie linee di codice Python!

import binwalk
binwalk.scan()

Utilizendu l'API Python pudete ancu creà Plugins Python per cunfigurà è espansione binwalk.

Ci hè ancu plugin IDA è versione cloud Binwalk Pro.

Allora perchè ùn scaricate micca l'imagine di firmware da Internet è pruvate binwalk? Vi prumettu chì vi divertirete assai :)

Source: www.habr.com

Add a comment