forked from InQuest/sandboxapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfalcon.py
More file actions
270 lines (207 loc) · 8.25 KB
/
Copy pathfalcon.py
File metadata and controls
270 lines (207 loc) · 8.25 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
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
from __future__ import print_function
import sys
import json
import sandboxapi
class FalconAPI(sandboxapi.SandboxAPI):
"""Falcon Sandbox API wrapper"""
def __init__(self, key, url=None, env=100):
"""Initialize the interface to Falcon Sandbox API with key and secret"""
sandboxapi.SandboxAPI.__init__(self)
self.api_url = url or 'https://www.reverse.it/api/v2'
self.key = key
self.env_id = str(env)
def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None):
"""Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps.
"""
if params:
params['environment_id'] = self.env_id
else:
params = {
'environment_id': self.env_id,
}
if headers:
headers['api-key'] = self.key
headers['User-Agent'] = 'Falcon Sandbox'
headers['Accept'] = 'application/json'
else:
headers = {
'api-key': self.key,
'User-Agent': 'Falcon Sandbox',
'Accept': 'application/json',
}
return sandboxapi.SandboxAPI._request(self, uri, method, params, files, headers)
def analyze(self, handle, filename):
"""Submit a file for analysis.
@type handle: File handle
@param handle: Handle to file to upload for analysis.
@type filename: str
@param filename: File name.
@rtype: str
@return: File hash as a string
"""
# multipart post files.
files = {"file" : (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
response = self._request("/submit/file", method='POST', files=files)
try:
if response.status_code == 201:
# good response
return response.json()['job_id']
else:
raise sandboxapi.SandboxError("api error in analyze: {r}".format(r=response.content.decode('utf-8')))
except (ValueError, KeyError) as e:
raise sandboxapi.SandboxError("error in analyze: {e}".format(e=e))
def check(self, item_id):
"""Check if an analysis is complete.
@type item_id: str
@param item_id: Job ID to check.
@rtype: bool
@return: Boolean indicating if a report is done or not.
"""
response = self._request("/report/{job_id}/state".format(job_id=item_id))
if response.status_code in (404, 429):
# unknown job id, api request limit exceeded
return False
try:
content = json.loads(response.content.decode('utf-8'))
status = content['state']
if status == 'SUCCESS' or status == 'ERROR':
return True
except (ValueError, KeyError) as e:
raise sandboxapi.SandboxError(e)
return False
def is_available(self):
"""Determine if the Falcon API server is alive.
@rtype: bool
@return: True if service is available, False otherwise.
"""
# if the availability flag is raised, return True immediately.
# NOTE: subsequent API failures will lower this flag. we do this here
# to ensure we don't keep hitting Falcon with requests while
# availability is there.
if self.server_available:
return True
# otherwise, we have to check with the cloud.
else:
try:
response = self._request("/system/heartbeat")
# we've got falcon.
if response.status_code == 200:
self.server_available = True
return True
except sandboxapi.SandboxError:
pass
self.server_available = False
return False
def queue_size(self):
"""Determine Falcon sandbox queue length
@rtype: str
@return: Details on the queue size.
"""
response = self._request("/system/queue-size")
return response.content.decode('utf-8')
def report(self, item_id, report_format="json"):
"""Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json, html.
@type item_id: str
@param item_id: File ID number
@type report_format: str
@param report_format: Return format
@rtype: dict
@return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
"""
report_format = report_format.lower()
response = self._request("/report/{job_id}/summary".format(job_id=item_id))
if response.status_code == 429:
raise sandboxapi.SandboxError('API rate limit exceeded while fetching report')
# if response is JSON, return it as an object
if report_format == "json":
try:
return json.loads(response.content.decode('utf-8'))
except ValueError:
pass
# otherwise, return the raw content.
return response.content.decode('utf-8')
def full_report(self, item_id, report_format="json"):
"""Retrieves a more detailed report"""
report_format = report_format.lower()
response = self._request("/report/{job_id}/file/{report_format}".format(job_id=item_id, report_format=report_format))
if response.status_code == 429:
raise sandboxapi.SandboxError('API rate limit exceeded while fetching report')
# if response is JSON, return it as an object
if report_format == "json":
try:
return json.loads(response.content.decode('utf-8'))
except ValueError:
pass
# otherwise, return the raw content.
return response.content.decode('utf-8')
def score(self, report):
"""Pass in the report from self.report(), get back an int 0-10."""
try:
threatlevel = int(report['threat_level'])
threatscore = int(report['threat_score'])
except (KeyError, IndexError, ValueError, TypeError) as e:
raise sandboxapi.SandboxError(e)
# from falcon docs:
# threatlevel is the verdict field with values: 0 = no threat, 1 = suspicious, 2 = malicious
# threascore is the "heuristic" confidence value of Falcon Sandbox in the verdict and is a value between 0
# and 100. A value above 75/100 is "pretty sure", a value above 90/100 is "very sure".
# the scoring below converts these values to a scalar. modify as needed.
score = 0
if threatlevel == 2 and threatscore >= 90:
score = 10
elif threatlevel == 2 and threatscore >= 75:
score = 9
elif threatlevel == 2:
score = 8
elif threatlevel == 1 and threatscore >= 90:
score = 7
elif threatlevel == 1 and threatscore >= 75:
score = 6
elif threatlevel == 1:
score = 5
elif threatlevel == 0 and threatscore < 75:
score = 1
return score
if __name__ == "__main__":
def usage():
msg = "%s: <key> <secret> <analyze <fh> | available | queue | report <id>>"
print(msg % sys.argv[0])
sys.exit(1)
if len(sys.argv) == 4:
cmd = sys.argv.pop().lower()
secret = sys.argv.pop().lower()
key = sys.argv.pop().lower()
arg = None
elif len(sys.argv) == 5:
arg = sys.argv.pop()
cmd = sys.argv.pop().lower()
secret = sys.argv.pop().lower()
key = sys.argv.pop().lower()
else:
usage()
# instantiate Falcon Sandbox API interface.
falcon = FalconAPI(key, secret)
# process command line arguments.
if "analyze" in cmd:
if arg is None:
usage()
else:
with open(arg, "rb") as handle:
print(falcon.analyze(handle, arg))
elif "available" in cmd:
print(falcon.is_available())
elif "queue" in cmd:
print(falcon.queue_size())
elif "report" in cmd:
if arg is None:
usage()
else:
print(falcon.report(arg))
else:
usage()