forked from joesecurity/jbxapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jbxapi.py
1701 lines (1388 loc) · 67 KB
/
jbxapi.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# License: MIT
# Copyright Joe Security 2023
"""
jbxapi.py serves two purposes.
(1) a light wrapper around the REST API of Joe Sandbox
(2) a command line script to interact with Joe Sandbox
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import os
import sys
import io
import json
import copy
import argparse
import time
import itertools
import random
import errno
import shutil
import tempfile
import math
try:
import requests
except ImportError:
print("Please install the Python 'requests' package via pip", file=sys.stderr)
sys.exit(1)
__version__ = "3.22.0"
# API URL.
API_URL = "https://jbxcloud.joesecurity.org/api"
# for on-premise installations, use the following URL:
# API_URL = "http://" + webserveraddress + "/joesandbox/index.php/api"
# APIKEY, to generate goto user settings - API key
API_KEY = ""
# (for Joe Sandbox Cloud only)
# Set to True if you agree to the Terms and Conditions.
# https://jbxcloud.joesecurity.org/resources/termsandconditions.pdf
ACCEPT_TAC = False
# default submission parameters
# when specifying None, the server decides
UnsetBool = object()
submission_defaults = {
# system selection, set to None for automatic selection
# 'systems': ('w7', 'w7x64'),
'systems': None,
# comment for an analysis
'comments': None,
# maximum analysis time
'analysis-time': None,
# password for decrypting documents like MS Office and PDFs
'document-password': None,
# This password will be used to decrypt archives (zip, 7z, rar etc.). Default password is "infected".
'archive-password': None,
# Will start the sample with the given command-line argument. Currently only available for Windows analyzers.
'command-line-argument': None,
# country for routing internet through
'localized-internet-country': None,
# tags
'tags': None,
# enable internet access during analysis
'internet-access': UnsetBool,
# enable internet simulation during analysis
'internet-simulation': UnsetBool,
# lookup samples in the report cache
'report-cache': UnsetBool,
# hybrid code analysis
'hybrid-code-analysis': UnsetBool,
# hybrid decompilation
'hybrid-decompilation': UnsetBool,
# inspect ssl traffic
'ssl-inspection': UnsetBool,
# instrumentation of vba scripts
'vba-instrumentation': UnsetBool,
# instrumentation of javascript
'js-instrumentation': UnsetBool,
# traces Java JAR files
'java-jar-tracing': UnsetBool,
# traces .Net files
'dotnet-tracing': UnsetBool,
# send an e-mail upon completion of the analysis
'email-notification': UnsetBool,
# starts the Sample with normal user privileges
'start-as-normal-user': UnsetBool,
# Set the system date for the analysis. Format is YYYY-MM-DD
'system-date': None,
# changes the locale, location, and keyboard layout of the analysis machine
'language-and-locale': None,
# Do not unpack archive files (zip, 7zip etc).
'archive-no-unpack': UnsetBool,
# Enable Hypervisor based Inspection
"hypervisor-based-inspection": UnsetBool,
# select fast mode for a faster but less thorough analysis
'fast-mode': UnsetBool,
# Enables secondary Results such as Yara rule generation, classification via Joe Sandbox Class as well as several detail reports.
# Analysis will run faster if secondary results are not enabled.
'secondary-results': UnsetBool,
# Perform APK DEX code instrumentation. Only applies to Android analyzer. Default true.
'apk-instrumentation': UnsetBool,
# Perform AMSI unpacking. Only applies to Windows. Default true
'amsi-unpacking': UnsetBool,
# Enables Powershell Logging. Only applies to Windows analyzer. Default false
'powershell-logging': UnsetBool,
# Disable automatically chained runs. Chained runs use additional techniques based on the final run's results, e.g. run without instrumentation, or run on bare metal. Default false
'disable-chained-runs': UnsetBool,
# Use live interaction. Requires user interaction via the web UI. Default false
'live-interaction': UnsetBool,
# Accepting the live interaction policy. Required when using live interaction. Default false
'accept-live-interaction-policy': UnsetBool,
# encryption password for analyses
'encrypt-with-password': None,
# choose the browser for URL analyses
'browser': None,
## JOE SANDBOX CLOUD EXCLUSIVE PARAMETERS
# lookup the reputation of URLs and domains (Requires sending URLs third-party services.)
'url-reputation': UnsetBool,
# Delete the analysis after X days
'delete-after-days': None,
## ON PREMISE EXCLUSIVE PARAMETERS
# priority of submissions
'priority': None,
## DEPRECATED PARAMETERS
'office-files-password': None,
'anti-evasion-date': UnsetBool,
'remote-assistance': UnsetBool,
'remote-assistance-view-only': UnsetBool,
'static-only': UnsetBool,
'export-to-jbxview': UnsetBool,
}
class JoeSandbox(object):
def __init__(self, apikey=None, apiurl=None, accept_tac=None,
timeout=None, verify_ssl=True, retries=3,
proxies=None, user_agent=None):
"""
Create a JoeSandbox object.
Parameters:
apikey: the api key
apiurl: the api url
accept_tac: Joe Sandbox Cloud requires accepting the Terms and Conditions.
https://jbxcloud.joesecurity.org/resources/termsandconditions.pdf
timeout: Timeout in seconds for accessing the API. Raises a ConnectionError on timeout.
verify_ssl: Enable or disable checking SSL certificates.
retries: Number of times requests should be retried if they timeout.
proxies: Proxy settings, see the requests library for more information:
https://requests.readthedocs.io/en/latest/user/advanced/#proxies
user_agent: The user agent. Use this when you write an integration with Joe Sandbox
so that it is possible to track how often an integration is being used.
"""
if apikey is None:
apikey = os.environ.get("JBX_API_KEY", API_KEY)
if apiurl is None:
apiurl = os.environ.get("JBX_API_URL", API_URL)
if accept_tac is None:
if "JBX_ACCEPT_TAC" in os.environ:
accept_tac = os.environ.get("JBX_ACCEPT_TAC") == "1"
else:
accept_tac = ACCEPT_TAC
self.apikey = apikey
self.apiurl = apiurl.rstrip("/")
self.accept_tac = accept_tac
self.timeout = timeout
self.retries = retries
if user_agent:
user_agent += " (jbxapi.py {})".format(__version__)
else:
user_agent = "jbxapi.py {}".format(__version__)
self.session = requests.Session()
self.session.verify = verify_ssl
self.session.proxies = proxies
self.session.headers.update({"User-Agent": user_agent})
def analysis_list(self):
"""
Fetch a list of all analyses.
Consider using `analysis_list_paged` instead.
"""
return list(self.analysis_list_paged())
def analysis_list_paged(self):
"""
Fetch all analyses. Returns an iterator.
The returned iterator can throw an exception anytime `next()` is called on it.
"""
pagination_next = None
while True:
response = self._post(self.apiurl + '/v2/analysis/list', data={
"apikey": self.apikey,
"pagination": "1",
"pagination_next": pagination_next,
})
data = self._raise_or_extract(response)
for item in data:
yield item
try:
pagination_next = response.json()["pagination"]["next"]
except KeyError:
break
def submit_sample(self, sample, cookbook=None, params={},
_extra_params={}, _chunked_upload=True):
"""
Submit a sample and returns the submission id.
Parameters:
sample: The sample to submit. Needs to be a file-like object or a tuple in
the shape (filename, file-like object).
cookbook: Uploads a cookbook together with the sample. Needs to be a file-like object or a
tuple in the shape (filename, file-like object)
params: Customize the sandbox parameters. They are described in more detail
in the default submission parameters.
Example:
import jbxapi
joe = jbxapi.JoeSandbox(user_agent="My Integration")
with open("sample.exe", "rb") as f:
joe.submit_sample(f, params={"systems": ["w7"]})
Example:
import io, jbxapi
joe = jbxapi.JoeSandbox(user_agent="My Integration")
cookbook = io.BytesIO(b"cookbook content")
with open("sample.exe", "rb") as f:
joe.submit_sample(f, cookbook=cookbook)
"""
params = copy.copy(params)
files = {}
self._check_user_parameters(params)
if cookbook:
files['cookbook'] = cookbook
# extract sample name
if isinstance(sample, (tuple, list)):
filename, sample = sample
else: # sample is file-like object
filename = requests.utils.guess_filename(sample) or "sample"
retry_with_regular_upload = False
if _chunked_upload:
orig_pos = sample.tell()
params["chunked-sample"] = filename
try:
response = self._submit(params, files, _extra_params=_extra_params)
self._chunked_upload('/v2/submission/chunked-sample', sample, {
"apikey": self.apikey,
"submission_id": response["submission_id"],
})
except InvalidParameterError as e:
# re-raise if the error is not due to unsupported chunked upload
if "chunked-sample" not in e.message:
raise
retry_with_regular_upload = True
except _ChunkedUploadNotPossible as e:
retry_with_regular_upload = True
if retry_with_regular_upload:
del params["chunked-sample"]
sample.seek(orig_pos)
if not _chunked_upload or retry_with_regular_upload:
files["sample"] = (filename, sample)
response = self._submit(params, files, _extra_params=_extra_params)
return response
def submit_sample_url(self, url, params={}, _extra_params={}):
"""
Submit a sample at a given URL for analysis.
"""
self._check_user_parameters(params)
params = copy.copy(params)
params['sample-url'] = url
return self._submit(params, _extra_params=_extra_params)
def submit_url(self, url, params={}, _extra_params={}):
"""
Submit a website for analysis.
"""
self._check_user_parameters(params)
params = copy.copy(params)
params['url'] = url
return self._submit(params, _extra_params=_extra_params)
def submit_command_line(self, command_line, params={}, _extra_params={}):
"""
Submit a commandline for analysis.
"""
self._check_user_parameters(params)
params = copy.copy(params)
params['command-line'] = command_line
return self._submit(params, _extra_params=_extra_params)
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
"""
Submit a cookbook.
"""
self._check_user_parameters(params)
files = {'cookbook': cookbook}
return self._submit(params, files, _extra_params=_extra_params)
def _prepare_params_for_submission(self, params):
params['apikey'] = self.apikey
params['accept-tac'] = "1" if self.accept_tac else "0"
# rename array parameters
params['systems[]'] = params.pop('systems', None)
params['tags[]'] = params.pop('tags', None)
# rename aliases
if 'document-password' in params:
params['office-files-password'] = params.pop('document-password')
# submit booleans as "0" and "1"
for key, value in list(params.items()):
try:
default = submission_defaults[key]
except KeyError:
continue
if default is UnsetBool or isinstance(default, bool):
params[key] = _to_bool(value, default)
return params
def _submit(self, params, files=None, _extra_params={}):
data = copy.copy(submission_defaults)
data.update(params)
data = self._prepare_params_for_submission(data)
data.update(_extra_params)
response = self._post(self.apiurl + '/v2/submission/new', data=data, files=files)
return self._raise_or_extract(response)
def _chunked_upload(self, url, f, params):
try:
file_size = self._file_size(f)
except (IOError, OSError):
raise _ChunkedUploadNotPossible("The file does not support chunked upload.")
chunk_size = 10 * 1024 * 1024
chunk_count = int(math.ceil(file_size / chunk_size))
params = copy.copy(params)
params.update({
"file-size": file_size,
"chunk-size": chunk_size,
"chunk-count": chunk_count,
})
chunk_index = 1
sent_size = 0
response = None
while sent_size < file_size:
# collect next chunk
chunk_data = io.BytesIO()
chunk_data_len = 0
while chunk_data_len < chunk_size:
read_data = f.read(chunk_size - chunk_data_len)
if read_data is None:
raise _ChunkedUploadNotPossible("Non-blocking files are not supported.")
if len(read_data) <= 0:
break
chunk_data.write(read_data)
chunk_data_len += len(read_data)
params["current-chunk-index"] = chunk_index
params["current-chunk-size"] = chunk_data_len
chunk_index += 1
chunk_data.seek(0)
response = self._post(self.apiurl + url, data=params, files={"chunk": chunk_data})
self._raise_or_extract(response) # raise Exception if the response is negative
sent_size += chunk_data_len
return response
def _file_size(self, f):
"""
Tries to find the size of the file-like object 'f'.
If the file-pointer is advanced (f.tell()) it subtracts this.
Raises ValueError if it fails to do so.
"""
pos = f.tell()
f.seek(0, os.SEEK_END)
end_pos = f.tell()
f.seek(pos, os.SEEK_SET)
return end_pos - pos
def submission_list(self, **kwargs):
"""
Fetch all submissions. Returns an iterator.
You can give the named parameter `include_shared`.
The returned iterator can throw an exception every time `next()` is called on it.
"""
include_shared = kwargs.get("include_shared", None)
pagination_next = None
while True:
response = self._post(self.apiurl + '/v2/submission/list', data={
"apikey": self.apikey,
"pagination_next": pagination_next,
"include-shared": _to_bool(include_shared),
})
data = self._raise_or_extract(response)
for item in data:
yield item
try:
pagination_next = response.json()["pagination"]["next"]
except KeyError:
break
def submission_info(self, submission_id):
"""
Returns information about a submission including all the analysis ids.
"""
response = self._post(self.apiurl + '/v2/submission/info', data={'apikey': self.apikey, 'submission_id': submission_id})
return self._raise_or_extract(response)
def submission_delete(self, submission_id):
"""
Delete a submission.
"""
response = self._post(self.apiurl + '/v2/submission/delete', data={'apikey': self.apikey, 'submission_id': submission_id})
return self._raise_or_extract(response)
def server_online(self):
"""
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
"""
response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey})
return self._raise_or_extract(response)
def analysis_info(self, webid):
"""
Show the status and most important attributes of an analysis.
"""
response = self._post(self.apiurl + "/v2/analysis/info", data={'apikey': self.apikey, 'webid': webid})
return self._raise_or_extract(response)
def analysis_delete(self, webid):
"""
Delete an analysis.
"""
response = self._post(self.apiurl + "/v2/analysis/delete", data={'apikey': self.apikey, 'webid': webid})
return self._raise_or_extract(response)
def analysis_download(self, webid, type, run=None, file=None, password=None):
"""
Download a resource for an analysis. E.g. the full report, binaries, screenshots.
The full list of resources can be found in our API documentation.
When `file` is given, the return value is the filename specified by the server,
otherwise it's a tuple of (filename, bytes).
Parameters:
webid: the webid of the analysis
type: the report type, e.g. 'html', 'bins'
run: specify the run. If it is None, let Joe Sandbox pick one
file: a writable file-like object (When omitted, the method returns
the data as a bytes object.)
password: a password for decrypting a resource (see the
encrypt-with-password submission option)
Example:
name, json_report = joe.analysis_download(123456, 'jsonfixed')
Example:
with open("full_report.html", "wb") as f:
name = joe.analysis_download(123456, "html", file=f)
"""
# when no file is specified, we create our own
if file is None:
_file = io.BytesIO()
else:
_file = file
# password-encrypted resources have to be stored in a temp file first
if password:
_decrypted_file = _file
_file = tempfile.TemporaryFile()
data = {
'apikey': self.apikey,
'webid': webid,
'type': type,
'run': run,
}
response = self._post(self.apiurl + "/v2/analysis/download", data=data, stream=True)
try:
filename = response.headers["Content-Disposition"].split("filename=")[1][1:-2]
except Exception as e:
filename = type
# do standard error handling when encountering an error (i.e. throw an exception)
if not response.ok:
self._raise_or_extract(response)
raise RuntimeError("Unreachable because statement above should raise.")
try:
for chunk in response.iter_content(1024):
_file.write(chunk)
except requests.exceptions.RequestException as e:
raise ConnectionError(e)
# decrypt temporary file
if password:
_file.seek(0)
self._decrypt(_file, _decrypted_file, password)
_file.close()
_file = _decrypted_file
# no user file means we return the content
if file is None:
return (filename, _file.getvalue())
else:
return filename
def analysis_search(self, query):
"""
Lists the webids of the analyses that match the given query.
Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id.
"""
response = self._post(self.apiurl + "/v2/analysis/search", data={'apikey': self.apikey, 'q': query})
return self._raise_or_extract(response)
def server_systems(self):
"""
Retrieve a list of available systems.
"""
response = self._post(self.apiurl + "/v2/server/systems", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def account_info(self):
"""
Only available on Joe Sandbox Cloud
Show information about the account.
"""
response = self._post(self.apiurl + "/v2/account/info", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def server_info(self):
"""
Query information about the server.
"""
response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def server_lia_countries(self):
"""
Show the available localized internet anonymization countries.
"""
response = self._post(self.apiurl + "/v2/server/lia_countries", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def server_languages_and_locales(self):
"""
Show the available languages and locales
"""
response = self._post(self.apiurl + "/v2/server/languages_and_locales", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def joelab_machine_info(self, machine):
"""
Show JoeLab Machine info.
"""
response = self._post(self.apiurl + "/v2/joelab/machine/info", data={'apikey': self.apikey,
'machine': machine})
return self._raise_or_extract(response)
def joelab_images_list(self, machine):
"""
List available images.
"""
response = self._post(self.apiurl + "/v2/joelab/images/list", data={'apikey': self.apikey,
'machine': machine})
return self._raise_or_extract(response)
def joelab_images_capture(self, machine, image=None):
"""
Capture disk image of a machine.
"""
response = self._post(self.apiurl + "/v2/joelab/images/capture", data={'apikey': self.apikey,
'machine': machine,
'accept-tac': "1" if self.accept_tac else "0",
'image': image})
return self._raise_or_extract(response)
def joelab_images_reset(self, machine, image=None):
"""
Reset a disk image of a machine.
"""
response = self._post(self.apiurl + "/v2/joelab/images/reset", data={'apikey': self.apikey,
'machine': machine,
'accept-tac': "1" if self.accept_tac else "0",
'image': image})
return self._raise_or_extract(response)
def joelab_filesystem_upload(self, machine, file, path=None, _chunked_upload=True):
"""
Upload a file to a Joe Lab machine.
Parameters:
machine The machine id.
file: The file to upload. Needs to be a file-like object or a tuple in
the shape (filename, file-like object).
"""
data = {
"apikey": self.apikey,
"accept-tac": "1" if self.accept_tac else "0",
"machine": machine,
"path": path,
}
# extract sample name
if isinstance(file, (tuple, list)):
filename, file = file
else: # sample is file-like object
filename = requests.utils.guess_filename(file) or "file"
retry_with_regular_upload = False
if _chunked_upload:
orig_pos = file.tell()
# filename
try:
response = self._chunked_upload('/v2/joelab/filesystem/upload-chunked', file, data)
except (UnknownEndpointError, _ChunkedUploadNotPossible) as e:
retry_with_regular_upload = True
file.seek(orig_pos)
if not _chunked_upload or retry_with_regular_upload:
files = {"file": (filename, file)}
response = self._post(self.apiurl + '/v2/joelab/filesystem/upload', data=data, files=files)
return self._raise_or_extract(response)
def joelab_filesystem_download(self, machine, path, file):
"""
Download a file from a Joe Lab machine.
Parameters:
machine: The machine id.
path: The path of the file on the Joe Lab machine.
file: a writable file-like object
Example:
with open("myfile.zip", "wb") as f:
joe.joelab_filesystem_download("w7_10", "C:\\windows32\\myfile.zip", f)
"""
data = {'apikey': self.apikey,
'machine': machine,
'path': path}
response = self._post(self.apiurl + "/v2/joelab/filesystem/download", data=data, stream=True)
# do standard error handling when encountering an error (i.e. throw an exception)
if not response.ok:
self._raise_or_extract(response)
raise RuntimeError("Unreachable because statement above should raise.")
try:
for chunk in response.iter_content(1024):
file.write(chunk)
except requests.exceptions.RequestException as e:
raise ConnectionError(e)
def joelab_network_info(self, machine):
"""
Show Network info
"""
response = self._post(self.apiurl + "/v2/joelab/network/info", data={'apikey': self.apikey,
'machine': machine})
return self._raise_or_extract(response)
def joelab_network_update(self, machine, settings):
"""
Update the network settings.
"""
params = dict(settings)
params["internet-enabled"] = _to_bool(params["internet-enabled"])
params['apikey'] = self.apikey
params['accept-tac'] = "1" if self.accept_tac else "0"
params['machine'] = machine
response = self._post(self.apiurl + "/v2/joelab/network/update", data=params)
return self._raise_or_extract(response)
def joelab_pcap_start(self, machine):
"""
Start PCAP recording.
"""
params = {
'apikey': self.apikey,
'accept-tac': "1" if self.accept_tac else "0",
'machine': machine,
}
response = self._post(self.apiurl + "/v2/joelab/pcap/start", data=params)
return self._raise_or_extract(response)
def joelab_pcap_stop(self, machine):
"""
Stop PCAP recording.
"""
params = {
'apikey': self.apikey,
'accept-tac': "1" if self.accept_tac else "0",
'machine': machine,
}
response = self._post(self.apiurl + "/v2/joelab/pcap/stop", data=params)
return self._raise_or_extract(response)
def joelab_pcap_download(self, machine, file):
"""
Download the captured PCAP.
Parameters:
machine: The machine id.
file: a writable file-like object
Example:
with open("dump.pcap", "wb") as f:
joe.joelab_pcap_download("w7_10", f)
"""
data = {'apikey': self.apikey,
'machine': machine}
response = self._post(self.apiurl + "/v2/joelab/pcap/download", data=data, stream=True)
# do standard error handling when encountering an error (i.e. throw an exception)
if not response.ok:
self._raise_or_extract(response)
raise RuntimeError("Unreachable because statement above should raise.")
try:
for chunk in response.iter_content(1024):
file.write(chunk)
except requests.exceptions.RequestException as e:
raise ConnectionError(e)
def joelab_list_exitpoints(self):
"""
List the available internet exit points.
"""
response = self._post(self.apiurl + "/v2/joelab/internet-exitpoints/list", data={'apikey': self.apikey})
return self._raise_or_extract(response)
def _decrypt(self, source, target, password):
"""
Decrypt encrypted files downloaded from a Joe Sandbox server.
"""
try:
import pyzipper
except ImportError:
raise NotImplementedError("Decryption requires Python 3 and the pyzipper library.")
try:
with pyzipper.AESZipFile(source) as myzip:
infolist = myzip.infolist()
assert(len(infolist) == 1)
with myzip.open(infolist[0], pwd=password) as zipmember:
shutil.copyfileobj(zipmember, target)
except Exception as e:
raise JoeException(str(e))
def _post(self, url, data=None, **kwargs):
"""
Wrapper around requests.post which
(a) always inserts a timeout
(b) converts errors to ConnectionError
(c) re-tries a few times
"""
# convert file names to ASCII for old urllib versions if necessary
_urllib3_fix_filenames(kwargs)
# try the request a few times
for i in itertools.count(1):
try:
return self.session.post(url, data=data, timeout=self.timeout, **kwargs)
except requests.exceptions.Timeout as e:
# exhausted all retries
if i >= self.retries:
raise ConnectionError(e)
except requests.exceptions.RequestException as e:
raise ConnectionError(e)
# exponential backoff
max_backoff = 4 ** i / 10 # .4, 1.6, 6.4, 25.6, ...
time.sleep(random.uniform(0, max_backoff))
def _check_user_parameters(self, user_parameters):
"""
Verifies that the parameter dict given by the user only contains
known keys. This ensures that the user detects typos faster.
"""
if not user_parameters:
return
# sanity check against typos
for key in user_parameters:
if key not in submission_defaults:
raise ValueError("Unknown parameter {0}".format(key))
def _raise_or_extract(self, response):
"""
Raises an exception if the response indicates an API error.
Otherwise returns the object at the 'data' key of the API response.
"""
try:
data = response.json()
except ValueError:
raise JoeException("The server responded with an unexpected format ({}). Is the API url correct?". format(response.status_code))
try:
if response.ok:
return data['data']
else:
error = data['errors'][0]
raise ApiError(error)
except (KeyError, TypeError):
raise JoeException("Unexpected data ({}). Is the API url correct?". format(response.status_code))
class JoeException(Exception):
pass
class ConnectionError(JoeException):
pass
class _ChunkedUploadNotPossible(JoeException):
pass
class ApiError(JoeException):
def __new__(cls, raw):
# select a more specific subclass if available
if cls is ApiError:
subclasses = {
2: MissingParameterError,
3: InvalidParameterError,
4: InvalidApiKeyError,
5: ServerOfflineError,
6: InternalServerError,
7: PermissionError,
8: UnknownEndpointError,
}
try:
cls = subclasses[raw["code"]]
except KeyError:
pass
return super(ApiError, cls).__new__(cls, raw["message"])
def __init__(self, raw):
super(ApiError, self).__init__(raw["message"])
self.raw = copy.deepcopy(raw)
self.code = raw["code"]
self.message = raw["message"]
class MissingParameterError(ApiError): pass
class InvalidParameterError(ApiError): pass
class InvalidApiKeyError(ApiError): pass
class ServerOfflineError(ApiError): pass
class InternalServerError(ApiError): pass
class PermissionError(ApiError): pass
class UnknownEndpointError(ApiError): pass
def _cli_bytes_from_str(text):
"""
Python 2/3 compatibility function to ensure that what is sent on the command line
is converted into bytes. In Python 2 this is a no-op.
"""
if isinstance(text, bytes):
return text
else:
return text.encode("utf-8", errors="surrogateescape")
def cli(argv):
def print_json(value, file=sys.stdout):
print(json.dumps(value, indent=4, sort_keys=True), file=file)
def analysis_list(joe, args):
print_json(joe.analysis_list())
def submit(joe, args):
params = {name[6:]: value for name, value in vars(args).items()
if name.startswith("param-") and value is not None}
extra_params = {}
for name, value in args.extra_params:
values = extra_params.setdefault(name, [])
values.append(value)
if args.url_mode:
print_json(joe.submit_url(args.sample, params=params, _extra_params=extra_params))
elif args.sample_url_mode:
print_json(joe.submit_sample_url(args.sample, params=params, _extra_params=extra_params))
elif args.command_line_mode:
print_json(joe.submit_command_line(args.sample, params=params, _extra_params=extra_params))
else:
try:
f_cookbook = open(args.cookbook, "rb") if args.cookbook is not None else None
def _submit_file(path):
with open(path, "rb") as f:
print_json(joe.submit_sample(f, params=params, _extra_params=extra_params, cookbook=f_cookbook))
if os.path.isdir(args.sample):
for dirpath, _, filenames in os.walk(args.sample):
for filename in filenames: