reverse-engineeringcontrol-flow-graphradare2

Getting full binary control flow graph from Radare2


I want to get a full control flow graph of a binary (malware) using radare2.
I followed this post from another question on SO. I wanted to ask if instead of ag there is another command that gives the control flow graph of the whole binary and not only the graph of one function.


Solution

  • First of all, make sure to install radare2 from git repository and use the newest version:

    $ git clone https://github.com/radare/radare2.git
    $ cd radare2
    $ ./sys/install.sh
    

    After you've downloaded and installed radare2, open your binary and perform analysis on it using the aaa command:

    $ r2 /bin/ls
     -- We fix bugs while you sleep.
    [0x004049a0]> aaa
    [x] Analyze all flags starting with sym. and entry0 (aa)
    [x] Analyze function calls (aac)
    [x] Analyze len bytes of instructions for references (aar)
    [x] Check for objc references
    [x] Check for vtables
    [x] Type matching analysis for all functions (aaft)
    [x] Propagate noreturn information
    [x] Use -AA or aaaa to perform additional experimental analysis.
    

    Adding ? after almost every command in radare will output the subcommands. For example, you know that the ag command and its subcommands can help you to output the visual graphs so by adding ? to ag you can discover its subcommands:

    [0x00000000]> ag?
    Usage: ag<graphtype><format> [addr]  
    Graph commands:
    | aga[format]             Data references graph
    | agA[format]             Global data references graph
    | agc[format]             Function callgraph
    | agC[format]             Global callgraph
    | agd[format] [fcn addr]  Diff graph
    ... <truncated> ...
    
    Output formats:
    | <blank>                 Ascii art
    | *                       r2 commands
    | d                       Graphviz dot
    | g                       Graph Modelling Language (gml)
    | j                       json ('J' for formatted disassembly)
    | k                       SDB key-value
    | t                       Tiny ascii art
    | v                       Interactive ascii art
    | w [path]                Write to path or display graph image (see graph.gv.format     and graph.web)
    

    You're searching for the agCd command which will output a full call-graph of the program in dot format.

    [0x004049a0]> agCd > output.dot
    

    The dot utility is part of the Graphviz software which can be installed using sudo apt-get install graphviz.
    You can view your output in any offline dot viewer, paste the output into an online Graphviz viewer and even convert the dot file to PNG:

    $ r2 /bin/ls
    [0x004049a0]> aa
    [x] Analyze all flags starting with sym. and entry0 (aa)
    [0x004049a0]> agCd > output.dot
    [0x004049a0]> !!dot -Tpng -o callgraph.png output.dot