-
-
Notifications
You must be signed in to change notification settings - Fork 529
Mullvad_DNS (New Analyzer) #2763
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
16 commits
Select commit
Hold shift + click to select a range
d4e89a9
created Mullvad_DNS analyzer
AnshSinghal 3ee0d72
resolved the issue
AnshSinghal 111b880
Merge branch 'develop' into Mullvad_DNS
AnshSinghal 6ae8b29
Resolved issues in PR
AnshSinghal a225a26
resolved migration conflict
AnshSinghal bc2eed1
resolved the classification error in analyzer
AnshSinghal 6e641b2
fixed the tests error because of invalid sample DNS
AnshSinghal 127e424
updated the requirements and the Mockup Response
AnshSinghal 0e39716
Removed unnecessary support for generic observable
AnshSinghal 58b449f
Changed the variable hostname and redundant observable variable
AnshSinghal a242ff0
Added varibale observable
AnshSinghal 7900934
accepted changes by @fgibertoni
AnshSinghal 186da2a
implemented requested changes and cleaned the code
AnshSinghal 84d59d7
added comment for httpx requirement
AnshSinghal 299e864
add the comment for package requirement
AnshSinghal 6d88d9d
Enhanced logging information
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
160 changes: 160 additions & 0 deletions
160
api_app/analyzers_manager/migrations/0150_analyzer_config_mullvad_dns.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,160 @@ | ||
| 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": "mullvad_dns.MullvadDNSAnalyzer", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "Mullvad_DNS", | ||
| "description": 'This analyzer queries Mullvad\'s DNS-over-HTTPS service (using the "base" endpoint) to check a domain\'s DNS records. It supports two modes:\r\n- "query": returns raw DNS answer data.\r\n- "malicious": interprets an NXDOMAIN (rcode==3) as the domain being blocked (i.e., malicious).', | ||
| "disabled": False, | ||
| "soft_time_limit": 60, | ||
| "routing_key": "default", | ||
| "health_check_status": True, | ||
| "type": "observable", | ||
| "docker_based": False, | ||
| "maximum_tlp": "RED", | ||
| "observable_supported": ["url", "domain", "generic"], | ||
| "supported_filetypes": [], | ||
| "run_hash": False, | ||
| "run_hash_type": "", | ||
| "not_supported_filetypes": [], | ||
| "mapping_data_model": {}, | ||
| "model": "analyzers_manager.AnalyzerConfig", | ||
| } | ||
|
|
||
| params = [ | ||
| { | ||
| "python_module": { | ||
| "module": "mullvad_dns.MullvadDNSAnalyzer", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "mode", | ||
| "type": "str", | ||
| "description": "'query': returns raw DNS answer data.\r\n'malicious': interprets an NXDOMAIN (rcode==3) as the domain being blocked (i.e., malicious).", | ||
| "is_secret": False, | ||
| "required": False, | ||
| } | ||
| ] | ||
|
|
||
| values = [ | ||
| { | ||
| "parameter": { | ||
| "python_module": { | ||
| "module": "mullvad_dns.MullvadDNSAnalyzer", | ||
| "base_path": "api_app.analyzers_manager.observable_analyzers", | ||
| }, | ||
| "name": "mode", | ||
| "type": "str", | ||
| "description": "'query': returns raw DNS answer data.\r\n'malicious': interprets an NXDOMAIN (rcode==3) as the domain being blocked (i.e., malicious).", | ||
| "is_secret": False, | ||
| "required": False, | ||
| }, | ||
| "analyzer_config": "Mullvad_DNS", | ||
| "connector_config": None, | ||
| "visualizer_config": None, | ||
| "ingestor_config": None, | ||
| "pivot_config": None, | ||
| "for_organization": False, | ||
| "value": "query", | ||
| "updated_at": "2025-02-20T16:14:25.192983Z", | ||
| "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, | ||
| 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", "0065_job_mpnodesearch"), | ||
| ("analyzers_manager", "0149_alter_die_analyzer"), | ||
| ] | ||
|
|
||
| operations = [migrations.RunPython(migrate, reverse_migrate)] | ||
120 changes: 120 additions & 0 deletions
120
api_app/analyzers_manager/observable_analyzers/mullvad_dns.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,120 @@ | ||
| # This file is a part of IntelOwl https://github.com/intelowlproject/IntelOwl | ||
| # See the file 'LICENSE' for copying permission. | ||
|
|
||
|
|
||
| import base64 | ||
| import logging | ||
| from urllib.parse import urlparse | ||
|
|
||
| import dns.message | ||
| import httpx | ||
AnshSinghal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| from api_app.analyzers_manager.classes import ObservableAnalyzer | ||
| from api_app.analyzers_manager.exceptions import AnalyzerConfigurationException | ||
| from api_app.analyzers_manager.observable_analyzers.dns.dns_responses import ( | ||
| malicious_detector_response, | ||
| ) | ||
| from tests.mock_utils import MockUpResponse, if_mock_connections, patch | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class MullvadDNSAnalyzer(ObservableAnalyzer): | ||
| """ | ||
| MullvadDNSAnalyzer: | ||
| This analyzer queries Mullvad's DNS-over-HTTPS service (using the "base" endpoint) | ||
| to check a domain's DNS records. It supports two modes: | ||
| - "query": returns raw DNS answer data. | ||
| - "malicious": interprets an NXDOMAIN (rcode==3) as the domain being blocked (i.e., malicious). | ||
| """ | ||
|
|
||
| url = "https://base.dns.mullvad.net/dns-query" | ||
|
|
||
| def update(self): | ||
| pass | ||
|
|
||
| @staticmethod | ||
| def encode_query(observable: str) -> str: | ||
| """ | ||
| Constructs a DNS query for the given observable (domain) for an A record, | ||
| converts it to wire format, and encodes it in URL-safe base64. | ||
| """ | ||
| logger.info(f"Encoding DNS query for {observable}") | ||
| query = dns.message.make_query(observable, dns.rdatatype.A) | ||
| wire_query = query.to_wire() | ||
| encoded_query = ( | ||
| base64.urlsafe_b64encode(wire_query).rstrip(b"=").decode("ascii") | ||
| ) | ||
| logger.info(f"Encoded query: {encoded_query}") | ||
| return encoded_query | ||
|
|
||
| def run(self): | ||
| """ | ||
| Executes the analyzer: | ||
| - Validates the observable type (DOMAIN or URL). | ||
| - For URLs, extracts the hostname. | ||
| - Encodes a DNS "A" record query. | ||
| - Makes an HTTP GET request to the Mullvad DoH endpoint. | ||
| - Parses the DNS response. | ||
| - Depending on the configured mode ("query" or "malicious"), returns either raw data or a flagged result. | ||
| """ | ||
|
|
||
| observable = self.observable_name | ||
|
|
||
| if self.observable_classification == self.ObservableTypes.URL.value: | ||
| observable = urlparse(observable).hostname | ||
|
|
||
| encoded_query = self.encode_query(observable) | ||
| complete_url = f"{self.url}?dns={encoded_query}" | ||
| logger.info(f"Requesting Mullvad DNS at: {complete_url}") | ||
|
|
||
| try: | ||
| response = httpx.Client(http2=True).get( | ||
| complete_url, | ||
| headers={"accept": "application/dns-message"}, | ||
| timeout=30.0, | ||
| ) | ||
| response.raise_for_status() | ||
| except httpx.HTTPError as e: | ||
| logger.error(f"HTTP error: {e}") | ||
| raise AnalyzerConfigurationException(f"Failed to query Mullvad DNS: {e}") | ||
|
|
||
| dns_response = dns.message.from_wire(response.content) | ||
|
|
||
| if self.mode == "malicious": | ||
| if dns_response.rcode() == 3: | ||
| return malicious_detector_response( | ||
| observable=observable, | ||
| malicious=True, | ||
| note="Domain is blocked by Mullvad DNS content filtering.", | ||
| ) | ||
| else: | ||
| return malicious_detector_response( | ||
| observable=observable, | ||
| malicious=False, | ||
| note="Domain is not blocked by Mullvad DNS content filtering.", | ||
| ) | ||
|
|
||
| else: | ||
| answers = dns_response.answer | ||
| data = [str(rrset) for rrset in answers] if answers else [] | ||
| return { | ||
| "status": "success", | ||
| "data": data, | ||
| "message": f"DNS query for {observable} completed successfully.", | ||
| } | ||
|
|
||
| @classmethod | ||
| def _monkeypatch(cls): | ||
| patches = [ | ||
| if_mock_connections( | ||
| patch( | ||
| "httpx.Client.get", | ||
| return_value=MockUpResponse( | ||
| {}, 200, content=b"\x12\x34\x56\x78..." | ||
| ), | ||
| ) | ||
| ) | ||
| ] | ||
| return super()._monkeypatch(patches=patches) | ||
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.