diff --git a/monkey/common/cloud/aws_instance.py b/monkey/common/cloud/aws_instance.py index ea6a10df7..0aece9bcc 100644 --- a/monkey/common/cloud/aws_instance.py +++ b/monkey/common/cloud/aws_instance.py @@ -1,6 +1,6 @@ import json import re -import urllib2 +import urllib.request, urllib.error, urllib.parse import logging @@ -25,18 +25,18 @@ class AwsInstance(object): self.account_id = None try: - self.instance_id = urllib2.urlopen( + self.instance_id = urllib.request.urlopen( AWS_LATEST_METADATA_URI_PREFIX + 'meta-data/instance-id', timeout=2).read() self.region = self._parse_region( - urllib2.urlopen(AWS_LATEST_METADATA_URI_PREFIX + 'meta-data/placement/availability-zone').read()) - except urllib2.URLError as e: + urllib.request.urlopen(AWS_LATEST_METADATA_URI_PREFIX + 'meta-data/placement/availability-zone').read()) + except urllib.error.URLError as e: logger.warning("Failed init of AwsInstance while getting metadata: {}".format(e.message)) try: self.account_id = self._extract_account_id( - urllib2.urlopen( + urllib.request.urlopen( AWS_LATEST_METADATA_URI_PREFIX + 'dynamic/instance-identity/document', timeout=2).read()) - except urllib2.URLError as e: + except urllib.error.URLError as e: logger.warning("Failed init of AwsInstance while getting dynamic instance data: {}".format(e.message)) @staticmethod diff --git a/monkey/common/cloud/test_filter_instance_data_from_aws_response.py b/monkey/common/cloud/test_filter_instance_data_from_aws_response.py index 8aec518d3..b48674387 100644 --- a/monkey/common/cloud/test_filter_instance_data_from_aws_response.py +++ b/monkey/common/cloud/test_filter_instance_data_from_aws_response.py @@ -1,5 +1,5 @@ from unittest import TestCase -from aws_service import filter_instance_data_from_aws_response +from .aws_service import filter_instance_data_from_aws_response import json @@ -53,7 +53,7 @@ class TestFilter_instance_data_from_aws_response(TestCase): self.assertEqual(filter_instance_data_from_aws_response(json.loads(json_response_empty)), []) self.assertEqual( filter_instance_data_from_aws_response(json.loads(json_response_full)), - [{'instance_id': u'string', - 'ip_address': u'string', - 'name': u'string', - 'os': u'string'}]) + [{'instance_id': 'string', + 'ip_address': 'string', + 'name': 'string', + 'os': 'string'}]) diff --git a/monkey/common/cmd/aws/aws_cmd_result.py b/monkey/common/cmd/aws/aws_cmd_result.py index 79b1bb79d..c8647bfe4 100644 --- a/monkey/common/cmd/aws/aws_cmd_result.py +++ b/monkey/common/cmd/aws/aws_cmd_result.py @@ -11,8 +11,8 @@ class AwsCmdResult(CmdResult): def __init__(self, command_info): super(AwsCmdResult, self).__init__( - self.is_successful(command_info, True), command_info[u'ResponseCode'], command_info[u'StandardOutputContent'], - command_info[u'StandardErrorContent']) + self.is_successful(command_info, True), command_info['ResponseCode'], command_info['StandardOutputContent'], + command_info['StandardErrorContent']) self.command_info = command_info @staticmethod @@ -23,4 +23,4 @@ class AwsCmdResult(CmdResult): :param is_timeout: Whether the given command timed out :return: True if successful, False otherwise. """ - return (command_info[u'Status'] == u'Success') or (is_timeout and (command_info[u'Status'] == u'InProgress')) + return (command_info['Status'] == 'Success') or (is_timeout and (command_info['Status'] == 'InProgress')) diff --git a/monkey/common/cmd/aws/aws_cmd_runner.py b/monkey/common/cmd/aws/aws_cmd_runner.py index b4198f642..9745d2c1d 100644 --- a/monkey/common/cmd/aws/aws_cmd_runner.py +++ b/monkey/common/cmd/aws/aws_cmd_runner.py @@ -28,9 +28,9 @@ class AwsCmdRunner(CmdRunner): return AwsCmdResult(command_info) def get_command_status(self, command_info): - if command_info[u'Status'] == u'InProgress': + if command_info['Status'] == 'InProgress': return CmdStatus.IN_PROGRESS - elif command_info[u'Status'] == u'Success': + elif command_info['Status'] == 'Success': return CmdStatus.SUCCESS else: return CmdStatus.FAILURE diff --git a/monkey/common/cmd/cmd_runner.py b/monkey/common/cmd/cmd_runner.py index 6686508a4..0450321b0 100644 --- a/monkey/common/cmd/cmd_runner.py +++ b/monkey/common/cmd/cmd_runner.py @@ -61,7 +61,7 @@ class CmdRunner(object): command_instance_dict[command] = instance instance_results = {} - command_result_pairs = CmdRunner.wait_commands(command_instance_dict.keys()) + command_result_pairs = CmdRunner.wait_commands(list(command_instance_dict.keys())) for command, result in command_result_pairs: instance = command_instance_dict[command] instance_results[instance['instance_id']] = inst_n_cmd_res_to_res(instance, result) diff --git a/monkey/common/network/network_range.py b/monkey/common/network/network_range.py index de89f7e4a..244a3ad3b 100644 --- a/monkey/common/network/network_range.py +++ b/monkey/common/network/network_range.py @@ -12,9 +12,7 @@ __author__ = 'itamar' LOG = logging.getLogger(__name__) -class NetworkRange(object): - __metaclass__ = ABCMeta - +class NetworkRange(object, metaclass=ABCMeta): def __init__(self, shuffle=True): self._shuffle = shuffle @@ -119,7 +117,7 @@ class IpRange(NetworkRange): return self._lower_end_ip_num <= self._ip_to_number(ip_address) <= self._higher_end_ip_num def _get_range(self): - return range(self._lower_end_ip_num, self._higher_end_ip_num + 1) + return list(range(self._lower_end_ip_num, self._higher_end_ip_num + 1)) class SingleIpRange(NetworkRange): diff --git a/monkey/common/utils/mongo_utils.py b/monkey/common/utils/mongo_utils.py index 7524a545e..cc5bea7d1 100644 --- a/monkey/common/utils/mongo_utils.py +++ b/monkey/common/utils/mongo_utils.py @@ -12,8 +12,8 @@ class MongoUtils: @staticmethod def fix_obj_for_mongo(o): - if type(o) == dict: - return dict([(k, MongoUtils.fix_obj_for_mongo(v)) for k, v in o.iteritems()]) + if isinstance(o, dict): + return dict([(k, MongoUtils.fix_obj_for_mongo(v)) for k, v in list(o.items())]) elif type(o) in (list, tuple): return [MongoUtils.fix_obj_for_mongo(i) for i in o] @@ -21,7 +21,7 @@ class MongoUtils: elif type(o) in (int, float, bool): return o - elif type(o) in (str, unicode): + elif type(o) in (str, str): # mongo dosn't like unprintable chars, so we use repr :/ return repr(o) diff --git a/monkey/common/utils/reg_utils.py b/monkey/common/utils/reg_utils.py index 1e6c297b3..fad92df5e 100644 --- a/monkey/common/utils/reg_utils.py +++ b/monkey/common/utils/reg_utils.py @@ -1,4 +1,4 @@ -import _winreg +import winreg from common.utils.mongo_utils import MongoUtils @@ -12,11 +12,11 @@ class RegUtils: pass @staticmethod - def get_reg_key(subkey_path, store=_winreg.HKEY_LOCAL_MACHINE): - key = _winreg.ConnectRegistry(None, store) - subkey = _winreg.OpenKey(key, subkey_path) + def get_reg_key(subkey_path, store=winreg.HKEY_LOCAL_MACHINE): + key = winreg.ConnectRegistry(None, store) + subkey = winreg.OpenKey(key, subkey_path) - d = dict([_winreg.EnumValue(subkey, i)[:2] for i in xrange(_winreg.QueryInfoKey(subkey)[0])]) + d = dict([winreg.EnumValue(subkey, i)[:2] for i in range(winreg.QueryInfoKey(subkey)[0])]) d = MongoUtils.fix_obj_for_mongo(d) subkey.Close() diff --git a/monkey/common/utils/wmi_utils.py b/monkey/common/utils/wmi_utils.py index 7b1dae455..4df0e6886 100644 --- a/monkey/common/utils/wmi_utils.py +++ b/monkey/common/utils/wmi_utils.py @@ -1,6 +1,6 @@ import wmi -from mongo_utils import MongoUtils +from .mongo_utils import MongoUtils __author__ = 'maor.rayzin' diff --git a/monkey/infection_monkey.py b/monkey/infection_monkey.py index 86e5f5657..7059088c9 100644 --- a/monkey/infection_monkey.py +++ b/monkey/infection_monkey.py @@ -1,4 +1,4 @@ -import infection_monkey.main +from . import infection_monkey.main if "__main__" == __name__: infection_monkey.main.main() diff --git a/monkey/infection_monkey/config.py b/monkey/infection_monkey/config.py index f7e4cfae4..e95ad46b6 100644 --- a/monkey/infection_monkey/config.py +++ b/monkey/infection_monkey/config.py @@ -22,7 +22,7 @@ class Configuration(object): exploit_import = importlib.import_module('infection_monkey.exploit') unknown_items = [] - for key, value in formatted_data.items(): + for key, value in list(formatted_data.items()): if key.startswith('_'): continue if key in ["name", "id", "current_server"]: diff --git a/monkey/infection_monkey/exploit/__init__.py b/monkey/infection_monkey/exploit/__init__.py index 19e5b327e..0dacb3496 100644 --- a/monkey/infection_monkey/exploit/__init__.py +++ b/monkey/infection_monkey/exploit/__init__.py @@ -6,9 +6,7 @@ from datetime import datetime __author__ = 'itamar' -class HostExploiter(object): - __metaclass__ = ABCMeta - +class HostExploiter(object, metaclass=ABCMeta): _TARGET_OS_TYPE = [] # Usual values are 'vulnerability' or 'brute_force' diff --git a/monkey/infection_monkey/exploit/hadoop.py b/monkey/infection_monkey/exploit/hadoop.py index 958bab7eb..8dfa67b08 100644 --- a/monkey/infection_monkey/exploit/hadoop.py +++ b/monkey/infection_monkey/exploit/hadoop.py @@ -58,7 +58,7 @@ class HadoopExploiter(WebRCE): resp = json.loads(resp.content) app_id = resp['application-id'] # Create a random name for our application in YARN - rand_name = ID_STRING + "".join([random.choice(string.ascii_lowercase) for _ in xrange(self.RAN_STR_LEN)]) + rand_name = ID_STRING + "".join([random.choice(string.ascii_lowercase) for _ in range(self.RAN_STR_LEN)]) payload = self.build_payload(app_id, rand_name, command) resp = requests.post(posixpath.join(url, "ws/v1/cluster/apps/"), json=payload) return resp.status_code == 202 diff --git a/monkey/infection_monkey/exploit/rdpgrinder.py b/monkey/infection_monkey/exploit/rdpgrinder.py index 0db63e86d..ed64736ac 100644 --- a/monkey/infection_monkey/exploit/rdpgrinder.py +++ b/monkey/infection_monkey/exploit/rdpgrinder.py @@ -125,7 +125,7 @@ class KeyPressRDPClient(rdp.RDPClientObserver): self._update_lock.acquire() time_diff = time.time() - self._last_update - if type(key) is WaitUpdateEvent: + if isinstance(key, WaitUpdateEvent): self._wait_for_update = True self._update_lock.release() key.updates -= 1 @@ -134,12 +134,12 @@ class KeyPressRDPClient(rdp.RDPClientObserver): elif time_diff > KEYS_INTERVAL and (not self._wait_for_update or time_diff > MAX_WAIT_FOR_UPDATE): self._wait_for_update = False self._update_lock.release() - if type(key) is ScanCodeEvent: + if isinstance(key, ScanCodeEvent): reactor.callFromThread(self._controller.sendKeyEventScancode, key.code, key.is_pressed, key.is_special) - elif type(key) is CharEvent: + elif isinstance(key, CharEvent): reactor.callFromThread(self._controller.sendKeyEventUnicode, ord(key.char), key.is_pressed) - elif type(key) is SleepEvent: + elif isinstance(key, SleepEvent): time.sleep(key.interval) self._keys = self._keys[1:] diff --git a/monkey/infection_monkey/exploit/shellshock.py b/monkey/infection_monkey/exploit/shellshock.py index 743761a92..0e05149e7 100644 --- a/monkey/infection_monkey/exploit/shellshock.py +++ b/monkey/infection_monkey/exploit/shellshock.py @@ -169,7 +169,7 @@ class ShellShockExploiter(HostExploiter): LOG.debug("Attack Flag is: %s" % self.success_flag) LOG.debug("Trying exploit for %s" % url) - for header, exploit in attacks.iteritems(): + for header, exploit in attacks.items(): attack = exploit + ' echo ' + self.success_flag + "; " + TEST_COMMAND result = self.attack_page(url, header, attack) if self.success_flag in result: diff --git a/monkey/infection_monkey/exploit/smbexec.py b/monkey/infection_monkey/exploit/smbexec.py index d49e66ae8..4646d7dd2 100644 --- a/monkey/infection_monkey/exploit/smbexec.py +++ b/monkey/infection_monkey/exploit/smbexec.py @@ -95,7 +95,7 @@ class SmbExploiter(HostExploiter): cmdline = MONKEY_CMDLINE_DETACHED_WINDOWS % {'monkey_path': remote_full_path} + \ build_monkey_commandline(self.host, get_monkey_depth() - 1) - for str_bind_format, port in SmbExploiter.KNOWN_PROTOCOLS.values(): + for str_bind_format, port in list(SmbExploiter.KNOWN_PROTOCOLS.values()): rpctransport = transport.DCERPCTransportFactory(str_bind_format % (self.host.ip_addr,)) rpctransport.set_dport(port) diff --git a/monkey/infection_monkey/exploit/sshexec.py b/monkey/infection_monkey/exploit/sshexec.py index c7cf030c1..ff979d6e7 100644 --- a/monkey/infection_monkey/exploit/sshexec.py +++ b/monkey/infection_monkey/exploit/sshexec.py @@ -2,7 +2,7 @@ import logging import time import paramiko -import StringIO +import io import infection_monkey.monkeyfs as monkeyfs from infection_monkey.exploit import HostExploiter @@ -41,7 +41,7 @@ class SSHExploiter(HostExploiter): for user, ssh_key_pair in user_ssh_key_pairs: # Creating file-like private key for paramiko - pkey = StringIO.StringIO(ssh_key_pair['private_key']) + pkey = io.StringIO(ssh_key_pair['private_key']) ssh_string = "%s@%s" % (ssh_key_pair['user'], ssh_key_pair['ip']) try: pkey = paramiko.RSAKey.from_private_key(pkey) @@ -100,7 +100,7 @@ class SSHExploiter(HostExploiter): port = SSH_PORT # if ssh banner found on different port, use that port. - for servkey, servdata in self.host.services.items(): + for servkey, servdata in list(self.host.services.items()): if servdata.get('name') == 'ssh' and servkey.startswith('tcp-'): port = int(servkey.replace('tcp-', '')) diff --git a/monkey/infection_monkey/exploit/struts2.py b/monkey/infection_monkey/exploit/struts2.py index cb81a2ef5..4be2d0acd 100644 --- a/monkey/infection_monkey/exploit/struts2.py +++ b/monkey/infection_monkey/exploit/struts2.py @@ -3,8 +3,8 @@ code used is from https://www.exploit-db.com/exploits/41570/ Vulnerable struts2 versions <=2.3.31 and <=2.5.10 """ -import urllib2 -import httplib +import urllib.request, urllib.error, urllib.parse +import http.client import unicodedata import re import ssl @@ -47,10 +47,10 @@ class Struts2Exploiter(WebRCE): def get_redirected(url): # Returns false if url is not right headers = {'User-Agent': 'Mozilla/5.0'} - request = urllib2.Request(url, headers=headers) + request = urllib.request.Request(url, headers=headers) try: - return urllib2.urlopen(request, context=ssl._create_unverified_context()).geturl() - except urllib2.URLError: + return urllib.request.urlopen(request, context=ssl._create_unverified_context()).geturl() + except urllib.error.URLError: LOG.error("Can't reach struts2 server") return False @@ -80,17 +80,17 @@ class Struts2Exploiter(WebRCE): "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))." \ "(#ros.flush())}" % cmd # Turns payload ascii just for consistency - if isinstance(payload, unicode): + if isinstance(payload, str): payload = unicodedata.normalize('NFKD', payload).encode('ascii', 'ignore') headers = {'User-Agent': 'Mozilla/5.0', 'Content-Type': payload} try: - request = urllib2.Request(url, headers=headers) + request = urllib.request.Request(url, headers=headers) # Timeout added or else we would wait for all monkeys' output - page = urllib2.urlopen(request).read() + page = urllib.request.urlopen(request).read() except AttributeError: # If url does not exist return False - except httplib.IncompleteRead as e: + except http.client.IncompleteRead as e: page = e.partial return page diff --git a/monkey/infection_monkey/exploit/tools.py b/monkey/infection_monkey/exploit/tools.py index 0b496f8be..152205d70 100644 --- a/monkey/infection_monkey/exploit/tools.py +++ b/monkey/infection_monkey/exploit/tools.py @@ -6,7 +6,7 @@ import pprint import socket import struct import sys -import urllib +import urllib.request, urllib.parse, urllib.error from impacket.dcerpc.v5 import transport, srvs from impacket.dcerpc.v5.dcom import wmi @@ -105,9 +105,9 @@ class WmiTools(object): @staticmethod def dcom_cleanup(): - for port_map in DCOMConnection.PORTMAPS.keys(): + for port_map in list(DCOMConnection.PORTMAPS.keys()): del DCOMConnection.PORTMAPS[port_map] - for oid_set in DCOMConnection.OID_SET.keys(): + for oid_set in list(DCOMConnection.OID_SET.keys()): del DCOMConnection.OID_SET[port_map] DCOMConnection.OID_SET = {} @@ -151,7 +151,7 @@ class WmiTools(object): record = next_item.getProperties() if not fields: - fields = record.keys() + fields = list(record.keys()) query_record = {} for key in fields: @@ -383,7 +383,7 @@ class HTTPTools(object): httpd.daemon = True httpd.start() - return "http://%s:%s/%s" % (local_ip, local_port, urllib.quote(os.path.basename(src_path))), httpd + return "http://%s:%s/%s" % (local_ip, local_port, urllib.parse.quote(os.path.basename(src_path))), httpd @staticmethod def create_locked_transfer(host, src_path, local_ip=None, local_port=None): @@ -411,7 +411,7 @@ class HTTPTools(object): httpd = LockedHTTPServer(local_ip, local_port, src_path, lock) httpd.start() lock.acquire() - return "http://%s:%s/%s" % (local_ip, local_port, urllib.quote(os.path.basename(src_path))), httpd + return "http://%s:%s/%s" % (local_ip, local_port, urllib.parse.quote(os.path.basename(src_path))), httpd def get_interface_to_target(dst): diff --git a/monkey/infection_monkey/exploit/web_rce.py b/monkey/infection_monkey/exploit/web_rce.py index fe45c65ce..56aa77442 100644 --- a/monkey/infection_monkey/exploit/web_rce.py +++ b/monkey/infection_monkey/exploit/web_rce.py @@ -370,7 +370,7 @@ class WebRCE(HostExploiter): LOG.error("Something went wrong while trying to change permission: %s" % e) return False # If exploiter returns True / False - if type(resp) is bool: + if isinstance(resp, bool): LOG.info("Permission change finished") return resp # If exploiter returns command output, we can check for execution errors @@ -406,7 +406,7 @@ class WebRCE(HostExploiter): try: resp = self.exploit(url, command) # If exploiter returns True / False - if type(resp) is bool: + if isinstance(resp, bool): LOG.info("Execution attempt successfully finished") self.add_executed_cmd(command) return resp diff --git a/monkey/infection_monkey/exploit/weblogic.py b/monkey/infection_monkey/exploit/weblogic.py index 87ea58477..625de13c6 100644 --- a/monkey/infection_monkey/exploit/weblogic.py +++ b/monkey/infection_monkey/exploit/weblogic.py @@ -1,11 +1,11 @@ -from __future__ import print_function + import threading import logging import time import copy from requests import post, exceptions -from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from http.server import BaseHTTPRequestHandler, HTTPServer from infection_monkey.exploit.web_rce import WebRCE from infection_monkey.exploit import HostExploiter diff --git a/monkey/infection_monkey/exploit/win_ms08_067.py b/monkey/infection_monkey/exploit/win_ms08_067.py index e1d2e5b85..170a7f1dc 100644 --- a/monkey/infection_monkey/exploit/win_ms08_067.py +++ b/monkey/infection_monkey/exploit/win_ms08_067.py @@ -162,7 +162,7 @@ class Ms08_067_Exploiter(HostExploiter): def is_os_supported(self): if self.host.os.get('type') in self._TARGET_OS_TYPE and \ - self.host.os.get('version') in self._windows_versions.keys(): + self.host.os.get('version') in list(self._windows_versions.keys()): return True if not self.host.os.get('type') or ( @@ -172,7 +172,7 @@ class Ms08_067_Exploiter(HostExploiter): smb_finger = SMBFinger() if smb_finger.get_host_fingerprint(self.host): return self.host.os.get('type') in self._TARGET_OS_TYPE and \ - self.host.os.get('version') in self._windows_versions.keys() + self.host.os.get('version') in list(self._windows_versions.keys()) return False def _exploit_host(self): diff --git a/monkey/infection_monkey/main.py b/monkey/infection_monkey/main.py index b8e292243..817b83024 100644 --- a/monkey/infection_monkey/main.py +++ b/monkey/infection_monkey/main.py @@ -1,4 +1,4 @@ -from __future__ import print_function + import argparse import json diff --git a/monkey/infection_monkey/model/host.py b/monkey/infection_monkey/model/host.py index dcc6e7455..1a4fef1c8 100644 --- a/monkey/infection_monkey/model/host.py +++ b/monkey/infection_monkey/model/host.py @@ -35,10 +35,10 @@ class VictimHost(object): def __str__(self): victim = "Victim Host %s: " % self.ip_addr victim += "OS - [" - for k, v in self.os.items(): + for k, v in list(self.os.items()): victim += "%s-%s " % (k, v) victim += "] Services - [" - for k, v in self.services.items(): + for k, v in list(self.services.items()): victim += "%s-%s " % (k, v) victim += '] ' victim += "target monkey: %s" % self.monkey_exe diff --git a/monkey/infection_monkey/monkey.py b/monkey/infection_monkey/monkey.py index af3a48bb2..0be24db3f 100644 --- a/monkey/infection_monkey/monkey.py +++ b/monkey/infection_monkey/monkey.py @@ -135,7 +135,7 @@ class InfectionMonkey(object): else: LOG.debug("Running with depth: %d" % WormConfiguration.depth) - for iteration_index in xrange(WormConfiguration.max_iterations): + for iteration_index in range(WormConfiguration.max_iterations): ControlClient.keepalive() ControlClient.load_control_config() diff --git a/monkey/infection_monkey/network/__init__.py b/monkey/infection_monkey/network/__init__.py index 59a6d01d6..33a6871e2 100644 --- a/monkey/infection_monkey/network/__init__.py +++ b/monkey/infection_monkey/network/__init__.py @@ -3,17 +3,13 @@ from abc import ABCMeta, abstractmethod, abstractproperty __author__ = 'itamar' -class HostScanner(object): - __metaclass__ = ABCMeta - +class HostScanner(object, metaclass=ABCMeta): @abstractmethod def is_host_alive(self, host): raise NotImplementedError() -class HostFinger(object): - __metaclass__ = ABCMeta - +class HostFinger(object, metaclass=ABCMeta): @abstractproperty def _SCANNED_SERVICE(self): pass diff --git a/monkey/infection_monkey/network/firewall.py b/monkey/infection_monkey/network/firewall.py index 678b6f67f..88171ecda 100644 --- a/monkey/infection_monkey/network/firewall.py +++ b/monkey/infection_monkey/network/firewall.py @@ -4,7 +4,7 @@ import platform def _run_netsh_cmd(command, args): - cmd = subprocess.Popen("netsh %s %s" % (command, " ".join(['%s="%s"' % (key, value) for key, value in args.items() + cmd = subprocess.Popen("netsh %s %s" % (command, " ".join(['%s="%s"' % (key, value) for key, value in list(args.items()) if value])), stdout=subprocess.PIPE) return cmd.stdout.read().strip().lower().endswith('ok.') @@ -81,17 +81,17 @@ class WinAdvFirewall(FirewallApp): if not self.is_enabled(): return True - for rule in self._rules.values(): + for rule in list(self._rules.values()): if rule.get('program') == sys.executable and \ 'in' == rule.get('dir') and \ 'allow' == rule.get('action') and \ - 4 == len(rule.keys()): + 4 == len(list(rule.keys())): return True return False def close(self): try: - for rule in self._rules.keys(): + for rule in list(self._rules.keys()): self.remove_firewall_rule({'name': rule}) except: pass @@ -151,14 +151,14 @@ class WinFirewall(FirewallApp): if not self.is_enabled(): return True - for rule in self._rules.values(): + for rule in list(self._rules.values()): if rule.get('program') == sys.executable and 'ENABLE' == rule.get('mode'): return True return False def close(self): try: - for rule in self._rules.values(): + for rule in list(self._rules.values()): self.remove_firewall_rule(**rule) except: pass diff --git a/monkey/infection_monkey/network/info.py b/monkey/infection_monkey/network/info.py index 952a9282e..c1e50586f 100644 --- a/monkey/infection_monkey/network/info.py +++ b/monkey/infection_monkey/network/info.py @@ -15,7 +15,7 @@ from requests import ConnectionError from common.network.network_range import CidrRange try: - long # Python 2 + int # Python 2 except NameError: long = int # Python 3 @@ -106,9 +106,9 @@ else: ifaddr = socket.inet_ntoa(ifreq[20:24]) else: continue - routes.append((socket.htonl(long(dst, 16)) & 0xffffffff, - socket.htonl(long(msk, 16)) & 0xffffffff, - socket.inet_ntoa(struct.pack("I", long(gw, 16))), + routes.append((socket.htonl(int(dst, 16)) & 0xffffffff, + socket.htonl(int(msk, 16)) & 0xffffffff, + socket.inet_ntoa(struct.pack("I", int(gw, 16))), iff, ifaddr)) f.close() @@ -158,7 +158,7 @@ def get_interfaces_ranges(): for net_interface in ifs: address_str = net_interface['addr'] netmask_str = net_interface['netmask'] - ip_interface = ipaddress.ip_interface(u"%s/%s" % (address_str, netmask_str)) + ip_interface = ipaddress.ip_interface("%s/%s" % (address_str, netmask_str)) # limit subnet scans to class C only res.append(CidrRange(cidr_range="%s/%s" % (address_str, netmask_str))) return res diff --git a/monkey/infection_monkey/network/network_scanner.py b/monkey/infection_monkey/network/network_scanner.py index 837add48a..e495b3ae7 100644 --- a/monkey/infection_monkey/network/network_scanner.py +++ b/monkey/infection_monkey/network/network_scanner.py @@ -48,13 +48,13 @@ class NetworkScanner(object): subnets_to_scan = [] if len(WormConfiguration.inaccessible_subnets) > 1: for subnet_str in WormConfiguration.inaccessible_subnets: - if NetworkScanner._is_any_ip_in_subnet([unicode(x) for x in self._ip_addresses], subnet_str): + if NetworkScanner._is_any_ip_in_subnet([str(x) for x in self._ip_addresses], subnet_str): # If machine has IPs from 2 different subnets in the same group, there's no point checking the other # subnet. for other_subnet_str in WormConfiguration.inaccessible_subnets: if other_subnet_str == subnet_str: continue - if not NetworkScanner._is_any_ip_in_subnet([unicode(x) for x in self._ip_addresses], + if not NetworkScanner._is_any_ip_in_subnet([str(x) for x in self._ip_addresses], other_subnet_str): subnets_to_scan.append(NetworkRange.get_range_obj(other_subnet_str)) break diff --git a/monkey/infection_monkey/network/smbfinger.py b/monkey/infection_monkey/network/smbfinger.py index e17bf4a56..b39ffef7a 100644 --- a/monkey/infection_monkey/network/smbfinger.py +++ b/monkey/infection_monkey/network/smbfinger.py @@ -19,14 +19,14 @@ class Packet(object): def __init__(self, **kw): self.fields = odict(self.__class__.fields) - for k, v in kw.items(): + for k, v in list(kw.items()): if callable(v): self.fields[k] = v(self.fields[k]) else: self.fields[k] = v def __str__(self): - return "".join(map(str, self.fields.values())) + return "".join(map(str, list(self.fields.values()))) ##### SMB Packets ##### diff --git a/monkey/infection_monkey/network/sshfinger.py b/monkey/infection_monkey/network/sshfinger.py index 56779bb8f..cc0849d19 100644 --- a/monkey/infection_monkey/network/sshfinger.py +++ b/monkey/infection_monkey/network/sshfinger.py @@ -36,7 +36,7 @@ class SSHFinger(HostFinger): def get_host_fingerprint(self, host): assert isinstance(host, VictimHost) - for name, data in host.services.items(): + for name, data in list(host.services.items()): banner = data.get('banner', '') if self._banner_regex.search(banner): self._banner_match(name, host, banner) diff --git a/monkey/infection_monkey/network/tcp_scanner.py b/monkey/infection_monkey/network/tcp_scanner.py index e76c08b46..2ea88842f 100644 --- a/monkey/infection_monkey/network/tcp_scanner.py +++ b/monkey/infection_monkey/network/tcp_scanner.py @@ -1,4 +1,4 @@ -from itertools import izip_longest +from itertools import zip_longest from random import shuffle import infection_monkey.config @@ -34,7 +34,7 @@ class TcpScanner(HostScanner, HostFinger): ports, banners = check_tcp_ports(host.ip_addr, target_ports, self._config.tcp_scan_timeout / 1000.0, self._config.tcp_scan_get_banner) - for target_port, banner in izip_longest(ports, banners, fillvalue=None): + for target_port, banner in zip_longest(ports, banners, fillvalue=None): service = tcp_port_to_service(target_port) self.init_service(host.services, service, target_port) if banner: diff --git a/monkey/infection_monkey/system_info/__init__.py b/monkey/infection_monkey/system_info/__init__.py index 56d7fca8b..02de3d1d4 100644 --- a/monkey/infection_monkey/system_info/__init__.py +++ b/monkey/infection_monkey/system_info/__init__.py @@ -34,10 +34,10 @@ class SystemInfoCollector(object): def __init__(self): self.os = SystemInfoCollector.get_os() if OperatingSystem.Windows == self.os: - from windows_info_collector import WindowsInfoCollector + from .windows_info_collector import WindowsInfoCollector self.collector = WindowsInfoCollector() else: - from linux_info_collector import LinuxInfoCollector + from .linux_info_collector import LinuxInfoCollector self.collector = LinuxInfoCollector() def get_info(self): diff --git a/monkey/infection_monkey/system_singleton.py b/monkey/infection_monkey/system_singleton.py index 9f56c238e..f7835ba20 100644 --- a/monkey/infection_monkey/system_singleton.py +++ b/monkey/infection_monkey/system_singleton.py @@ -10,9 +10,7 @@ __author__ = 'itamar' LOG = logging.getLogger(__name__) -class _SystemSingleton(object): - __metaclass__ = ABCMeta - +class _SystemSingleton(object, metaclass=ABCMeta): @property @abstractmethod def locked(self): diff --git a/monkey/infection_monkey/telemetry/base_telem.py b/monkey/infection_monkey/telemetry/base_telem.py index c232ab975..db0673f9d 100644 --- a/monkey/infection_monkey/telemetry/base_telem.py +++ b/monkey/infection_monkey/telemetry/base_telem.py @@ -5,13 +5,11 @@ from infection_monkey.control import ControlClient __author__ = 'itay.mizeretz' -class BaseTelem(object): +class BaseTelem(object, metaclass=abc.ABCMeta): """ Abstract base class for telemetry. """ - __metaclass__ = abc.ABCMeta - def __init__(self): pass diff --git a/monkey/infection_monkey/transport/http.py b/monkey/infection_monkey/transport/http.py index 0f01cf64a..16e92919f 100644 --- a/monkey/infection_monkey/transport/http.py +++ b/monkey/infection_monkey/transport/http.py @@ -1,11 +1,11 @@ -import BaseHTTPServer +import http.server import os.path import select import socket import threading -import urllib +import urllib.request, urllib.parse, urllib.error from logging import getLogger -from urlparse import urlsplit +from urllib.parse import urlsplit from threading import Lock import infection_monkey.monkeyfs as monkeyfs @@ -16,7 +16,7 @@ __author__ = 'hoffer' LOG = getLogger(__name__) -class FileServHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): +class FileServHTTPRequestHandler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" filename = "" @@ -61,7 +61,7 @@ class FileServHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): f.close() def send_head(self): - if self.path != '/' + urllib.quote(os.path.basename(self.filename)): + if self.path != '/' + urllib.parse.quote(os.path.basename(self.filename)): self.send_error(500, "") return None, 0, 0 f = None @@ -106,7 +106,7 @@ class FileServHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): format % args)) -class HTTPConnectProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): +class HTTPConnectProxyHandler(http.server.BaseHTTPRequestHandler): timeout = 30 # timeout with clients, set to None not to make persistent connection proxy_via = None # pseudonym of the proxy in Via header, set to None not to modify original Via header protocol_version = "HTTP/1.1" @@ -175,7 +175,7 @@ class HTTPServer(threading.Thread): return True return False - httpd = BaseHTTPServer.HTTPServer((self._local_ip, self._local_port), TempHandler) + httpd = http.server.HTTPServer((self._local_ip, self._local_port), TempHandler) httpd.timeout = 0.5 # this is irrelevant? while not self._stopped and self.downloads < self.max_downloads: @@ -222,7 +222,7 @@ class LockedHTTPServer(threading.Thread): return True return False - httpd = BaseHTTPServer.HTTPServer((self._local_ip, self._local_port), TempHandler) + httpd = http.server.HTTPServer((self._local_ip, self._local_port), TempHandler) self.lock.release() while not self._stopped and self.downloads < self.max_downloads: httpd.handle_request() @@ -236,7 +236,7 @@ class LockedHTTPServer(threading.Thread): class HTTPConnectProxy(TransportProxyBase): def run(self): - httpd = BaseHTTPServer.HTTPServer((self.local_host, self.local_port), HTTPConnectProxyHandler) + httpd = http.server.HTTPServer((self.local_host, self.local_port), HTTPConnectProxyHandler) httpd.timeout = 30 while not self._stopped: httpd.handle_request() diff --git a/monkey/monkey_island.py b/monkey/monkey_island.py index 104b5efdf..ff543a686 100644 --- a/monkey/monkey_island.py +++ b/monkey/monkey_island.py @@ -1,4 +1,4 @@ -import monkey_island.cc.main +from . import monkey_island.cc.main if "__main__" == __name__: monkey_island.cc.main.main() diff --git a/monkey/monkey_island/cc/app.py b/monkey/monkey_island/cc/app.py index 2e04ef0be..c6ad585df 100644 --- a/monkey/monkey_island/cc/app.py +++ b/monkey/monkey_island/cc/app.py @@ -64,16 +64,16 @@ def normalize_obj(obj): obj['id'] = obj['_id'] del obj['_id'] - for key, value in obj.items(): - if type(value) is bson.objectid.ObjectId: + for key, value in list(obj.items()): + if isinstance(value, bson.objectid.ObjectId): obj[key] = str(value) - if type(value) is datetime: + if isinstance(value, datetime): obj[key] = str(value) - if type(value) is dict: + if isinstance(value, dict): obj[key] = normalize_obj(value) - if type(value) is list: + if isinstance(value, list): for i in range(0, len(value)): - if type(value[i]) is dict: + if isinstance(value[i], dict): value[i] = normalize_obj(value[i]) return obj diff --git a/monkey/monkey_island/cc/environment/__init__.py b/monkey/monkey_island/cc/environment/__init__.py index 73cb813fe..0115cf446 100644 --- a/monkey/monkey_island/cc/environment/__init__.py +++ b/monkey/monkey_island/cc/environment/__init__.py @@ -6,9 +6,7 @@ from Crypto.Hash import SHA3_512 __author__ = 'itay.mizeretz' -class Environment(object): - __metaclass__ = abc.ABCMeta - +class Environment(object, metaclass=abc.ABCMeta): _ISLAND_PORT = 5000 _MONGO_DB_NAME = "monkeyisland" _MONGO_DB_HOST = "localhost" diff --git a/monkey/monkey_island/cc/main.py b/monkey/monkey_island/cc/main.py index 5b9bda8cb..e51975d24 100644 --- a/monkey/monkey_island/cc/main.py +++ b/monkey/monkey_island/cc/main.py @@ -1,4 +1,4 @@ -from __future__ import print_function # In python 2.7 + # In python 2.7 import os import os.path diff --git a/monkey/monkey_island/cc/models/__init__.py b/monkey/monkey_island/cc/models/__init__.py index 9d69a51fc..105866937 100644 --- a/monkey/monkey_island/cc/models/__init__.py +++ b/monkey/monkey_island/cc/models/__init__.py @@ -12,8 +12,8 @@ else: connect(db=env.mongo_db_name, host=env.mongo_db_host, port=env.mongo_db_port) # Order of importing matters here, for registering the embedded and referenced documents before using them. -from config import Config -from creds import Creds -from monkey_ttl import MonkeyTtl -from pba_results import PbaResults -from monkey import Monkey +from .config import Config +from .creds import Creds +from .monkey_ttl import MonkeyTtl +from .pba_results import PbaResults +from .monkey import Monkey diff --git a/monkey/monkey_island/cc/models/test_monkey.py b/monkey/monkey_island/cc/models/test_monkey.py index 717fb309a..37a71cfef 100644 --- a/monkey/monkey_island/cc/models/test_monkey.py +++ b/monkey/monkey_island/cc/models/test_monkey.py @@ -1,10 +1,10 @@ import uuid from time import sleep -from monkey import Monkey +from .monkey import Monkey from monkey_island.cc.models.monkey import MonkeyNotFoundError from monkey_island.cc.testing.IslandTestCase import IslandTestCase -from monkey_ttl import MonkeyTtl +from .monkey_ttl import MonkeyTtl class TestMonkey(IslandTestCase): @@ -87,6 +87,6 @@ class TestMonkey(IslandTestCase): windows_monkey.save() unknown_monkey.save() - self.assertEquals(1, len(filter(lambda m: m.get_os() == "windows", Monkey.objects()))) - self.assertEquals(1, len(filter(lambda m: m.get_os() == "linux", Monkey.objects()))) - self.assertEquals(1, len(filter(lambda m: m.get_os() == "unknown", Monkey.objects()))) + self.assertEqual(1, len([m for m in Monkey.objects() if m.get_os() == "windows"])) + self.assertEqual(1, len([m for m in Monkey.objects() if m.get_os() == "linux"])) + self.assertEqual(1, len([m for m in Monkey.objects() if m.get_os() == "unknown"])) diff --git a/monkey/monkey_island/cc/report_exporter_manager.py b/monkey/monkey_island/cc/report_exporter_manager.py index 5e51a43e1..c0e538258 100644 --- a/monkey/monkey_island/cc/report_exporter_manager.py +++ b/monkey/monkey_island/cc/report_exporter_manager.py @@ -14,9 +14,7 @@ class Singleton(type): return cls._instances[cls] -class ReportExporterManager(object): - __metaclass__ = Singleton - +class ReportExporterManager(object, metaclass=Singleton): def __init__(self): self._exporters_set = set() diff --git a/monkey/monkey_island/cc/services/attack/attack_config.py b/monkey/monkey_island/cc/services/attack/attack_config.py index 60df09d88..9f6b5d2d9 100644 --- a/monkey/monkey_island/cc/services/attack/attack_config.py +++ b/monkey/monkey_island/cc/services/attack/attack_config.py @@ -26,8 +26,8 @@ class AttackConfig(object): :return: Technique object or None if technique is not found """ attack_config = AttackConfig.get_config() - for key, attack_type in attack_config['properties'].items(): - for key, technique in attack_type['properties'].items(): + for key, attack_type in list(attack_config['properties'].items()): + for key, technique in list(attack_type['properties'].items()): if key == technique_id: return technique return None @@ -66,7 +66,7 @@ class AttackConfig(object): :param monkey_config: Monkey island's configuration :param monkey_schema: Monkey configuration schema """ - for key, definition in monkey_schema['definitions'].items(): + for key, definition in list(monkey_schema['definitions'].items()): for array_field in definition['anyOf']: # Check if current array field has attack_techniques assigned to it if 'attack_techniques' in array_field and array_field['attack_techniques']: @@ -83,7 +83,7 @@ class AttackConfig(object): :param monkey_config: Monkey island's configuration :param monkey_schema: Monkey configuration schema """ - for key, value in monkey_schema['properties'].items(): + for key, value in list(monkey_schema['properties'].items()): AttackConfig.r_set_booleans([key], value, attack_techniques, monkey_config) @staticmethod @@ -110,7 +110,7 @@ class AttackConfig(object): dictionary = value['properties'] else: dictionary = value - for key, item in dictionary.items(): + for key, item in list(dictionary.items()): path.append(key) AttackConfig.r_set_booleans(path, item, attack_techniques, monkey_config) # Method enumerated everything in current path, goes back a level. @@ -158,7 +158,7 @@ class AttackConfig(object): elif not remove and field not in config_value[array_name]: config_value[array_name].append(field) else: - for prop in config_value.items(): + for prop in list(config_value.items()): AttackConfig.r_alter_array(prop[1], array_name, field, remove) @staticmethod @@ -169,7 +169,7 @@ class AttackConfig(object): """ attack_config = AttackConfig.get_config() techniques = {} - for type_name, attack_type in attack_config['properties'].items(): - for key, technique in attack_type['properties'].items(): + for type_name, attack_type in list(attack_config['properties'].items()): + for key, technique in list(attack_type['properties'].items()): techniques[key] = technique['value'] return techniques diff --git a/monkey/monkey_island/cc/services/attack/attack_report.py b/monkey/monkey_island/cc/services/attack/attack_report.py index 7004e3721..89a384e9d 100644 --- a/monkey/monkey_island/cc/services/attack/attack_report.py +++ b/monkey/monkey_island/cc/services/attack/attack_report.py @@ -41,7 +41,7 @@ class AttackReportService: 'name': REPORT_NAME } - for tech_id, value in AttackConfig.get_technique_values().items(): + for tech_id, value in list(AttackConfig.get_technique_values().items()): if value: try: report['techniques'].update({tech_id: TECHNIQUES[tech_id].get_report_data()}) diff --git a/monkey/monkey_island/cc/services/attack/technique_reports/T1110.py b/monkey/monkey_island/cc/services/attack/technique_reports/T1110.py index 91d785bc3..a9bd24e70 100644 --- a/monkey/monkey_island/cc/services/attack/technique_reports/T1110.py +++ b/monkey/monkey_island/cc/services/attack/technique_reports/T1110.py @@ -59,7 +59,7 @@ class T1110(AttackTechnique): 'ntlm_hash': {'type': 'NTLM hash', 'output': T1110.censor_hash(attempt['ntlm_hash'], 20)}, 'ssh_key': {'type': 'SSH key', 'output': attempt['ssh_key']}, 'password': {'type': 'Plaintext password', 'output': T1110.censor_password(attempt['password'])}} - for key, cred in creds.items(): + for key, cred in list(creds.items()): if attempt[key]: return '%s ; %s : %s' % (username, cred['type'], diff --git a/monkey/monkey_island/cc/services/attack/technique_reports/__init__.py b/monkey/monkey_island/cc/services/attack/technique_reports/__init__.py index edd180d50..cc4d13355 100644 --- a/monkey/monkey_island/cc/services/attack/technique_reports/__init__.py +++ b/monkey/monkey_island/cc/services/attack/technique_reports/__init__.py @@ -6,9 +6,8 @@ from monkey_island.cc.services.attack.attack_config import AttackConfig from common.utils.code_utils import abstractstatic -class AttackTechnique(object): +class AttackTechnique(object, metaclass=abc.ABCMeta): """ Abstract class for ATT&CK report components """ - __metaclass__ = abc.ABCMeta @abc.abstractproperty def unscanned_msg(self): diff --git a/monkey/monkey_island/cc/services/config.py b/monkey/monkey_island/cc/services/config.py index c52ceb3f4..8e6c9b2fa 100644 --- a/monkey/monkey_island/cc/services/config.py +++ b/monkey/monkey_island/cc/services/config.py @@ -10,7 +10,7 @@ from monkey_island.cc.database import mongo from monkey_island.cc.encryptor import encryptor from monkey_island.cc.environment.environment import env from monkey_island.cc.utils import local_ip_addresses -from config_schema import SCHEMA +from .config_schema import SCHEMA __author__ = "itay.mizeretz" @@ -203,11 +203,11 @@ class ConfigService: # Do it only for root. if instance != {}: return - for property, subschema in properties.iteritems(): + for property, subschema in properties.items(): main_dict = {} - for property2, subschema2 in subschema["properties"].iteritems(): + for property2, subschema2 in subschema["properties"].items(): sub_dict = {} - for property3, subschema3 in subschema2["properties"].iteritems(): + for property3, subschema3 in subschema2["properties"].items(): if "default" in subschema3: sub_dict[property3] = subschema3["default"] main_dict[property2] = sub_dict diff --git a/monkey/monkey_island/cc/services/config_schema.py b/monkey/monkey_island/cc/services/config_schema.py index cd417f8e4..333c42263 100644 --- a/monkey/monkey_island/cc/services/config_schema.py +++ b/monkey/monkey_island/cc/services/config_schema.py @@ -1,4 +1,4 @@ -WARNING_SIGN = u" \u26A0" +WARNING_SIGN = " \u26A0" SCHEMA = { "title": "Monkey", diff --git a/monkey/monkey_island/cc/services/edge.py b/monkey/monkey_island/cc/services/edge.py index eb23c3901..c328deee2 100644 --- a/monkey/monkey_island/cc/services/edge.py +++ b/monkey/monkey_island/cc/services/edge.py @@ -151,7 +151,7 @@ class EdgeService: else: to_label = NodeService.get_monkey_label(to_id) - RIGHT_ARROW = u"\u2192" + RIGHT_ARROW = "\u2192" return "%s %s %s" % (from_label, RIGHT_ARROW, to_label) diff --git a/monkey/monkey_island/cc/services/mimikatz_utils.py b/monkey/monkey_island/cc/services/mimikatz_utils.py index 9aca91a59..4b88473fe 100644 --- a/monkey/monkey_island/cc/services/mimikatz_utils.py +++ b/monkey/monkey_island/cc/services/mimikatz_utils.py @@ -16,8 +16,8 @@ class MimikatzSecrets(object): return {} for sam_user_txt in users_secrets: - sam_user = dict([map(unicode.strip, line.split(":")) for line in - filter(lambda l: l.count(":") == 1, sam_user_txt.splitlines())]) + sam_user = dict([list(map(str.strip, line.split(":"))) for line in + [l for l in sam_user_txt.splitlines() if l.count(":") == 1]]) username = sam_user.get("User") users_dict[username] = {} diff --git a/monkey/monkey_island/cc/services/pth_report.py b/monkey/monkey_island/cc/services/pth_report.py index 9f3b9769f..5e77b6395 100644 --- a/monkey/monkey_island/cc/services/pth_report.py +++ b/monkey/monkey_island/cc/services/pth_report.py @@ -217,7 +217,7 @@ class PTHReportService(object): @staticmethod def generate_map_nodes(): - monkeys = filter(lambda m: m.get_os() == "windows", Monkey.objects()) + monkeys = [m for m in Monkey.objects() if m.get_os() == "windows"] return [ { diff --git a/monkey/monkey_island/cc/services/report.py b/monkey/monkey_island/cc/services/report.py index 593bbfdaf..e49e60d81 100644 --- a/monkey/monkey_island/cc/services/report.py +++ b/monkey/monkey_island/cc/services/report.py @@ -16,7 +16,7 @@ from monkey_island.cc.services.config import ConfigService from monkey_island.cc.services.edge import EdgeService from monkey_island.cc.services.node import NodeService from monkey_island.cc.utils import local_ip_addresses, get_subnets -from pth_report import PTHReportService +from .pth_report import PTHReportService from common.network.network_range import NetworkRange __author__ = "itay.mizeretz" diff --git a/monkey/monkey_island/cc/services/test_PTHReportService.py b/monkey/monkey_island/cc/services/test_PTHReportService.py index 24e560ff0..7c4d4229b 100644 --- a/monkey/monkey_island/cc/services/test_PTHReportService.py +++ b/monkey/monkey_island/cc/services/test_PTHReportService.py @@ -40,7 +40,7 @@ class TestPTHReportServiceGenerateMapNodes(IslandTestCase): map_nodes = PTHReportService.generate_map_nodes() - self.assertEquals(2, len(map_nodes)) + self.assertEqual(2, len(map_nodes)) def test_generate_map_nodes_parsing(self): self.fail_if_not_testing_env() @@ -59,11 +59,11 @@ class TestPTHReportServiceGenerateMapNodes(IslandTestCase): map_nodes = PTHReportService.generate_map_nodes() - self.assertEquals(map_nodes[0]["id"], monkey_id) - self.assertEquals(map_nodes[0]["label"], "A_Windows_PC_1 : 1.1.1.1") - self.assertEquals(map_nodes[0]["group"], "critical") - self.assertEquals(len(map_nodes[0]["services"]), 2) - self.assertEquals(map_nodes[0]["hostname"], hostname) + self.assertEqual(map_nodes[0]["id"], monkey_id) + self.assertEqual(map_nodes[0]["label"], "A_Windows_PC_1 : 1.1.1.1") + self.assertEqual(map_nodes[0]["group"], "critical") + self.assertEqual(len(map_nodes[0]["services"]), 2) + self.assertEqual(map_nodes[0]["hostname"], hostname) diff --git a/monkey/monkey_island/cc/services/wmi_handler.py b/monkey/monkey_island/cc/services/wmi_handler.py index 227bd18da..82209701f 100644 --- a/monkey/monkey_island/cc/services/wmi_handler.py +++ b/monkey/monkey_island/cc/services/wmi_handler.py @@ -95,7 +95,7 @@ class WMIHandler(object): groups_entities_list = self.info_for_mongo[group_sid]['entities_list'] child_sid = '' - if type(child_part) in (unicode, str): + if type(child_part) in (str, str): child_part = str(child_part) name = None domain_name = None @@ -124,7 +124,7 @@ class WMIHandler(object): self.info_for_mongo[child_sid]['member_of'].append(group_sid) def insert_info_to_mongo(self): - for entity in self.info_for_mongo.values(): + for entity in list(self.info_for_mongo.values()): if entity['machine_id']: # Handling for local entities. mongo.db.groupsandusers.update({'SID': entity['SID'], diff --git a/monkey/monkey_island/cc/testing/IslandTestCase.py b/monkey/monkey_island/cc/testing/IslandTestCase.py index e894f13df..1c708279e 100644 --- a/monkey/monkey_island/cc/testing/IslandTestCase.py +++ b/monkey/monkey_island/cc/testing/IslandTestCase.py @@ -5,7 +5,7 @@ from monkey_island.cc.models import Monkey class IslandTestCase(unittest.TestCase): def fail_if_not_testing_env(self): - self.failIf(not env.testing, "Change server_config.json to testing environment.") + self.assertFalse(not env.testing, "Change server_config.json to testing environment.") @staticmethod def clean_monkey_db():