Code Monkey home page Code Monkey logo

angr-utils's Introduction

angr-utils

Angr-utils is a collection of utilities for angr binary analysis framework.

Note

Visualisation for various graphs (currently supported: CFG, CG; planned: DFG, CDG, DDG) has been moved to bingraphvis.

The API of the facade functions in visualize.py are considered stable (except marked otherwise in comment), and should not break between releases, although they provide only a limited subset of bingraphvis functionalities.

This tool is not designed to support interactive CFGs. For full interactivity, check out angr-management, for navigable static CFGs check out cfg-explorer.

Main functionality

  • CFG visualisation
  • Pretty printers
  • Utility functions

Install

cd angr-dev
git clone https://github.com/axt/bingraphvis
pip install -e ./bingraphvis
git clone https://github.com/axt/angr-utils
pip install -e ./angr-utils

Usage

See examples for more details.

Plot fancy cfg-s:

import angr
from angrutils import *
proj = angr.Project("<...>/ais3_crackme", load_options={'auto_load_libs':False})
main = proj.loader.main_object.get_symbol("main")
start_state = proj.factory.blank_state(addr=main.rebased_addr)
cfg = proj.analyses.CFGEmulated(fail_fast=True, starts=[main.rebased_addr], initial_state=start_state)
plot_cfg(cfg, "ais3_cfg", asminst=True, remove_imports=True, remove_path_terminator=True)  

cfg

angr-utils's People

Contributors

axt avatar kyle-kyle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angr-utils's Issues

Obtain the graph create by process

Hi,
first of all thanks for the project. I would suggest to make possible for a user to have the graph back. For example, once you call set_output and subsequently process you can store the png generated by the libraries. I would like to not be forces to set the output and maybe just call get_graph and obtain the graph returned by the process function. Is it already possible?

Thanks

Regarding CFG construction

Hi, Here is the source code of the program I am trying to construct a call graph of:

#include <stdio.h>

void A(){}
void B(){}
void C(){A();}
void D(){B();}
void E(int x){
	if ( x>0){ D(); }
	else{ C(); }
}

int main(int argc, char *argv[]){
	FILE *fp;
	fp  = fopen("input.txt","r");
	return 0;
	E(2);
}

Here is the generated CFGFast by angr which is drawn by angr-utils. Shouldn't the rightmost strongly connected component (Function E) should be somehow connected to the ending block of main? Why is that component completely disconnected from the main function graph? Thanks in advance.
a2_dyn_cfg

Getting VEX-IR of a function

I generated CFGs of two representations of the same function (asm and VEX-IR) . So each BB contains the VEX statements and expressions.
I would like to get the whole function at VEX-IR representation. I tried to change the "format" in the following command:
plot_cfg(cfg, output_path, format="plain", asminst=asminst, vexinst=vexinst, func_addr={addr:True}, debug_info=False, remove_imports=True, remove_path_terminator=True)

But still I cannot get the text version of the VEX representation. I am wondering is that possible? Could you please help?
asm-f1

VEX-ir-f1

Thank you!

Getting error while running examples

Hi,

I cloned the repository and try to run the examples. But I am getting this error while runnning.

Traceback (most recent call last):
File "/home/sankara/PycharmProjects/angr-utils/examples/plot_cfg/plot_cfg_example.py", line 21, in
analyze(proj, main.addr, "ais3")
File "/home/sankara/PycharmProjects/angr-utils/examples/plot_cfg/plot_cfg_example.py", line 13, in analyze
plot_cfg(cfg, "%s_%s_cfg" % (name, func.name), asminst=True, vexinst=False, func_addr={addr:True}, debug_info=False, remove_imports=True, remove_path_terminator=True)
File "/home/sankara/PycharmProjects/angr-utils/angrutils/visualize.py", line 31, in plot_cfg
vis.process(cfg.graph)
File "/home/sankara/.local/lib/python2.7/site-packages/bingraphvis/base.py", line 310, in process
return self.output.generate(graph)
File "/home/sankara/.local/lib/python2.7/site-packages/bingraphvis/output.py", line 214, in generate
dotfile.write("{}.{}".format(self.fname, self.format), format=self.format)
File "/home/sankara/.local/lib/python2.7/site-packages/pydot.py", line 1756, in write
s = self.create(prog, format, encoding=encoding)
File "/home/sankara/.local/lib/python2.7/site-packages/pydot.py", line 1867, in create
raise OSError(*args)
OSError: [Errno 2] "dot" not found in path.

