From 656aba263a77d32871b24d0072956bf18151a52f Mon Sep 17 00:00:00 2001 From: ErebusZ Date: Thu, 4 Jan 2024 10:24:12 +0100 Subject: [PATCH] Handle nmap command crash --- agent/nmap_agent.py | 13 ++++++++++--- tests/conftest.py | 8 ++++++++ tests/nmap_agent_test.py | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/agent/nmap_agent.py b/agent/nmap_agent.py index cf933deb..72a68a33 100644 --- a/agent/nmap_agent.py +++ b/agent/nmap_agent.py @@ -129,7 +129,11 @@ def process(self, message: msg.Message) -> None: "target %s/%s was processed before, exiting", host, mask ) return - scan_results, normal_results = self._scan_host(host, mask) + try: + scan_results, normal_results = self._scan_host(host, mask) + except subprocess.CalledProcessError: + logger.error("Nmap command failed to scan host %s", host) + continue logger.info("scan results %s", scan_results) self._emit_services(scan_results, domain_name) @@ -141,8 +145,11 @@ def process(self, message: msg.Message) -> None: return if self._is_domain_in_scope(domain_name) is False: return - - scan_results, normal_results = self._scan_domain(domain_name) + try: + scan_results, normal_results = self._scan_domain(domain_name) + except subprocess.CalledProcessError: + logger.error("Nmap command failed to scan domain name %s", domain_name) + return logger.info("scan results %s", scan_results) self._emit_services(scan_results, domain_name) diff --git a/tests/conftest.py b/tests/conftest.py index 365ac01b..5eb2e311 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -371,3 +371,11 @@ def nmap_agent_all_ports( agent = nmap_agent.NmapAgent(definition, settings) return agent + + +@pytest.fixture +def invalid_domain_msg() -> message.Message: + """Creates a dummy message of type v3.asset.domain_name for testing purposes.""" + return message.Message.from_data( + selector="v3.asset.domain_name", data={"name": "-ostorlab.co"} + ) diff --git a/tests/nmap_agent_test.py b/tests/nmap_agent_test.py index 17908482..f7aec00a 100644 --- a/tests/nmap_agent_test.py +++ b/tests/nmap_agent_test.py @@ -1,6 +1,7 @@ """Unittests for Nmap agent.""" import json from typing import List, Dict, Union +import subprocess import requests_mock as rq_mock from ostorlab.agent.message import message @@ -669,3 +670,20 @@ def testNmapAgent_whenIpv6AboveLimit_agentShouldRaiseError( assert len(agent_mock) == 0 assert error_message.value.args[0] == "Subnet mask below 112 is not supported" + + +def testAgentNmap_whenInvalidDomainName_doesNotCrash( + nmap_test_agent: nmap_agent.NmapAgent, + agent_mock: List[message.Message], + invalid_domain_msg: message.Message, + mocker: plugin.MockerFixture, +) -> None: + """Unit test for testing agent handling of an invalid domain name.""" + mocker.patch( + "subprocess.run", + side_effect=subprocess.CalledProcessError(255, ""), + ) + + nmap_test_agent.process(invalid_domain_msg) + + assert len(agent_mock) == 0