Skip to content

Commit 2ca4ceb

Browse files
authored
Merge pull request #182 from Pithus/feat/extract_files
Feat/extract files
2 parents 05f6981 + c47476d commit 2ca4ceb

8 files changed

Lines changed: 134 additions & 5 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from django.core.files.storage import default_storage
2+
from tempfile import NamedTemporaryFile, TemporaryDirectory
3+
import zipfile
4+
import binwalkpy
5+
import os
6+
import gc
7+
import logging
8+
from django.conf import settings
9+
from elasticsearch import Elasticsearch
10+
from pathlib import PurePosixPath
11+
12+
13+
es = Elasticsearch(
14+
settings.ELASTICSEARCH_HOSTS,
15+
request_timeout=30, max_retries=5,
16+
retry_on_timeout=True,
17+
basic_auth=(settings.ELASTICSEARCH_USER, settings.ELASTICSEARCH_PASSWORD)
18+
)
19+
20+
21+
def analysis(sha256):
22+
es.update(index=settings.ELASTICSEARCH_TASKS_INDEX, id=sha256, body={'doc': {'extract_files': 1}},
23+
retry_on_conflict=1)
24+
files = []
25+
try:
26+
with NamedTemporaryFile() as f:
27+
f.write(default_storage.open(sha256).read())
28+
f.seek(0)
29+
30+
with TemporaryDirectory() as tmp_dir:
31+
apk = zipfile.ZipFile(f)
32+
33+
file_list = apk.namelist()
34+
for member in file_list:
35+
files.append(member)
36+
apk.extract(member, tmp_dir)
37+
38+
for file in files:
39+
file = os.path.join(tmp_dir, file)
40+
bw = binwalkpy.Binwalk(
41+
target_file_name=file,
42+
output_directory=os.path.join(tmp_dir, "_extracted"),
43+
include=["dex", "elf", "zip"],
44+
full_search=True,
45+
)
46+
extractions = bw.extract_file()
47+
for e in extractions.values():
48+
for fname in os.listdir(e['output_directory']):
49+
fpath = os.path.join(e['output_directory'], fname)
50+
if os.path.isfile(fpath):
51+
print(f"\n\n\n\n\n\n\n{PurePosixPath(e["output_directory"]).name}\n\n\n\n\n\n\n")
52+
with open(fpath, "rb") as f:
53+
default_storage.save(
54+
os.path.join(
55+
sha256,
56+
"extracted",
57+
f"{PurePosixPath(e["output_directory"]).name}_{fname}"
58+
),
59+
f
60+
)
61+
es.update(index=settings.ELASTICSEARCH_TASKS_INDEX, id=sha256, body={'doc': {'extract_files': 2}},
62+
retry_on_conflict=1)
63+
64+
except Exception as e:
65+
logging.exception(e)
66+
es.update(index=settings.ELASTICSEARCH_TASKS_INDEX, id=sha256, body={'doc': {'extract_files': -1}},
67+
retry_on_conflict=1)
68+
69+
del apk, f
70+
gc.collect()
71+
72+
return {'status': 'success', 'info': ''}

‎bazaar/core/tasks.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
similarity,
1818
virus_total,
1919
misp,
20+
extract_files,
2021
)
2122

2223

@@ -36,6 +37,7 @@ def _prepare(sha256):
3637
'quark_analysis': 1,
3738
'misp_analysis': 1,
3839
'mobsf_analysis': 1,
40+
'extract_files': 1,
3941
'analysis_date': timezone.now()
4042
}
4143

@@ -61,6 +63,7 @@ def analyze(sha256, force=False):
6163
async_task(mobsf.analysis, sha256)
6264
async_task(malware_bazaar.analysis, sha256)
6365
async_task(virus_total.analysis, sha256)
66+
async_task(extract_files.analysis, sha256)
6467
async_task(apkid.analysis, sha256)
6568
async_task(similarity.analysis, sha256)
6669
async_task(androcfg.analysis, sha256)