I tried to debug but would could not able to fix.

on pydot.py line number 1855

    try:
        p = subprocess.Popen(
            cmdline,
            env=env,
            cwd=tmp_dir,
            shell=False,
            stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    except OSError as e:
        if e.errno == os.errno.ENOENT:
            args = list(e.args)
            args[1] = '"{prog}" not found in path.'.format(
                prog=prog)
            raise OSError(*args)
        else:
            raise

This particular part is throwing, "No such file" error. Could you please guide me?

graph is not getting generated

Traceback (most recent call last):
File "/home/a/.virtualenvs/angr/lib/python3.6/site-packages/pydot.py", line 1926, in create
working_dir=tmp_dir,
File "/home/a/.virtualenvs/angr/lib/python3.6/site-packages/pydot.py", line 139, in call_graphviz
**kwargs
File "/usr/lib/python3.6/subprocess.py", line 729, in init
restore_signals, start_new_session)
File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'dot': 'dot'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "cfg123.py", line 7, in
plot_cfg(cfg, "ais3_cfg", asminst=True, remove_imports=True, remove_path_terminator=True)
File "/home/a/ang-dev/angr-utils/angrutils/visualize.py", line 34, in plot_cfg
vis.process(cfg.graph)
File "/home/a/ang-dev/bingraphvis/bingraphvis/base.py", line 310, in process
return self.output.generate(graph)
File "/home/a/ang-dev/bingraphvis/bingraphvis/output.py", line 217, in generate
dotfile.write("{}.{}".format(self.fname, self.format), format=self.format)
File "/home/a/.virtualenvs/angr/lib/python3.6/site-packages/pydot.py", line 1828, in write
s = self.create(prog, format, encoding=encoding)
File "/home/a/.virtualenvs/angr/lib/python3.6/site-packages/pydot.py", line 1933, in create
raise OSError(*args)
FileNotFoundError: [Errno 2] "dot" not found in path.

How can i solve this problem

I got an error when I was import angr

It gives me this:

Traceback (most recent call last):
File "E:\Document\porgram\科研项目\src\angr_other_learn\angr-utils\examples\myExample\test.py", line 1, in
import angr
File "D:\Program Files\Anaconda3\lib\site-packages\angr_init_.py", line 22, in
from .utils.formatting import setup_terminal
File "D:\Program Files\Anaconda3\lib\site-packages\angr\utils_init_.py", line 5, in
from . import enums_conv
File "D:\Program Files\Anaconda3\lib\site-packages\angr\utils\enums_conv.py", line 6, in
from ..protos.primitives_pb2 import Edge
File "D:\Program Files\Anaconda3\lib\site-packages\angr\protos_init_.py", line 10, in
from . import primitives_pb2
File "D:\Program Files\Anaconda3\lib\site-packages\angr\protos\primitives_pb2.py", line 5, in
from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor' from 'google.protobuf' (unknown location)

here is the sourse code

import angr

it gives me the error in the first line of the code.
I don't know what is going on, and I coudn't find effective solutions on Google. please help me

Save CFG to a file instead of rendering in new window

I'm using angr strictly in a shell environment. I would like to use the plot_cfg function, or something similar, to generate an image (perhaps in a PNG format) on my local file system, instead of rendering the image in a new window (which clearly won't work in a shell environment). Looking through the available arguments I don't see any options for saving the rendered CFG to a file instead of displaying it. Is such a feature available or something that could be incorporated in a future release?

Legend

I love your a fancy graph utility! :)
It would be great to have an option to insert a legend when generating a CFG if necessary.

plot_ CFG cannot draw disassembly code

I ran the sample code, but I didn't get an image of the disassembly code,image as below:
out
parameter "format='raw'" then "dot -Tpng -o out.png ais3_cfg.raw" as same as above.
the "ais3_cfg.raw" file's content as below:
image
The node description of the "ais3_cfg. Raw" file does not seem to contain disassembly content. I don't know whether this is an angr problem or an angr utils problem.
could you give me some help? Thanks

DDG example

Thank you for the visualizations for the CDG.

Can someone please provide a short example for the DDG "plot_ddg_data". It seems that the DDG is overwhelmed with the number of edges when the entire binary file is put into it and no suitable example can be found in the example directory.
I tried to create the CFG just for the main method(that worked), but then no DDG was found.

Thank you in advance!

Add support for html-like labels

To support various kinds of highlighting / annotation, add support for HTML-like labels.

Example

digraph G {
rankdir=TB;
0 [shape=Mrecord, label=<{ 0x80484cd (0x80484cd) main | 
<TABLE BORDER="0" CELLPADDING="0">
    <TR><TD><IMG  SRC="cica.png" SCALE="TRUE"></IMG></TD><TD>0x80484cd&#58;</TD><TD ALIGN="LEFT"><I>push</I></TD><TD ALIGN="LEFT">ebp</TD><TD></TD><TD></TD></TR>
    <TR><TD><FONT COLOR="BLUE">[1]</FONT></TD><TD>0x80484ce&#58;</TD><TD ALIGN="LEFT"><I>mov</I></TD><TD ALIGN="LEFT">ebp, <B>esp</B></TD><TD></TD><TD></TD></TR>
    <TR><TD></TD><TD>0x80484d0&#58;</TD><TD ALIGN="LEFT"><I>and</I></TD><TD ALIGN="LEFT"><B>esp</B>, <FONT COLOR="GREEN">0xfffffff0</FONT></TD><TD><FONT COLOR="grey">; comment</FONT></TD><TD></TD></TR>
</TABLE> }}>, fontsize="8.0", fontname=monospace, penwidth=1];
}

plot_cfg(): Plotted CFG is not readable

Using plot_cfg(), generated PNG for CFG which is not readable at all when call depth is 5 or more.
Code snippet below:

            main = proj.loader.main_object.get_symbol(FUNC_NAME)
            start_state = proj.factory.blank_state(addr=main.rebased_addr)
            if CFG_TYPE == "emulated":
                cfg = proj.analyses.CFGEmulated(fail_fast=True, starts=[main.rebased_addr], initial_state=start_state, resolve_indirect_jumps=False, call_depth=CALL_DEPTH)

Basically when call depth was kept to 5, then it was blurred upon zooming, however, with depth 1 or 3, the plotted graphs were readable.
Screenshot 2020-01-14 at 11 19 10

cfg

