-
-
Notifications
You must be signed in to change notification settings - Fork 492
[Analyzer] Debloat #2806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
[Analyzer] Debloat #2806
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
00e4c8d
initial commit for Debloat
AnshSinghal e02df24
converted binary to pefile
AnshSinghal 97a73f1
completed the debloat analyzer
AnshSinghal 90e1659
fixed minor bugs
AnshSinghal 546b258
migration file
AnshSinghal aab2924
handling files with no solution
AnshSinghal 5843f03
handling files with no solution
AnshSinghal 9337939
added example of debloated file in monkeypatch
AnshSinghal 22d5218
updated the version of debloat
AnshSinghal 87b4fcb
updated migrations file
AnshSinghal b586c03
fised migration file
AnshSinghal 4e30211
corrected json in monkeypatch
AnshSinghal aae36f5
updated version, emulated flush, changed TLP
AnshSinghal eed2df9
improved logging
AnshSinghal 4ae033c
fixed minor loop issue
AnshSinghal 7a2e06d
Update debloat.py
AnshSinghal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
# This file is a part of IntelOwl https://github.com/intelowlproject/IntelOwl | ||
# See the file 'LICENSE' for copying permission. | ||
|
||
import hashlib | ||
import logging | ||
import os | ||
import sys | ||
from base64 import b64encode | ||
from tempfile import TemporaryDirectory | ||
|
||
import pefile | ||
from debloat.processor import process_pe | ||
|
||
from api_app.analyzers_manager.classes import FileAnalyzer | ||
from api_app.analyzers_manager.exceptions import AnalyzerRunException | ||
from tests.mock_utils import MockUpResponse, if_mock_connections, patch | ||
|
||
logger = logging.getLogger(__name__) | ||
logger.setLevel(logging.DEBUG) | ||
|
||
|
||
# Custom logger to handle the debloat library's logging | ||
def log_message(*args, end="\n", flush=False, **kwargs): | ||
message = " ".join(map(str, args)) | ||
if end: | ||
message += end | ||
valid_kwargs = {} | ||
for key, value in kwargs.items(): | ||
if key in [ | ||
"level", | ||
"exc_info", | ||
"stack_info", | ||
"extra", | ||
"msg", | ||
"args", | ||
"kwargs", | ||
]: | ||
valid_kwargs[key] = value | ||
logger.info(message, **valid_kwargs) | ||
# Emulate flush if requested | ||
fgibertoni marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for handler in logger.handlers: | ||
if hasattr(handler, "flush"): | ||
handler.flush() | ||
break | ||
else: | ||
# Fallback to stdout flush if no flushable handlers | ||
sys.stdout.flush() | ||
|
||
|
||
class Debloat(FileAnalyzer): | ||
|
||
def run(self): | ||
try: | ||
binary = pefile.PE(self.filepath, fast_load=True) | ||
except pefile.PEFormatError as e: | ||
raise AnalyzerRunException(f"Invalid PE file: {e}") | ||
|
||
with TemporaryDirectory() as temp_dir: | ||
output_path = os.path.join(temp_dir, "debloated.exe") | ||
original_size = os.path.getsize(self.filepath) | ||
|
||
try: | ||
debloat_code = process_pe( | ||
binary, | ||
out_path=output_path, | ||
last_ditch_processing=True, | ||
cert_preservation=True, | ||
log_message=log_message, | ||
beginning_file_size=original_size, | ||
) | ||
except OSError as e: | ||
raise AnalyzerRunException( | ||
f"File operation failed during Debloat processing: {e}" | ||
) | ||
except ValueError as e: | ||
raise AnalyzerRunException( | ||
f"Invalid parameter in Debloat processing: {e}" | ||
) | ||
except AttributeError as e: | ||
raise AnalyzerRunException( | ||
f"Debloat library error, possibly malformed PE object: {e}" | ||
) | ||
|
||
logger.info(f"Debloat processed {self.filepath} with code {debloat_code}") | ||
|
||
if debloat_code == 0 and not os.path.exists(output_path): | ||
return { | ||
"success": False, | ||
"error": "No solution found", | ||
} | ||
|
||
if not os.path.exists(output_path) or not os.path.isfile(output_path): | ||
raise AnalyzerRunException( | ||
"Debloat did not produce a valid output file" | ||
) | ||
|
||
debloated_size = os.path.getsize(output_path) | ||
size_reduction = ( | ||
(original_size - debloated_size) / original_size * 100 | ||
if original_size > 0 | ||
else 0 | ||
) | ||
|
||
with open(output_path, "rb") as f: | ||
output = f.read() | ||
debloated_hash = hashlib.md5(output).hexdigest() | ||
AnshSinghal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
debloated_sha256 = hashlib.sha256(output).hexdigest() | ||
|
||
encoded_output = b64encode(output).decode("utf-8") | ||
|
||
os.remove(output_path) | ||
logger.debug("Cleaned up temporary file.") | ||
|
||
return { | ||
"success": True, | ||
"original_size": original_size, | ||
"debloated_size": debloated_size, | ||
"debloated_file": encoded_output, | ||
"size_reduction_percentage": size_reduction, | ||
"debloated_hash": debloated_hash, | ||
"debloated_sha256": debloated_sha256, | ||
} | ||
|
||
@classmethod | ||
def update(cls) -> bool: | ||
pass | ||
|
||
@classmethod | ||
def _monkeypatch(cls, patches: list = None): | ||
patches = [ | ||
if_mock_connections( | ||
patch( | ||
"debloat.processor.process_pe", | ||
return_value=MockUpResponse( | ||
{ | ||
"success": True, | ||
"original_size": 3840392, | ||
"debloated_file": "TVqQAAMAAAAEAAAA//", | ||
"debloated_hash": "f7f92eadfb444e7fce27efa2007a955a", | ||
"debloated_size": 813976, | ||
"size_reduction_percentage": 78.80487200264973, | ||
"debloated_sha256": "f7f92eadfb444e7fce27efa2007a955a", | ||
}, | ||
200, | ||
), | ||
) | ||
), | ||
] | ||
return super()._monkeypatch(patches) |
125 changes: 125 additions & 0 deletions
125
api_app/analyzers_manager/migrations/0155_analyzer_config_debloat.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
from django.db import migrations | ||
from django.db.models.fields.related_descriptors import ( | ||
ForwardManyToOneDescriptor, | ||
ForwardOneToOneDescriptor, | ||
ManyToManyDescriptor, | ||
ReverseManyToOneDescriptor, | ||
ReverseOneToOneDescriptor, | ||
) | ||
|
||
plugin = { | ||
"python_module": { | ||
"health_check_schedule": None, | ||
"update_schedule": None, | ||
"module": "debloat.Debloat", | ||
"base_path": "api_app.analyzers_manager.file_analyzers", | ||
}, | ||
"name": "Debloat", | ||
"description": '"Analyzer for debloating PE files using the [Debloat](https://github.com/Squiblydoo/debloat) tool. Reduces file size for easier malware analysis."', | ||
"disabled": False, | ||
"soft_time_limit": 300, | ||
"routing_key": "default", | ||
"health_check_status": True, | ||
"type": "file", | ||
"docker_based": False, | ||
"maximum_tlp": "CLEAR", | ||
"observable_supported": [], | ||
"supported_filetypes": ["application/vnd.microsoft.portable-executable"], | ||
"run_hash": False, | ||
"run_hash_type": "", | ||
"not_supported_filetypes": [], | ||
"mapping_data_model": {}, | ||
"model": "analyzers_manager.AnalyzerConfig", | ||
} | ||
|
||
params = [] | ||
|
||
values = [] | ||
|
||
|
||
def _get_real_obj(Model, field, value): | ||
def _get_obj(Model, other_model, value): | ||
if isinstance(value, dict): | ||
real_vals = {} | ||
for key, real_val in value.items(): | ||
real_vals[key] = _get_real_obj(other_model, key, real_val) | ||
value = other_model.objects.get_or_create(**real_vals)[0] | ||
# it is just the primary key serialized | ||
else: | ||
if isinstance(value, int): | ||
if Model.__name__ == "PluginConfig": | ||
value = other_model.objects.get(name=plugin["name"]) | ||
else: | ||
value = other_model.objects.get(pk=value) | ||
else: | ||
value = other_model.objects.get(name=value) | ||
return value | ||
|
||
if ( | ||
type(getattr(Model, field)) | ||
in [ | ||
ForwardManyToOneDescriptor, | ||
ReverseManyToOneDescriptor, | ||
ReverseOneToOneDescriptor, | ||
ForwardOneToOneDescriptor, | ||
] | ||
and value | ||
): | ||
other_model = getattr(Model, field).get_queryset().model | ||
value = _get_obj(Model, other_model, value) | ||
elif type(getattr(Model, field)) in [ManyToManyDescriptor] and value: | ||
other_model = getattr(Model, field).rel.model | ||
value = [_get_obj(Model, other_model, val) for val in value] | ||
return value | ||
|
||
|
||
def _create_object(Model, data): | ||
mtm, no_mtm = {}, {} | ||
for field, value in data.items(): | ||
value = _get_real_obj(Model, field, value) | ||
if type(getattr(Model, field)) is ManyToManyDescriptor: | ||
mtm[field] = value | ||
else: | ||
no_mtm[field] = value | ||
try: | ||
o = Model.objects.get(**no_mtm) | ||
except Model.DoesNotExist: | ||
o = Model(**no_mtm) | ||
o.full_clean() | ||
o.save() | ||
for field, value in mtm.items(): | ||
attribute = getattr(o, field) | ||
if value is not None: | ||
attribute.set(value) | ||
return False | ||
return True | ||
|
||
|
||
def migrate(apps, schema_editor): | ||
Parameter = apps.get_model("api_app", "Parameter") | ||
PluginConfig = apps.get_model("api_app", "PluginConfig") | ||
python_path = plugin.pop("model") | ||
Model = apps.get_model(*python_path.split(".")) | ||
if not Model.objects.filter(name=plugin["name"]).exists(): | ||
exists = _create_object(Model, plugin) | ||
if not exists: | ||
for param in params: | ||
_create_object(Parameter, param) | ||
for value in values: | ||
_create_object(PluginConfig, value) | ||
|
||
|
||
def reverse_migrate(apps, schema_editor): | ||
python_path = plugin.pop("model") | ||
Model = apps.get_model(*python_path.split(".")) | ||
Model.objects.get(name=plugin["name"]).delete() | ||
|
||
|
||
class Migration(migrations.Migration): | ||
atomic = False | ||
dependencies = [ | ||
("api_app", "0071_delete_last_elastic_report"), | ||
("analyzers_manager", "0154_analyzer_config_bbot"), | ||
] | ||
|
||
operations = [migrations.RunPython(migrate, reverse_migrate)] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,43 @@ | ||
services: | ||
uwsgi: | ||
build: | ||
context: .. | ||
dockerfile: docker/Dockerfile | ||
args: | ||
REPO_DOWNLOADER_ENABLED: ${REPO_DOWNLOADER_ENABLED} | ||
WATCHMAN: "true" | ||
PYCTI_VERSION: ${PYCTI_VERSION:-5.10.0} | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True | ||
- DJANGO_TEST_SERVER=True | ||
- DJANGO_WATCHMAN_TIMEOUT=60 | ||
|
||
daphne: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
|
||
nginx: | ||
build: | ||
context: .. | ||
dockerfile: docker/Dockerfile_nginx | ||
image: intelowlproject/intelowl_nginx:test | ||
volumes: | ||
- ../configuration/nginx/django_server.conf:/etc/nginx/conf.d/default.conf | ||
|
||
celery_beat: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True | ||
|
||
celery_worker_default: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True | ||
services: | ||
uwsgi: | ||
build: | ||
context: .. | ||
dockerfile: docker/Dockerfile | ||
args: | ||
REPO_DOWNLOADER_ENABLED: ${REPO_DOWNLOADER_ENABLED} | ||
fgibertoni marked this conversation as resolved.
Show resolved
Hide resolved
|
||
WATCHMAN: "true" | ||
PYCTI_VERSION: ${PYCTI_VERSION:-5.10.0} | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True | ||
- DJANGO_TEST_SERVER=True | ||
- DJANGO_WATCHMAN_TIMEOUT=60 | ||
daphne: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
nginx: | ||
build: | ||
context: .. | ||
dockerfile: docker/Dockerfile_nginx | ||
image: intelowlproject/intelowl_nginx:test | ||
volumes: | ||
- ../configuration/nginx/django_server.conf:/etc/nginx/conf.d/default.conf | ||
celery_beat: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True | ||
celery_worker_default: | ||
image: intelowlproject/intelowl:test | ||
volumes: | ||
- ../:/opt/deploy/intel_owl | ||
environment: | ||
- DEBUG=True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.