‎bazaar/core/utils.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,12 @@ def compute_status(status):
2424
success = True
2525
analysis_launched = False
2626
error = False
27-
running = len(status.keys()) != 8
27+
running = 0
2828
for k, v in status.items():
2929
if k != 'analysis_date':
3030
success = success and v == 2
3131
error = error or v == -1
32-
running = running or v == 1 or v == 0
32+
running = running or v == 1
3333
if v == 2:
3434
analysis_launched = True # if at least one step succeeded, the analysis was launched
3535
return {

‎bazaar/front/urls.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
download_sample_view, my_rule_edit_view, my_rule_create_view, my_rule_delete_view, og_card_view, \
66
my_retrohunt_view, get_andgrocfg_code, get_genom, basic_url_download_view, report_status_view, instance_status, \
77
remove_bookmark_sample_view, add_bookmark_sample_view, workspace_view, add_comment_view, delete_comment_view, \
8-
notifications_view, notification_delete_view
8+
notifications_view, notification_delete_view, dl_hidden
99

1010
app_name = "front"
1111
urlpatterns = [
@@ -16,6 +16,7 @@
1616
path("report/<str:sha256>/json", view=export_report_view, name="export_report"),
1717
path("report/<str:sha256>/card", view=og_card_view, name="og_card"),
1818
path("report/<str:sha256>/status", view=report_status_view, name="report_status"),
19+
path("report/<str:sha256>/extracted/<str:filename>", view=dl_hidden, name="dl_hidden"),
1920
path("apk/", view=basic_upload_view, name="basic_upload"),
2021
path("apk/<str:sha256>", view=download_sample_view, name="download_sample"),
2122
path("apk/<str:sha256>/bookmark/add", view=add_bookmark_sample_view, name="add_bookmark_sample"),

‎bazaar/front/view.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import logging
23
from collections import Counter
34
from tempfile import NamedTemporaryFile
@@ -7,7 +8,7 @@
78
from django.contrib import messages
89
from django.core.cache import cache
910
from django.core.files.storage import default_storage
10-
from django.http import HttpResponse, JsonResponse, HttpResponseNotAllowed
11+
from django.http import HttpResponse, JsonResponse, HttpResponseNotAllowed, Http404, FileResponse
1112
from django.http.response import HttpResponseBadRequest
1213
from django.shortcuts import redirect, render
1314
from django.utils import timezone
@@ -146,6 +147,12 @@ def get(self, request, *args, **kwargs):
146147
else:
147148
is_bookmarked = False
148149

150+
# Check if binwalk found data to extract
151+
_, extracted_files = default_storage.listdir(os.path.join(sha, "extracted"))
152+
hidden_files = {}
153+
for fname in extracted_files:
154+
hidden_files[fname] = os.path.join(sha, "extracted", fname)
155+
149156
return render(request, 'front/report.html', {
150157
'result': result,
151158
'status': status,
@@ -155,12 +162,28 @@ def get(self, request, *args, **kwargs):
155162
'hunting_matches': hunting_matches,
156163
'similar_samples': similar_samples,
157164
'cache_retention_time': cache_retention_time,
158-
'is_bookmarked': is_bookmarked})
165+
'is_bookmarked': is_bookmarked,
166+
'hidden_files': hidden_files,
167+
})
159168
except Exception as e:
160169
logging.exception(e)
161170
return redirect(reverse_lazy('front:home'))
162171

163172

173+
def dl_hidden(request, sha256, filename):
174+
fpath = os.path.join(sha256, "extracted", filename)
175+
if not default_storage.exists(fpath):
176+
raise Http404("File not found")
177+
178+
file = default_storage.open(fpath, "rb")
179+
180+
return FileResponse(
181+
file,
182+
as_attachment=True,
183+
filename=filename.split("/")[-1],
184+
)
185+
186+
164187
def report_status_view(request, sha256):
165188
try:
166189
report_status = ReportService.get_status(sha256)

‎bazaar/templates/front/report.html‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,18 @@ <h3>Browsable activities</h3>
264264
{% endif %}
265265

266266
{% include "front/report/m_services_et_al.html" with d=result %}
267+
268+
{% if hidden_files %}
269+
<div>
270+
<h3>Hidden Files</h3>
271+
<p class="text-muted small">Information computed with
272+
<a class="small" target="_blank" href="https://github.com/pithus/bazaar">Pithus</a>.
273+
</p>
274+
<div class="overflow-box">
275+
{% include "front/report/m_hidden_files.html" with d=hidden_files r=result %}
276+
</div>
277+
</div>
278+
{% endif %}
267279
</div>
268280

269281
<div class="tab-pane" role="tabpanel" aria-labelledby="threat_intel-tab" id="threat_intel">
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<table class="table table-condensed">
2+
<thead>
3+
<tr>
4+
<th>File</th>
5+
</tr>
6+
</thead>
7+
<tbody>
8+
{% for fname, path in d.items %}
9+
<tr>
10+
<td>
11+
<a href="{% url 'front:dl_hidden' sha256=r.sha256 filename=fname %}">
12+
<code>{{ fname }}</code>
13+
</a>
14+
</td>
15+
{% endfor %}
16+
</tbody>
17+
</table>

‎requirements/base.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ numpy==2.4.1
4545
pandas==2.3.3
4646
tld==0.13.1
4747
matplotlib
48+
binwalkpy @ git+https://github.com/Pithus/binwalkpy.git
4849

4950
# Map
5051
pygal_maps_world==1.0.2

0 commit comments

Comments
 (0)