Variable names and const location fixes

This commit is contained in:
Shay Nehmad 2019-10-28 16:15:31 +02:00
parent cd3835a42e
commit 4b0ea4aed7
10 changed files with 31 additions and 33 deletions

View File

@ -304,7 +304,7 @@ class ControlClient(object):
try: try:
target_addr, target_port = my_proxy.split(':', 1) target_addr, target_port = my_proxy.split(':', 1)
target_port = int(target_port) target_port = int(target_port)
except: except ValueError:
return None return None
else: else:
proxy_class = HTTPConnectProxy proxy_class = HTTPConnectProxy

View File

@ -26,6 +26,7 @@ else:
try: try:
WindowsError WindowsError
except NameError: except NameError:
# noinspection PyShadowingBuiltins
WindowsError = IOError WindowsError = IOError
__author__ = 'itamar' __author__ = 'itamar'
@ -103,14 +104,14 @@ class MonkeyDrops(object):
dropper_date_reference_path = WormConfiguration.dropper_date_reference_path_linux dropper_date_reference_path = WormConfiguration.dropper_date_reference_path_linux
try: try:
ref_stat = os.stat(dropper_date_reference_path) ref_stat = os.stat(dropper_date_reference_path)
except OSError as exc: except OSError:
LOG.warning("Cannot set reference date using '%s', file not found", LOG.warning("Cannot set reference date using '%s', file not found",
dropper_date_reference_path) dropper_date_reference_path)
else: else:
try: try:
os.utime(self._config['destination_path'], os.utime(self._config['destination_path'],
(ref_stat.st_atime, ref_stat.st_mtime)) (ref_stat.st_atime, ref_stat.st_mtime))
except: except OSError:
LOG.warning("Cannot set reference date to destination file") LOG.warning("Cannot set reference date to destination file")
monkey_options =\ monkey_options =\

View File

@ -25,7 +25,7 @@ class FirewallApp(object):
def __enter__(self): def __enter__(self):
return self return self
def __exit__(self, type, value, traceback): def __exit__(self, exc_type, value, traceback):
self.close() self.close()
def close(self): def close(self):
@ -49,9 +49,9 @@ class WinAdvFirewall(FirewallApp):
except: except:
return None return None
def add_firewall_rule(self, name="Firewall", dir="in", action="allow", program=sys.executable, **kwargs): def add_firewall_rule(self, name="Firewall", direction="in", action="allow", program=sys.executable, **kwargs):
netsh_args = {'name': name, netsh_args = {'name': name,
'dir': dir, 'dir': direction,
'action': action, 'action': action,
'program': program} 'program': program}
netsh_args.update(kwargs) netsh_args.update(kwargs)

View File

@ -16,6 +16,11 @@ from infection_monkey.utils.environment import is_windows_os
# Timeout for monkey connections # Timeout for monkey connections
TIMEOUT = 15 TIMEOUT = 15
LOOPBACK_NAME = b"lo"
SIOCGIFADDR = 0x8915 # get PA address
SIOCGIFNETMASK = 0x891b # get network PA mask
RTF_UP = 0x0001 # Route usable
RTF_REJECT = 0x0200
def get_host_subnets(): def get_host_subnets():
@ -62,12 +67,6 @@ else:
def get_routes(): # based on scapy implementation for route parsing def get_routes(): # based on scapy implementation for route parsing
LOOPBACK_NAME = b"lo"
SIOCGIFADDR = 0x8915 # get PA address
SIOCGIFNETMASK = 0x891b # get network PA mask
RTF_UP = 0x0001 # Route usable
RTF_REJECT = 0x0200
try: try:
f = open("/proc/net/route", "r") f = open("/proc/net/route", "r")
except IOError: except IOError:

View File

@ -64,7 +64,6 @@ class FileServHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
if self.path != '/' + urllib.parse.quote(os.path.basename(self.filename)): if self.path != '/' + urllib.parse.quote(os.path.basename(self.filename)):
self.send_error(500, "") self.send_error(500, "")
return None, 0, 0 return None, 0, 0
f = None
try: try:
f = monkeyfs.open(self.filename, 'rb') f = monkeyfs.open(self.filename, 'rb')
except IOError: except IOError:
@ -100,10 +99,10 @@ class FileServHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
return f, start_range, end_range return f, start_range, end_range
def log_message(self, format, *args): def log_message(self, format_string, *args):
LOG.debug("FileServHTTPRequestHandler: %s - - [%s] %s" % (self.address_string(), LOG.debug("FileServHTTPRequestHandler: %s - - [%s] %s" % (self.address_string(),
self.log_date_time_string(), self.log_date_time_string(),
format % args)) format_string % args))
class HTTPConnectProxyHandler(http.server.BaseHTTPRequestHandler): class HTTPConnectProxyHandler(http.server.BaseHTTPRequestHandler):
@ -117,7 +116,6 @@ class HTTPConnectProxyHandler(http.server.BaseHTTPRequestHandler):
def do_CONNECT(self): def do_CONNECT(self):
# just provide a tunnel, transfer the data with no modification # just provide a tunnel, transfer the data with no modification
req = self req = self
reqbody = None
req.path = "https://%s/" % req.path.replace(':443', '') req.path = "https://%s/" % req.path.replace(':443', '')
u = urlsplit(req.path) u = urlsplit(req.path)
@ -148,9 +146,9 @@ class HTTPConnectProxyHandler(http.server.BaseHTTPRequestHandler):
update_last_serve_time() update_last_serve_time()
conn.close() conn.close()
def log_message(self, format, *args): def log_message(self, format_string, *args):
LOG.debug("HTTPConnectProxyHandler: %s - [%s] %s" % LOG.debug("HTTPConnectProxyHandler: %s - [%s] %s" %
(self.address_string(), self.log_date_time_string(), format % args)) (self.address_string(), self.log_date_time_string(), format_string % args))
class HTTPServer(threading.Thread): class HTTPServer(threading.Thread):