vex: priv/main_main.c:769 (LibVEX_Translate): Assertion `0 == sizeof(VexGuestMIPS32State) % LibVEX_GUEST_STATE_ALIGN' failed

Problem creating the graph

Hi @axt,
I'm still trying to fix the problem with the angr-utils and i have a weird behaviour. Using pngpixel,like last time, 'm trying to print a simple graph for png_user_version_check, maybe I'm doing something wrong, but I cannot see the connection between the block ending in 0x5a8 and 0x51d. When you have time can you generate the graph for that function and upload here the result please?

Thanks

AttributeError: 'XRef' object has no attribute 'sort'

python3.9
macOS Monterey 12.1
angr 9.1.11752
angr-utils 0.5.0
bingraphvis 0.3.0

import angr
from angrutils import *


def cfgfastpng(filename):
    proj = angr.Project(filename, auto_load_libs = False)
    cfg = proj.analyses.CFGFast()
    plot_cfg(cfg, "cfg", format='png', asminst=True, remove_imports=True)


if __name__ == '__main__':
    cfgfastpng('./01_angr_avoid')

WARNING | 2022-03-01 19:55:43,281 | angr.analyses.cfg.cfg_fast | _tidy_data_references() sees an address 0x80d6040 that does not belong to any section or segment.
Traceback (most recent call last):
File "/Users/chenyanzhi/Documents/angr/test.py", line 12, in
cfgfastpng('./01_angr_avoid')
File "/Users/chenyanzhi/Documents/angr/test.py", line 8, in cfgfastpng
plot_cfg(cfg, "cfg", format='png', asminst=True, remove_imports=True)
File "/Users/chenyanzhi/Desktop/angr-dev/angr-utils/angrutils/visualize.py", line 34, in plot_cfg
vis.process(cfg.graph)
File "/Users/chenyanzhi/Desktop/angr-dev/bingraphvis/bingraphvis/base.py", line 309, in process
graph = self.pipeline.process(filter=filter)
File "/Users/chenyanzhi/Desktop/angr-dev/bingraphvis/bingraphvis/base.py", line 286, in process
c.render(n)
File "/Users/chenyanzhi/Desktop/angr-dev/bingraphvis/bingraphvis/base.py", line 126, in render
an.annotate_content(n, n.content[self.name])
File "/Users/chenyanzhi/Desktop/angr-dev/bingraphvis/bingraphvis/angr/annotator.py", line 384, in annotate_content
if dr.sort == 'string':
AttributeError: 'XRef' object has no attribute 'sort'

Is there a way to walk a dissasembly graph?

Hello!

I intent to automaticaly analyze CFG graphs of binaries in order to find some properties of packers. The graph generated by simply running CFGFast() is not very easy to analyse as it's only a graph of addresess (as far as I cat tell). Is the a way to get this nice CFG representation in basic blocks, which is generated by plot_cfg(), and walk through it?

Thanks in advance!

[Feature request] Merge graphs

Hi @axt,
i was thinking that would be nice to have the opportunity to merge 2 graphs. When this can be useful? Suppose that a user would prefer to generate a graph of a function in a shared object and generate the graph of function contained in an elf file that uses that shared object. At this point the user could just generate the graph from the shared object only once and after for each occurrence pf that specific function in the elf it could just "merge" the pre-generated graph. Would be this useful?

Thanks

Obtain the graph for SIMP

Hi,
at the moment when I create a png for a graph if an SIMP is encountered the graph does not show all the call done but that SIMP. Is it possible to have the full graph even with the call made by the SIMPs? I think it would be useful in case a user has loaded all the shared object and wants to see whet happens in the SIMP thar could be function in the loaded shared objects

Thanks

can't generate graph

hi
i want use CFGFast generate CFG
my code is:

proj=angr.Project('/opt/png')
cfg = proj.analyses.CFGFast()
plot_cfg(cfg, "mycfg",asminst=True, remove_imports=True, remove_path_terminator=True)

but an error occurred:

"dot" with args ['-Tpng', '/tmp/tmpd9c_cdp3'] returned code: -11

stdout, stderr:
 b''
b''

Traceback (most recent call last):
  File "outputGraph.py", line 135, in <module>
    outputGraph()
  File "outputGraph.py", line 88, in outputGraph
    plot_cfg(cfgs, "static", asminst=True, remove_imports=True, remove_path_terminator=True) #, format='raw')
  File "/opt/angr-utils/angrutils/visualize.py", line 34, in plot_cfg
    vis.process(cfg.graph) 
  File "/opt/bingraphvis/bingraphvis/base.py", line 310, in process
    return self.output.generate(graph)
  File "/opt/bingraphvis/bingraphvis/output.py", line 217, in generate
    dotfile.write("{}.{}".format(self.fname, self.format), format=self.format)
  File "/usr/local/lib/python3.6/site-packages/pydot.py", line 1817, in write
    s = self.create(prog, format, encoding=encoding)
  File "/usr/local/lib/python3.6/site-packages/pydot.py", line 1945, in create
    assert process.returncode == 0, process.returncode
AssertionError: -11

when instead of using the png format as output, add format='raw' (or svg)parameter to plot_cfg, use
dot -Tpng xxx.raw > xxx.png

also an error occurred:
Segmentation fault (core dumped)

can you give me some advice or hints.

thanks

AttributeError: 'NoneType' object has no attribute 'addr'

Hay,

I've just tried to give the examples/plot_cfg example a go but keep receiving the "AttributeError: 'NoneType' object has no attribute 'addr'" error. I've tried a couple of PE32 executables but get the same error with all of them, I'm guessing it's an issue with the fact I'm targeting PE files?

Thanks

No module named 'angrutils'

Hi, guys, your setup.py of angrutils is wrong. The name should be angrutils but you set it to angr-utils which leads to the error ModuleNotFoundError: No module named 'angrutils'.

Are there limitations to plot_cfg()?

I am trying to plot the cfg of notepad.exe as an exercise.
I am using CFGFast and CFGEmulated.

CFGFast()

proj = angr.Project('notepad.exe', load_options={'auto_load_libs': False})
#main = proj.loader.main_object.get_symbol("main") #cant find main, no symbols
cfg = proj.analyses.CFGFast(show_progressbar=True)
len(cfg.functions)
415
len(cfg.graph.nodes())
8086
plot_cfg(cfg, 'test', asminst=True, remove_imports=True, remove_path_terminator=True)
#ends up just hanging here

CFGEmulated()

proj = angr.Project('notepad.exe', load_options={'auto_load_libs': False})
#main = proj.loader.main_object.get_symbol("main") #cant find main, no symbols
cfg = proj.analyses.CFGEmulated(show_progressbar=True)
len(cfg.functions)
365
len(cfg.graph.nodes)
12501
plot_cfg(cfg, 'test', asminst=True, remove_imports=True, remove_path_terminator=True)
#hangs here as well

  1. I could see how producing a PNG of 8k+ nodes would take a long time. I was just wondering if there was anything I was missing or if there is a limit to the size of the binary.

  2. For me, the cfgs are nice to haves, but I'm just trying to get a list of all the possible addresses the program could jump to. With that goal in mind, which analyses would be better suited for finding all the addresses?

Installation problem with virtualenv

Hello, @axt
I installed angr in virtualenv. And I want to install angr-utils in virtualenv too. But when I execute "python setup.py install" in virtualenv :
(angr_env) raphael@ubuntu:~/Desktop/angr-utils-0.3.0$ sudo python setup.py install /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) running install running build running build_py running install_lib running install_egg_info Removing /usr/local/lib/python2.7/dist-packages/angr_utils-0.3.0.egg-info Writing /usr/local/lib/python2.7/dist-packages/angr_utils-0.3.0.egg-info
Ubuntu 17.04, Python 2.7.13

How can I install this in virtualenv?

No module named "expr"

When executing from angrutils import *, the following error occurs:

c:\users\sandbox\.virtualenvs\angr-aoudwqk0\lib\site-packages\angrutils\pp.py in <module>
      4 import claripy
      5 import simuvex
----> 6 from expr import *
      7
      8 def pp(obj, **kwargs):

ModuleNotFoundError: No module named 'expr'

Looking at the other files in the package, it would seem that the line should be changed to from .expr import * as it is a local module

plot_cfg not working

I am not able to plot graphs. Even the example files that you have given are not working.

`/home/siddhu/.virtualenvs/angr/lib/python2.7/site-packages/bingraphvis/angr/factory.pyc in default_cfg_pipeline(self, cfg, asminst, vexinst, remove_path_terminator, color_edges, comments)
19 vis.add_content(AngrAsm(project))
20 if comments:
---> 21 if cfg.sort == 'fast':
22 if project.arch.name in ('X86', 'AMD64'):
23 vis.add_content_annotator(AngrX86CommentsAsm(project))

