-
Notifications
You must be signed in to change notification settings - Fork 2
/
extract.py
408 lines (353 loc) · 15 KB
/
extract.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""Extract all IOCs and their latest last seen timestamp
from all historical versions of rstthreats
"""
import enum
import json
import logging
import multiprocessing
import os
import re
import socket
import subprocess
import unittest
domain_feed_path = f"feeds{os.sep}full{os.sep}random100_ioc_domain_latest.json"
ip_feed_path = f"feeds{os.sep}full{os.sep}random100_ioc_ip_latest.json"
url_feed_path = f"feeds{os.sep}full{os.sep}random100_ioc_url_latest.json"
short_feed_path = f"feeds{os.sep}short{os.sep}*"
os.chdir("rstthreats")
class Task(enum.Enum):
DOMAIN = 1
IP = 2
URL = 3
class CommitHistory:
def get_commit_ids(self, feed_path: str) -> list[str]:
"""Search git repository for all commits where files exist at `feed_path`
Args:
feed_path (str): Path to files to be extracted
Returns:
list[str]: Git commit ids where files at `feed_path` are present
"""
# rev-list results are in reverse-chronological order
res = subprocess.check_output(
[
"git",
"rev-list",
"--all",
"--objects",
"--",
feed_path,
]
)
commit_ids = [
line
for line in res.decode().split("\n")
if line and len(line.split(" ")) == 1
]
return commit_ids
class Random100(CommitHistory):
def extract_ioc_records(self, feed_path: str) -> list[dict]:
"""Extract IOC records from all historical versions of
files at `feed_path`
Args:
commit_ids (list[str]): Git commit ids where files at `feed_path` are present
Returns:
list[dict]: IOC records
"""
commit_ids = self.get_commit_ids(feed_path)
ioc_records: list[dict] = []
for idx, commit_id in enumerate(commit_ids):
try:
commit_data = json.loads(
"[" # NDJSON workaround
+ subprocess.check_output(
[
"git",
"cat-file",
"-p",
f"{commit_id}:{feed_path}",
]
)
.decode()
.replace("} {", "},{") # NDJSON workaround
.replace("\n", "") # NDJSON workaround
.replace("}{", "},{") # NDJSON workaround
+ "]" # NDJSON workaround
)
except Exception as e:
logging.info("Commit %d : ID %s | %s", idx, commit_id, e)
else:
ioc_records += commit_data
return ioc_records
def get_domain_and_last_seen(
self, ioc_records: list[dict]
) -> list[tuple[str, str]]:
"""Search IOC records for all unique domains and their last seen timestamps
sorted by domain name and then by timestamp in ascending order
Args:
ioc_records (list[dict]): IOC records
Returns:
list[tuple[str, str]]: All unique domains and their last seen timestamps
"""
return sorted(
set((h["domain"].strip(), h["lseen"]) for h in ioc_records),
key=lambda x: (x[0], x[1]),
) + [("", "")]
def get_ip_and_last_seen(self, ioc_records: list[dict]) -> list[tuple[str, str]]:
"""Search IOC records for all unique IPs and their last seen timestamps
sorted by IP and then by timestamp in ascending order
Args:
ioc_records (list[dict]): IOC records
Returns:
list[tuple[str, str]]: All unique IPs and their last seen timestamps
"""
return sorted(
set((h["ip"]["v4"].strip(), h["lseen"]) for h in ioc_records),
key=lambda x: (socket.inet_pton(socket.AF_INET, x[0]), x[1]),
) + [("", "")]
def get_url_and_last_seen(self, ioc_records: list[dict]) -> list[tuple[str, str]]:
"""Search IOC records for all unique URLs and their last seen timestamps
sorted by URL and then by timestamp in ascending order
Args:
ioc_records (list[dict]): IOC records
Returns:
list[tuple[str, str]]: All unique URLs and their last seen timestamps
"""
return sorted(
set((h["url"].strip(), h["lseen"]) for h in ioc_records),
key=lambda x: (x[0], x[1]),
) + [("", "")]
def drop_duplicates(self, ioc_and_last_seen: list[tuple[str, str]]) -> list[str]:
"""For each ioc-timestamp pair, drop duplicates except for tuple with latest timestamp,
store result as string of format "{ioc} # {timestamp}"
Args:
ioc_and_last_seen (list[tuple[str, str]]): All unique iocs and their last seen timestamps
Returns:
list[str]: Each unique ioc and its latest last seen timestamp in format "{ioc} # {timestamp}"
"""
ioc_and_latest_last_seen: list[str] = []
current = None
for i, entry in enumerate(ioc_and_last_seen):
if current is not None and current[0] != entry[0]:
ioc_and_latest_last_seen.append(f"{current[0]} # {current[1]}")
current = entry
return ioc_and_latest_last_seen
def write_random100_list(self, task: Task):
"""Writes consolidated random100 lists to text files
Args:
task (Task): IOC type
"""
if task is Task.DOMAIN:
domain_ioc_records = self.extract_ioc_records(domain_feed_path)
domain_and_last_seen = self.get_domain_and_last_seen(domain_ioc_records)
domain_and_latest_last_seen = self.drop_duplicates(domain_and_last_seen)
if domain_and_latest_last_seen:
with open(f"..{os.sep}random100_ioc_domain_latest_all.txt", "w") as f:
f.write("\n".join(domain_and_latest_last_seen))
if task is Task.IP:
ip_ioc_records = self.extract_ioc_records(ip_feed_path)
ip_and_last_seen = self.get_ip_and_last_seen(ip_ioc_records)
ip_and_latest_last_seen = self.drop_duplicates(ip_and_last_seen)
if ip_and_latest_last_seen:
with open(f"..{os.sep}random100_ioc_ip_latest_all.txt", "w") as f:
f.write("\n".join(ip_and_latest_last_seen))
if task is Task.URL:
url_ioc_records = self.extract_ioc_records(url_feed_path)
url_and_last_seen = self.get_url_and_last_seen(url_ioc_records)
url_and_latest_last_seen = self.drop_duplicates(url_and_last_seen)
if url_and_latest_last_seen:
with open(f"..{os.sep}random100_ioc_url_latest_all.txt", "w") as f:
f.write("\n".join(url_and_latest_last_seen))
class TestRandom100(unittest.TestCase):
def setUp(self):
self.random100 = Random100()
self.ioc_record_sample_size = 500
self.domain_ioc_records = self.random100.extract_ioc_records(domain_feed_path)[
: self.ioc_record_sample_size
]
self.ip_ioc_records = self.random100.extract_ioc_records(ip_feed_path)[
: self.ioc_record_sample_size
]
self.url_ioc_records = self.random100.extract_ioc_records(url_feed_path)[
: self.ioc_record_sample_size
]
def test_extract_ioc_records(self):
self.assertTrue(len(self.domain_ioc_records) == self.ioc_record_sample_size)
self.assertTrue(len(self.ip_ioc_records) == self.ioc_record_sample_size)
self.assertTrue(len(self.url_ioc_records) == self.ioc_record_sample_size)
def test_get_ioc_and_last_seen(self):
self.domain_and_last_seen = self.random100.get_domain_and_last_seen(
self.domain_ioc_records
)
self.ip_and_last_seen = self.random100.get_ip_and_last_seen(self.ip_ioc_records)
self.url_and_last_seen = self.random100.get_url_and_last_seen(
self.url_ioc_records
)
self.assertTrue(
len(self.domain_and_last_seen) == self.ioc_record_sample_size + 1
)
self.assertTrue(len(self.ip_and_last_seen) == self.ioc_record_sample_size + 1)
self.assertTrue(len(self.url_and_last_seen) == self.ioc_record_sample_size + 1)
def test_drop_duplicates(self):
self.assertTrue(len(self.random100.drop_duplicates([("", "")])) == 0)
self.assertTrue(
len(self.random100.drop_duplicates([("example.com", "1"), ("", "")])) == 1
)
self.assertTrue(
len(
self.random100.drop_duplicates(
[("example.com", "1"), ("example.com", "2"), ("", "")]
)
)
== 1
)
self.assertTrue(
len(
self.random100.drop_duplicates(
[
("example.com", "1"),
("example.com", "2"),
("example.org", "1"),
("", ""),
]
)
)
== 2
)
self.assertTrue(
len(
self.random100.drop_duplicates(
[("example.com", "1"), ("example.org", "1"), ("", "")]
)
)
== 2
)
self.assertTrue(
len(
self.random100.drop_duplicates(
[
("example.com", "1"),
("example.org", "1"),
("example.org", "2"),
("", ""),
]
)
)
== 2
)
class Short(CommitHistory):
def extract_short_ioc_records(self, feed_path: str) -> dict[Task, dict]:
"""Extract IOC records from all historical versions of
files at `feed_path` and categorises them by type `Task`
Args:
feed_path (str): Path to files to be extracted
Returns:
dict[Task, dict]: IOCs categorised by type `Task`
"""
commit_ids = self.get_commit_ids(feed_path)
domain_records: dict = dict()
ip_records: dict = dict()
url_records: dict = dict()
for idx, commit_id in enumerate(commit_ids):
files_in_commit = subprocess.check_output(
["git", "show", commit_id, "--name-only"]
)
json_feed_paths_in_commit = [
line
for line in files_in_commit.decode().split("\n")
if line and re.match(f"^feeds{os.sep}short{os.sep}.*json$", line)
]
for json_feed_path in json_feed_paths_in_commit:
if "ioc_hash" in json_feed_path:
continue
try:
commit_data = json.loads(
"[" # NDJSON workaround
+ subprocess.check_output(
[
"git",
"cat-file",
"-p",
f"{commit_id}:{json_feed_path}",
],
stderr=subprocess.DEVNULL,
)
.decode()
.replace("}\n{", "},\n{") # NDJSON workaround
+ "]" # NDJSON workaround
)
except Exception as e:
logging.info("Commit %d : ID %s | %s", idx, commit_id, e)
else:
# duplicate records are always older as `git rev-list is in reverse chronological order`
if "ioc_domain" in json_feed_path:
for entry in commit_data:
if entry["domain"] not in domain_records:
domain_records[entry["domain"]] = entry["collect"]
if "ioc_ip" in json_feed_path:
for entry in commit_data:
if entry["ip"]["v4"] not in ip_records:
ip_records[entry["ip"]["v4"]] = entry["collect"]
if "ioc_url" in json_feed_path:
for entry in commit_data:
if entry["url"] not in url_records:
url_records[entry["url"]] = entry["collect"]
return {Task.DOMAIN: domain_records, Task.IP: ip_records, Task.URL: url_records}
def write_short_lists(self):
"""Writes consolidated short lists to text files"""
records = self.extract_short_ioc_records(short_feed_path)
domain_records = records[Task.DOMAIN]
ip_records = records[Task.IP]
url_records = records[Task.URL]
domain_and_latest_last_seen = [
f"{s[0]} # {s[1]}"
for s in sorted(domain_records.items(), key=lambda x: x[0])
]
if domain_and_latest_last_seen:
with open(f"..{os.sep}ioc_domain_short_all.txt", "w") as f:
f.write("\n".join(domain_and_latest_last_seen))
ip_and_latest_last_seen = [
f"{s[0]} # {s[1]}"
for s in sorted(
ip_records.items(), key=lambda x: socket.inet_pton(socket.AF_INET, x[0])
)
]
if ip_and_latest_last_seen:
with open(f"..{os.sep}ioc_ip_short_all.txt", "w") as f:
f.write("\n".join(ip_and_latest_last_seen))
url_and_latest_last_seen = [
f"{s[0]} # {s[1]}" for s in sorted(url_records.items(), key=lambda x: x[0])
]
if url_and_latest_last_seen:
with open(f"..{os.sep}ioc_url_short_all.txt", "w") as f:
f.write("\n".join(url_and_latest_last_seen))
class TestShort(unittest.TestCase):
def setUp(self):
self.short = Short()
sample_short_domain_feed_path = (
f"feeds{os.sep}short{os.sep}ioc_domain_20230208_short.json"
)
sample_short_ip_feed_path = (
f"feeds{os.sep}short{os.sep}ioc_ip_20230208_short.json"
)
sample_short_url_feed_path = (
f"feeds{os.sep}short{os.sep}ioc_url_20230208_short.json"
)
self.short_domain_ioc_records = self.short.extract_short_ioc_records(
sample_short_domain_feed_path
)
self.short_ip_ioc_records = self.short.extract_short_ioc_records(
sample_short_ip_feed_path
)
self.short_url_ioc_records = self.short.extract_short_ioc_records(
sample_short_url_feed_path
)
def test_extract_short_ioc_records(self):
self.assertTrue(len(self.short_domain_ioc_records[Task.DOMAIN]))
self.assertTrue(len(self.short_ip_ioc_records[Task.IP]))
self.assertTrue(len(self.short_url_ioc_records[Task.URL]))
if __name__ == "__main__":
with multiprocessing.get_context("fork").Pool(None) as p:
random100 = Random100()
p.map(random100.write_random100_list, [Task.DOMAIN, Task.IP, Task.URL])
short = Short()
short.write_short_lists()