-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalwareGraphExtract.py
More file actions
157 lines (137 loc) · 5.51 KB
/
malwareGraphExtract.py
File metadata and controls
157 lines (137 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import r2pipe
import os
import re
import json
import networkx as nx
import numpy as np
import sys
import matplotlib.pyplot as plt
import argparse
from networkx.algorithms import bipartite
import networkx.algorithms.isomorphism as iso
import networkx.algorithms.graph_hashing as graph_hashing
import pandas as pd
np.set_printoptions(threshold=np.inf)
parser = argparse.ArgumentParser(description='Extract Adjacency matrix / graph from PE')
parser.add_argument('file', nargs='*', help="The file to analyze")
parser.add_argument('-e', action='store_true', help="export function to *.gml")
parser.add_argument('-i', help="import gml file to compare with all other function")
p = parser.parse_args()
printFunction = {}
matching_d = {}
iso_l = []
bi_l = []
nodes_l = []
hash_l = []
def allFunction(f):
"""
Print all function from PE
sym : Symbol from symbol table
sub : subroutine, part of a function
fcn : regular function
"""
result = []
x = f.cmdj("aflj")
for i in range(0, int(f.cmd("aflc"))):
data = json.dumps(x[i]['name'])
if ("fcn." in data) or ("entry0" in data) :
result.append(data.replace('"',''))
return result
def ActionBasicBloc(nameFunction, *args):
"""
Print adjacency_matrix of Graph
if args = save, save the graph to png
"""
G = initGraph()
cpt = 0
bb = f.cmd("afb " + nameFunction)
for i in bb.splitlines():
index = i.split(' ')
if cpt == 0:
G.add_node(index[0], color='green', style='filled')
elif cpt == G.number_of_nodes() -1 :
G.add_node(index[0], color='red', style='filled')
else:
G.add_node(index[0])
cpt = cpt + 1
if ("j" in index) and ("f" in index) :
G.add_edges_from([(index[0], index[5]),(index[0],index[7])], weight=1)
elif ("j" in index) or ("f" in index) :
G.add_edge(index[0], index[5], weight=1)
else :
pass
color_d = nx.get_node_attributes(G, 'color')
default_color = 'blue'
color_l = [color_d.get(node, default_color) for node in G.nodes()]
if 'save' in args :
print(nx.to_numpy_matrix(G))
nx.draw(G, node_color=color_l)
plt.savefig(str(p.file) +"_graph_" + str(nameFunction) + ".png")
elif 'print' in args :
printFunction[str(nameFunction)] = str(G.number_of_nodes())
#debug
#if G.number_of_nodes() < 10:
#print(str(nameFunction))
#print(nx.to_numpy_matrix(G))
#[print(nameFunction, n, nbrdict) for n, nbrdict in G.adjacency()]
#print(bipartite.is_bipartite(G))
#print(nx.graph_edit_distance(G1,G2)) #is_isomorphic
elif 'export' in args :
nx.write_gml(G, "_"+ str(nameFunction)+".gml")
elif 'matching' in args :
if p.i :
if os.path.isfile(p.i):
try :
G_up =nx.read_gml(p.i)
if G_up.number_of_nodes() < 10 and G_up.number_of_nodes() == G.number_of_nodes() :
matching_d[str(nameFunction)] = str(nx.graph_edit_distance(G, G_up))
#print("Distance between " + p.i +" and " + str(nameFunction) + " : "+ str(nx.graph_edit_distance(G, G_up)))
nodes_l.append(G.number_of_nodes())
iso_l.append(1) if (nx.is_isomorphic(G, G_up) == True) else iso_l.append(0)
bi_l.append(1) if (bipartite.is_bipartite(G) == True) else bi_l.append(0)
hash_l.append(graph_hashing.weisfeiler_lehman_graph_hash(G))
#print(graph_hashing.weisfeiler_lehman_graph_hash(G_up))
else:
pass
except FileNotFoundError:
print("error opening file")
else:
pass
else:
print(nx.to_numpy_matrix(G))
def initGraph():
return nx.MultiDiGraph()
if __name__=="__main__":
pd.set_option('display.max_rows', None)
print(p.file)
if p.file :
if os.path.isfile(p.file[0]):
try :
f = r2pipe.open(p.file[0])
f.cmd("e asm.bytes = 0")
f.cmd("e scr.utf8 = true")
f.cmd("aaa")
f.cmd("aan") #print alias function like -A
listeDesFonctions = allFunction(f)
print("Number of methods : " + str(len(listeDesFonctions)))
if p.e :
[ActionBasicBloc(fc, "export") for fc in listeDesFonctions]
elif p.i :
[ActionBasicBloc(fc, "matching") for fc in listeDesFonctions]
label = ['Function Name', 'GED']
df = pd.DataFrame(matching_d.items(), columns=label)
df["node"] = pd.Series(nodes_l, dtype='float64')
df["Isomoprhism"] = pd.Series(iso_l, dtype='float64')
df["Bipartite"] = pd.Series(bi_l, dtype='float64')
df["weisfeiler_lehman"] = pd.Series(hash_l)
print(df)
else:
[ActionBasicBloc(fc, "print") for fc in listeDesFonctions]
df = pd.DataFrame(printFunction.items(), columns=['Method','Node'])
print(df[pd.to_numeric(df['Node']) < int(10) ])
except FileNotFoundError:
print("error opening file")
else :
print("file doesn't exist")
else:
parser.print_help()