AttributeError: 'CFGAccurate' object has no attribute 'sort'
`

Need a new Sample?

hi, AXT, I run your sample code with newest angr and got several errors, and I fix it like this:

import angr
from angrutils import *
proj = angr.Project("./test", load_options={'auto_load_libs':False})
main = proj.loader.main_bin.get_symbol("main")
#start_state = proj.factory.blank_state(addr=main.addr)
start_state = proj.factory.entry_state()
#cfg = proj.analyses.CFGFast(fail_fast=True, starts=[main.addr], initial_state=start_state)
cfg = proj.analyses.CFG()
plot_cfg(cfg, "ais3_cfg", asminst=True, remove_imports=True, remove_path_terminator=True)

anyway, your work is great!

Problem with fauxware file

I creat cfg with crackme0x00a file -> success. But error with fauxware file. This is error. Please, help me.
screenshot from 2017-06-09 00-23-39

Multiple duplicated CFG in a graph

I use the latest version (8.19.4.5) of angr to generate a precise CFG with statements listed below.
Then I use angrutils.plot_cfg to plot the graphs, but the output seems wrong, there are multiple duplicated CFG in a graph. So, could you fix it? Thanks!


proj = angr.Project(binary_path, load_options={'auto_load_libs': False})
cfg = proj.analyses.CFGEmulated(context_sensitivity_level=1, fail_fast=True)
for addr,func in cfg.kb.functions.items():
    print(func.name)
    if func.name in ['main','func_0', 'func_1']:
        angrutils.plot_cfg(cfg, "%s_%s_cfg" % ("emul", func.name), asminst=True, vexinst=False, func_addr={addr:True}, debug_info=False, remove_imports=True, remove_path_terminator=True)

Link of a malformed graph:
https://www.dropbox.com/s/xhq8t4pi9esyqwx/emul_func_0_cfg.png?dl=0

how to speed up cfg_path

I am using the cfg_path to collect all the possible path in the CFG for each function. However, it takes forever. Is there any way to speed up? Or another way to obtain all the paths in CFG?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.