View File

@ -34,8 +34,8 @@ def load_server_configuration_from_file():
def load_env_from_file(): def load_env_from_file():
config_json = load_server_configuration_from_file() loaded_config_json = load_server_configuration_from_file()
return config_json['server_config'] return loaded_config_json['server_config']
try: try:

View File

@ -132,7 +132,7 @@ def is_monkey(object_id):
try: try:
_ = Monkey.get_single_monkey_by_id(object_id) _ = Monkey.get_single_monkey_by_id(object_id)
return True return True
except: except MonkeyNotFoundError:
return False return False

View File

@ -144,7 +144,7 @@ class ConfigService:
if should_encrypt: if should_encrypt:
try: try:
ConfigService.encrypt_config(config_json) ConfigService.encrypt_config(config_json)
except KeyError as e: except KeyError:
logger.error('Bad configuration file was submitted.') logger.error('Bad configuration file was submitted.')
return False return False
mongo.db.config.update({'name': 'newconfig'}, {"$set": config_json}, upsert=True) mongo.db.config.update({'name': 'newconfig'}, {"$set": config_json}, upsert=True)
@ -154,9 +154,9 @@ class ConfigService:
@staticmethod @staticmethod
def init_default_config(): def init_default_config():
if ConfigService.default_config is None: if ConfigService.default_config is None:
defaultValidatingDraft4Validator = ConfigService._extend_config_with_default(Draft4Validator) default_validating_draft4_validator = ConfigService._extend_config_with_default(Draft4Validator)
config = {} config = {}
defaultValidatingDraft4Validator(SCHEMA).validate(config) default_validating_draft4_validator(SCHEMA).validate(config)
ConfigService.default_config = config ConfigService.default_config = config
@staticmethod @staticmethod
@ -207,15 +207,15 @@ class ConfigService:
# Do it only for root. # Do it only for root.
if instance != {}: if instance != {}:
return return
for property, subschema in list(properties.items()): for property1, subschema1 in list(properties.items()):
main_dict = {} main_dict = {}
for property2, subschema2 in list(subschema["properties"].items()): for property2, subschema2 in list(subschema1["properties"].items()):
sub_dict = {} sub_dict = {}
for property3, subschema3 in list(subschema2["properties"].items()): for property3, subschema3 in list(subschema2["properties"].items()):
if "default" in subschema3: if "default" in subschema3:
sub_dict[property3] = subschema3["default"] sub_dict[property3] = subschema3["default"]
main_dict[property2] = sub_dict main_dict[property2] = sub_dict
instance.setdefault(property, main_dict) instance.setdefault(property1, main_dict)
for error in validate_properties(validator, properties, instance, schema): for error in validate_properties(validator, properties, instance, schema):
yield error yield error

View File

@ -141,7 +141,7 @@ class EdgeService:
@staticmethod @staticmethod
def get_edge_label(edge): def get_edge_label(edge):
NodeService = monkey_island.cc.services.node.NodeService node_service = monkey_island.cc.services.node.NodeService
from_id = edge["from"] from_id = edge["from"]
to_id = edge["to"] to_id = edge["to"]
@ -153,9 +153,9 @@ class EdgeService:
if is_monkey(to_id): if is_monkey(to_id):
to_label = get_monkey_label_by_id(to_id) to_label = get_monkey_label_by_id(to_id)
else: else:
to_label = NodeService.get_node_label(NodeService.get_node_by_id(to_id)) to_label = node_service.get_node_label(node_service.get_node_by_id(to_id))
RIGHT_ARROW = "\u2192"
return "%s %s %s" % (from_label, RIGHT_ARROW, to_label) return "%s %s %s" % (from_label, RIGHT_ARROW, to_label)
RIGHT_ARROW = "\u2192"

View File

@ -56,9 +56,9 @@ class NodeService:
accessible_from_nodes.append(from_node_label) accessible_from_nodes.append(from_node_label)
accessible_from_nodes_hostnames.append(from_node_hostname) accessible_from_nodes_hostnames.append(from_node_hostname)
for exploit in edge["exploits"]: for edge_exploit in edge["exploits"]:
exploit["origin"] = from_node_label edge_exploit["origin"] = from_node_label
exploits.append(exploit) exploits.append(edge_exploit)
exploits = sorted(exploits, key=lambda exploit: exploit['timestamp']) exploits = sorted(exploits, key=lambda exploit: exploit['timestamp'])