-
Notifications
You must be signed in to change notification settings - Fork 2
/
scorecards.py
334 lines (279 loc) · 12.6 KB
/
scorecards.py
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Standard Python imports
#
import os
import subprocess
import math
import datetime
# For progress bars
from tqdm import tqdm
# Modules directly associated with this application
#
import scoring
import utility
# TODO: More representative scoring functions
def generate_threat_actor_scorecards(misp_data, directory, start_date, end_date):
"""
Generate a score card for each threat actor
misp_data - The events and attributes loaded from the MISP server
directory - The name of the directory to store the output in
start_date - A datetime object with the earliest date of events to be used when scoring,
use the datetime epoch to ignore the date
end_date - A datetime object with the latest date of events to be used when scoring,
use the datetime epoch to ignore the date
"""
generate_scorecards(misp_data, directory, "threat-actor", "threat actor", start_date, end_date)
def generate_ransomware_scorecards(misp_data, directory, start_date, end_date):
"""
Generate a score card for each ransomware
misp_data - The events and attributes loaded from the MISP server
directory - The name of the directory to store the output in
start_date - A datetime object with the earliest date of events to be used when scoring,
use the datetime epoch to ignore the date
end_date - A datetime object with the latest date of events to be used when scoring,
use the datetime epoch to ignore the date
"""
generate_scorecards(misp_data, directory, "ransomware", "ransomware", start_date, end_date)
def generate_scorecards(misp_data, directory, galaxy_type, entry_description, start_date, end_date):
"""
Generate a score card for each entry (e.g. threat actor or ransomware)
misp_data - The events and attributes loaded from the MISP server
directory - The name of the directory to store the output in
galaxy_type - The type of the galaxy to look at
entry_description - How we refer to the galaxy type in human-readable terms
start_date - A datetime object with the earliest date of events to be used when scoring,
use the datetime epoch to ignore the date
end_date - A datetime object with the latest date of events to be used when scoring,
use the datetime epoch to ignore the date
"""
events = misp_data["events"]
attributes = misp_data["attributes"]
epoch = datetime.datetime.utcfromtimestamp(0)
# Generate dictionary of entries
entries = utility.identify_galaxy_entries(misp_data, galaxy_type, initial={})
# Set up the score characteristics
#
score_descriptions = {
"team_size": "Estimated Organisation Size",
"resource_cost": "Estimated Infrastructure Spend",
"time_cost": "Estimated Time Investment",
"logistical_budget": "Logistical Budget"
};
score_colour = {
"team_size": "orange",
"resource_cost": "red",
"time_cost": "blue",
"logistical_budget": "black"
};
score_units = {
"team_size": "People",
"resource_cost": "$",
"time_cost": "Years",
"logistical_budget": ""
};
score_range = {
"team_size": 500,
"resource_cost": 1000000,
"time_cost": 3,
"logistical_budget": 1000
};
score_type = { # linear or log
"team_size": "log",
"resource_cost": "log",
"time_cost": "log",
"logistical_budget": "log"
};
# Unlike the heatmap scores, which are used for comparative analysis of the threat actors, this
# is a bit more complex in that the scores are intended to be absolutes in specific units.
#
score_multiplier = {
"team_size": 40,
"resource_cost": 50000,
"time_cost": 0.1,
"logistical_budget": 50.0
};
score_fuzz = {
"team_size": 0.25,
"resource_cost": 0.25,
"time_cost": 0.25,
"logistical_budget": 0.05
};
# This will be filled in later, when the palette is constructed
score_palette_offset = {}
# Initialise our accumulators for the number of events relevant to each entry
#
num_events = {}
for entry in entries:
num_events[entry] = 0
# Generate an initial collection of score cards
#
scorecards = {}
for entry in entries:
scorecards[entry] = {
"team_size": 0,
"resource_cost": 0,
"time_cost": 0,
"logistical_budget": 0
};
# Scan the events by entry and timestamp
#
for event in events:
event_id = int(event["id"])
if event_id in attributes:
event_attributes = attributes[event_id]
else:
event_attributes = []
unattributed = "Unattributed"
event_entry = unattributed
if "GalaxyCluster" in event:
galaxycluster = event["GalaxyCluster"]
for galaxy in galaxycluster:
if "Galaxy" in galaxy:
if galaxy["type"] == galaxy_type:
event_entry = galaxy["value"]
if event_entry != unattributed:
if "timestamp" in event:
seconds_since_epoch = int(event["timestamp"])
if seconds_since_epoch > 1:
event_time = datetime.datetime.fromtimestamp(seconds_since_epoch)
reject = False
if start_date != epoch and event_time < start_date:
reject = True
if end_date != epoch and event_time > end_date:
reject = True
if not reject:
scorecards[event_entry]["team_size"] += scoring.score_team_size(event, event_attributes)
scorecards[event_entry]["resource_cost"] += scoring.score_resource_cost(event, event_attributes)
scorecards[event_entry]["time_cost"] += scoring.score_time_cost(event, event_attributes)
scorecards[event_entry]["logistical_budget"] += scoring.score_logistical_budget(event, event_attributes)
num_events[event_entry] += 1
# Now generate our score card as a sumple text output for now
#
if False:
for entry in entries:
print("Score card for " + entry_description + ": " + entry)
print("")
print("Team size: " + str(scorecards[entry]["team_size"]))
print("Resource cost: " + str(scorecards[entry]["resource_cost"]))
print("Time cost: " + str(scorecards[entry]["time_cost"]))
print("Logistical budget: " + str(scorecards[entry]["logistical_budget"]))
print("")
# Generate a chart for each entry
#
if not entries:
print("No entries found")
else:
height = len(entries)
for entry in tqdm(entries):
filename = directory + "/scorecard-" + entry
with open(filename + ".plt", "w") as outfile:
# Set the size of the output image (though note that it will be rotated)
outfile.write("set terminal png size 720, 1280\n")
# Set the filename of the output image
outfile.write("set output \"" + filename + ".tmp.png\"\n")
# Don't draw a key or a colour box
#
outfile.write("unset key\n")
outfile.write("unset colorbox\n")
# Set the bottom (left after rotation) margin so that score names are not truncated
#
outfile.write("set bmargin 15\n")
outfile.write("set tmargin 5\n")
outfile.write("set lmargin 7\n")
outfile.write("set rmargin 3\n")
# Produce multiple graphs side-by-side
outfile.write("set multiplot layout 1, " + str(len(score_descriptions)) + "\n")
# Set the graph style
outfile.write("set style fill solid noborder\n")
# Specify the X-axis parameters
#
outfile.write("set xrange [ 0.0 : 2.0 ]\n")
outfile.write("set boxwidth 1.0\n")
outfile.write("unset xtics\n")
# Add a title to the scorecard
#
title = "Logistical budget for " + entry_description + " " + entry
if start_date != epoch:
title += " starting at " + start_date.strftime("%Y-%m-%d")
if end_date != epoch:
title += " ending at " + end_date.strftime("%Y-%m-%d")
outfile.write("set label 1 \"" + title + "\" offset -3, 10 rotate by 90\n")
# Set the palette for all scores: Gnuplot allows a single palette even in multiplots
#
outfile.write("set palette defined (")
offset = 0.0
numleft = len(scorecards[entry])
for score in scorecards[entry]:
score_palette_offset[score] = offset
outfile.write(str(offset) + " \"grey\", ")
outfile.write(str(offset + (1.0 - 2.0 * score_fuzz[score])) + " \"grey\", ")
outfile.write(str(offset + (1.0 - score_fuzz[score])) + " \"" + score_colour[score] + "\", ")
outfile.write(str(offset + 1.0) + " \"white\"")
offset += 1.0
numleft -= 1
if numleft != 0:
outfile.write(", ")
outfile.write(")\n")
score_palette_max = offset
outfile.write("set cbrange [ 0.0 : " + str(score_palette_max) + "]\n")
# Now write out the data
#
for score in scorecards[entry]:
# Specify the Y-axis parameters
#
outfile.write("set yrange [ 0.0 : " + str(score_range[score]) + " ]\n")
if score_range[score] < 5.0:
outfile.write("set format y \"%1.1f\"\n")
else:
outfile.write("set format y \"%6.0f\"\n")
outfile.write("set ytics " + str(score_range[score] / 10.0) + "\n")
outfile.write("set format y ''\n")
# Set the score description label
outfile.write("set xlabel \"" + score_descriptions[score] + "\" right rotate by 90\n")
# Output the scaled score
#
outfile.write("$" + score + " << EOD\n")
val = scorecards[entry][score]
if score_type[score] == "linear":
pass
elif score_type[score] == "log":
if val != 0:
val = math.log(val)
else:
raise RuntimeError("Unexpected score_type")
val = val * score_multiplier[score]
outfile.write("1 " + str(val / (1.0 - score_fuzz[score])) + "\n")
outfile.write("EOD\n")
# End the data, and plot
#
outfile.write("plot for [i=255:1:-1] \"$" + score + "\" using 1:(($2/256.0)*i):" +
"(" + str(score_palette_offset[score]) + "+(i/256.0)) notitle with boxes fillcolor palette\n")
outfile.write("unset label 1\n")
# Process the plot into a temporary bitmap
#
try:
process = subprocess.Popen(
args=["gnuplot", filename + ".plt"],
stdout=subprocess.PIPE)
output = process.communicate()[0].decode("utf-8")
if len(output) != 0:
print(output)
except Exception as e:
print("Unable to run gnuplot: Is it installed? " + repr(e))
# Rotate the bitmap output
#
try:
process = subprocess.Popen(
args=["convert", "-rotate", "90", filename + ".tmp.png", filename + ".png"],
stdout=subprocess.PIPE)
output = process.communicate()[0].decode("utf-8")
if len(output) != 0:
print(output)
except Exception as e:
print("Unable to run convert: Is ImageMagick installed? " + repr(e))
# Remove the temporary output
os.remove(filename + ".tmp.png");
print("\n\nNumber of events by entity:\n")
for entry in entries:
print(entry + ": " + str(num_events[entry]))