diff --git a/monkey/infection_monkey/exploit/sshexec.py b/monkey/infection_monkey/exploit/sshexec.py index 31757a5e3..c59871257 100644 --- a/monkey/infection_monkey/exploit/sshexec.py +++ b/monkey/infection_monkey/exploit/sshexec.py @@ -177,8 +177,15 @@ class SSHExploiter(HostExploiter): raise FailedExploitationError def _exploit_host(self) -> ExploiterResultData: + port = self._get_ssh_port() + is_open, _ = check_tcp_port(self.host.ip_addr, port) + if not is_open: + self.exploit_result.error_message = f"SSH port is closed on {self.host}, skipping" + logger.info(self.exploit_result.error_message) + return self.exploit_result + try: - ssh = self._exploit() + ssh = self._exploit(port) except FailedExploitationError as err: self.exploit_result.error_message = str(err) logger.error(str(err)) @@ -203,26 +210,7 @@ class SSHExploiter(HostExploiter): ) return self.exploit_result - def _exploit(self) -> paramiko.SSHClient: - port = SSH_PORT - - # if ssh banner found on different port, use that port. - for servkey, servdata in list(self.host.services.items()): - if servdata.get("name") == "ssh" and servkey.startswith("tcp-"): - port = int(servkey.replace("tcp-", "")) - - is_open, _ = check_tcp_port(self.host.ip_addr, port) - if not is_open: - self.exploit_result.error_message = f"SSH port is closed on {self.host}, skipping" - self._publish_exploitation_event( - target=self.host.ip_addr, - exploitation_success=False, - error_message=self.exploit_result.error_message, - tags=(SSH_EXPLOITER_TAG,), - ) - logger.info(self.exploit_result.error_message) - raise FailedExploitationError(self.exploit_result.error_message) - + def _exploit(self, port) -> paramiko.SSHClient: try: ssh = self.exploit_with_ssh_keys(port) except FailedExploitationError: @@ -294,6 +282,16 @@ class SSHExploiter(HostExploiter): except Exception as exc: raise FailedExploitationError(f"Error running monkey on victim {self.host}: ({exc})") + def _get_ssh_port(self) -> int: + port = SSH_PORT + + # if ssh banner found on different port, use that port. + for servkey, servdata in list(self.host.services.items()): + if servdata.get("name") == "ssh" and servkey.startswith("tcp-"): + port = int(servkey.replace("tcp-", "")) + + return port + def _get_victim_os(self, ssh: paramiko.SSHClient) -> bool: try: _, stdout, _ = ssh.exec_command("uname -o", timeout=SSH_EXEC_TIMEOUT)