Skip to content

Instantly share code, notes, and snippets.

@gamozolabs
Created October 7, 2019 01:34
Show Gist options
  • Save gamozolabs/d67a35f8e4cbbf254066836efc17d64e to your computer and use it in GitHub Desktop.
Save gamozolabs/d67a35f8e4cbbf254066836efc17d64e to your computer and use it in GitHub Desktop.
from binaryninja import *
import re
NODE_RE = re.compile("NODE (node_[0-9]+)")
INST_RE = re.compile("INST (.*)")
EDGE_RE = re.compile("([A-Z]+) (node_[0-9]+) -> (node_[0-9]+)")
def graph_falkil(binaryview):
# Parse the file
file_contents = open(r"D:\binjagraph.txt", "r").read()
# Dict of all nodes
nodes = {}
# Active node we are working on
cur_node = None
# All edges in the graph
branches = {}
for line in file_contents.splitlines():
node = NODE_RE.match(line)
if node != None:
# Set that this is the node we're currently processing
cur_node = node.group(1)
continue
inst = INST_RE.match(line)
if inst != None:
assert cur_node != None
# Create the entry if it does not exist
if cur_node not in nodes:
nodes[cur_node] = []
# Add this instruction to the node
nodes[cur_node].append(inst.group(1))
continue
edge = EDGE_RE.match(line)
if edge != None:
edge_type = edge.group(1)
edge_from = edge.group(2)
edge_to = edge.group(3)
if edge_type == "TTGT":
branches[(BranchType.TrueBranch, edge_from)] = edge_to
elif edge_type == "FTGT":
branches[(BranchType.FalseBranch, edge_from)] = edge_to
elif edge_type == "BRANCH":
branches[(BranchType.UnconditionalBranch, edge_from)] = edge_to
else:
assert true == false
continue
# Create graph
graph = FlowGraph()
named_nodes = {}
# Add nodes to graph
for node_name, lines in reversed(list(nodes.iteritems())):
node = FlowGraphNode(graph)
node.lines = lines
print(node_name)
named_nodes[node_name] = node
graph.append(node)
# Link edges
for key, edge_to in branches.iteritems():
edge_type, edge_from = key
print("%s %s -> %s" % (edge_type, edge_from, edge_to))
named_nodes[edge_from].add_outgoing_edge(edge_type, named_nodes[edge_to])
show_graph_report("Graphy", graph)
PluginCommand.register(
"FalkIL Graphing", "Graph a FalkIL file", graph_falkil
)
pub fn dump_binja(&self) {
// Get all the edges we have to traverse
let to_explore = self.traverse_bfs(ILLabel(0));
let mut payload = String::new();
for node in to_explore {
payload += &format!("NODE node_{}\n", node.0);
for inst in &self.graph[&node][..] {
payload += &format!("INST {}\n", inst);
match inst {
ILInst::Bcond(_, _, _, ttgt, ftgt) => {
payload += &format!("TTGT node_{} -> node_{}\n", node.0, ttgt.0);
payload += &format!("FTGT node_{} -> node_{}\n", node.0, ftgt.0);
}
ILInst::Branch(tgt) => {
payload += &format!("BRANCH node_{} -> node_{}\n", node.0, tgt.0);
}
_ => {}
}
}
}
std::fs::write(r"/mnt/d/binjagraph.txt", payload.as_bytes()).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment