-
-
Notifications
You must be signed in to change notification settings - Fork 529
Pdf uri extractor and pivoting #2391
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
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a020bcc
uri extraction
federicofantini 2ef8b87
added download file analyzer and pivot configs
federicofantini 274b5aa
fixed code review doctor
federicofantini 5bddd39
made code review changes
federicofantini e3a7e2c
added abstract update method
federicofantini 5e83a32
Merge remote-tracking branch 'public/develop' into pdf-uri-extractor-…
federicofantini 647ed38
fixed migration order
federicofantini fc21106
fixed validated_data dict access
federicofantini 5d9899e
Merge branch 'develop' into pdf-uri-extractor-and-pivoting
federicofantini f9db6ec
fixed migrations order
federicofantini 4259773
fixed migrations order
federicofantini 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
163 changes: 163 additions & 0 deletions
163
api_app/analyzers_manager/migrations/0097_analyzer_config_downloadfilefromuri.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,163 @@ | ||
| from django.db import migrations | ||
| from django.db.models.fields.related_descriptors import ( | ||
| ForwardManyToOneDescriptor, | ||
| ForwardOneToOneDescriptor, | ||
| ManyToManyDescriptor, | ||
| ) | ||
|
|
||
| plugin = { | ||
| "python_module": { | ||
| "health_check_schedule": None, | ||
| "update_schedule": None, | ||
| "module": "download_file_from_uri.DownloadFileFromUri", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "DownloadFileFromUri", | ||
| "description": "performs an http request to an uri and download the file through the http proxy", | ||
| "disabled": False, | ||
| "soft_time_limit": 60, | ||
| "routing_key": "default", | ||
| "health_check_status": True, | ||
| "type": "observable", | ||
| "docker_based": False, | ||
| "maximum_tlp": "RED", | ||
| "observable_supported": ["url"], | ||
| "supported_filetypes": [], | ||
| "run_hash": False, | ||
| "run_hash_type": "", | ||
| "not_supported_filetypes": [], | ||
| "model": "analyzers_manager.AnalyzerConfig", | ||
| } | ||
|
|
||
| params = [ | ||
| { | ||
| "python_module": { | ||
| "module": "download_file_from_uri.DownloadFileFromUri", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "http_proxy", | ||
| "type": "str", | ||
| "description": "http proxy url", | ||
| "is_secret": True, | ||
| "required": True, | ||
| }, | ||
| { | ||
| "python_module": { | ||
| "module": "download_file_from_uri.DownloadFileFromUri", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "basefolder", | ||
| "type": "str", | ||
| "description": "folder where the files will be stored", | ||
| "is_secret": False, | ||
| "required": True, | ||
| }, | ||
| ] | ||
|
|
||
| values = [ | ||
| { | ||
| "parameter": { | ||
| "python_module": { | ||
| "module": "download_file_from_uri.DownloadFileFromUri", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "basefolder", | ||
| "type": "str", | ||
| "description": "folder where the files will be stored", | ||
| "is_secret": False, | ||
| "required": True, | ||
| }, | ||
| "analyzer_config": "DownloadFileFromUri", | ||
| "connector_config": None, | ||
| "visualizer_config": None, | ||
| "ingestor_config": None, | ||
| "pivot_config": None, | ||
| "for_organization": False, | ||
| "value": "/opt/deploy/files_required/downloaded_files_from_uris/", | ||
| "updated_at": "2024-06-19T10:23:03.145744Z", | ||
| "owner": None, | ||
| } | ||
| ] | ||
|
|
||
|
|
||
| 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, 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", "0062_alter_parameter_python_module"), | ||
| ("analyzers_manager", "0096_analyzer_config_malprobscan"), | ||
| ] | ||
|
|
||
| operations = [migrations.RunPython(migrate, reverse_migrate)] |
77 changes: 77 additions & 0 deletions
77
api_app/analyzers_manager/observable_analyzers/download_file_from_uri.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,77 @@ | ||
| # This file is a part of IntelOwl https://github.com/intelowlproject/IntelOwl | ||
| # See the file 'LICENSE' for copying permission. | ||
|
|
||
| import logging | ||
| import os | ||
| import re | ||
| import unicodedata | ||
| from urllib.parse import unquote, urlparse | ||
|
|
||
| import requests | ||
|
|
||
| from api_app.analyzers_manager.classes import ObservableAnalyzer | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # https://github.com/django/django/blob/master/django/utils/text.py | ||
| def custom_slugify(value, allow_unicode=False): | ||
| value = str(value) | ||
| if allow_unicode: | ||
| value = unicodedata.normalize("NFKC", value) | ||
| else: | ||
| value = ( | ||
| unicodedata.normalize("NFKD", value) | ||
| .encode("ascii", "ignore") | ||
| .decode("ascii") | ||
| ) | ||
| # clear strange chars | ||
| return re.sub(r"[\\\"'$&%/#@()]", "", value) | ||
|
|
||
|
|
||
| class DownloadFileFromUri(ObservableAnalyzer): | ||
| basefolder: str | ||
| _http_proxy: str | ||
|
|
||
| def run(self): | ||
| result = {"errors": [], "stored_in": ""} | ||
|
|
||
| if not os.path.exists(self.basefolder): | ||
| os.makedirs(self.basefolder) | ||
|
|
||
| proxies = {"http": self._http_proxy} if self._http_proxy else {} | ||
| headers = { | ||
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " | ||
| "AppleWebKit/537.36 (KHTML, like Gecko) " | ||
| "Chrome/126.0.0.0 Safari/537.36 Edg/125.0.2535.92", | ||
| "Content-type": "application/octet-stream", | ||
| } | ||
federicofantini marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| try: | ||
| r = requests.get( | ||
| self.observable_name, | ||
| headers=headers, | ||
| proxies=proxies, | ||
| allow_redirects=True, | ||
| timeout=50, | ||
federicofantini marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ) | ||
| except requests.exceptions.Timeout as e: | ||
| result["errors"].append(f"timeout: {e}") | ||
| except requests.exceptions.TooManyRedirects as e: | ||
| result["errors"].append(f"too many requests: {e}") | ||
| except requests.exceptions.HTTPError as e: | ||
| result["errors"].append(f"http error: {e}") | ||
| except requests.exceptions.ConnectionError as e: | ||
| result["errors"].append(f"connection error: {e}") | ||
| except requests.exceptions.RequestException as e: | ||
| result["errors"].append(f"catastrophic error: {e}") | ||
federicofantini marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| else: | ||
| if filename := custom_slugify( | ||
| os.path.basename(urlparse(unquote(self.observable_name)).path) | ||
| ): | ||
| with open(os.path.join(self.basefolder, filename), "wb") as tmp: | ||
| tmp.write(r.content) | ||
| tmp.flush() | ||
| tmp.close() | ||
| result["stored_in"] = os.path.join(self.basefolder, filename) | ||
| return result | ||
federicofantini marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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.