From 8c4288d100ebbdccd1184787dd0ebbea531d7d57 Mon Sep 17 00:00:00 2001 From: acepace Date: Sat, 20 Aug 2016 17:58:59 +0300 Subject: [PATCH] PEP8 changes --- chaos_monkey/main.py | 36 +++++----- chaos_monkey/monkey.py | 4 +- chaos_monkey/network/firewall.py | 29 ++++---- chaos_monkey/network/info.py | 12 ++-- chaos_monkey/network/network_scanner.py | 6 +- chaos_monkey/network/range.py | 2 +- chaos_monkey/network/smbfinger.py | 67 ++++++++++--------- chaos_monkey/network/sshfinger.py | 3 +- chaos_monkey/network/tcp_scanner.py | 10 +-- chaos_monkey/network/tools.py | 2 +- chaos_monkey/system_info/__init__.py | 27 ++++---- .../system_info/linux_info_collector.py | 1 - 12 files changed, 106 insertions(+), 93 deletions(-) diff --git a/chaos_monkey/main.py b/chaos_monkey/main.py index 6689ad3e7..2cc4ed484 100644 --- a/chaos_monkey/main.py +++ b/chaos_monkey/main.py @@ -19,19 +19,20 @@ LOG = None LOG_CONFIG = {'version': 1, 'disable_existing_loggers': False, - 'formatters': {'standard': {'format': '%(asctime)s [%(process)d:%(levelname)s] %(module)s.%(funcName)s.%(lineno)d: %(message)s'}, - }, + 'formatters': {'standard': { + 'format': '%(asctime)s [%(process)d:%(levelname)s] %(module)s.%(funcName)s.%(lineno)d: %(message)s'}, + }, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'standard'}, - 'file': {'class': 'logging.FileHandler', - 'level': 'DEBUG', - 'formatter': 'standard', - 'filename': None} - }, + 'file': {'class': 'logging.FileHandler', + 'level': 'DEBUG', + 'formatter': 'standard', + 'filename': None} + }, 'root': {'level': 'DEBUG', 'handlers': ['console']}, - } + } def main(): @@ -42,7 +43,7 @@ def main(): monkey_mode = sys.argv[1] - if not monkey_mode in [MONKEY_ARG, DROPPER_ARG]: + if not (monkey_mode in [MONKEY_ARG, DROPPER_ARG]): return True config_file = EXTERNAL_CONFIG_FILE @@ -66,7 +67,7 @@ def main(): print "Loaded Configuration: %r" % WormConfiguration.as_dict() - #Make sure we're not in a machine that has the kill file + # Make sure we're not in a machine that has the kill file kill_path = WormConfiguration.kill_file_path_windows if sys.platform == "win32" else WormConfiguration.kill_file_path_linux if os.path.exists(kill_path): print "Kill path found, finished run" @@ -74,10 +75,12 @@ def main(): try: if MONKEY_ARG == monkey_mode: - log_path = os.path.expandvars(WormConfiguration.monkey_log_path_windows) if sys.platform == "win32" else WormConfiguration.monkey_log_path_linux + log_path = os.path.expandvars( + WormConfiguration.monkey_log_path_windows) if sys.platform == "win32" else WormConfiguration.monkey_log_path_linux monkey_cls = ChaosMonkey elif DROPPER_ARG == monkey_mode: - log_path = os.path.expandvars(WormConfiguration.dropper_log_path_windows) if sys.platform == "win32" else WormConfiguration.dropper_log_path_linux + log_path = os.path.expandvars( + WormConfiguration.dropper_log_path_windows) if sys.platform == "win32" else WormConfiguration.dropper_log_path_linux monkey_cls = MonkeyDrops else: return True @@ -109,14 +112,15 @@ def main(): monkey.start() if WormConfiguration.serialize_config: - with open(config_file, 'w') as config_fo: - json_dict = WormConfiguration.as_dict() - json.dump(json_dict, config_fo, skipkeys=True, sort_keys=True, indent=4, separators=(',', ': ')) - + with open(config_file, 'w') as config_fo: + json_dict = WormConfiguration.as_dict() + json.dump(json_dict, config_fo, skipkeys=True, sort_keys=True, indent=4, separators=(',', ': ')) + return True finally: monkey.cleanup() + if "__main__" == __name__: if not main(): sys.exit(1) diff --git a/chaos_monkey/monkey.py b/chaos_monkey/monkey.py index c99c0daf8..dd14a8fe0 100644 --- a/chaos_monkey/monkey.py +++ b/chaos_monkey/monkey.py @@ -143,7 +143,6 @@ class ChaosMonkey(object): LOG.debug("Skipping %r - exploitation failed before", machine) continue - successful_exploiter = None if monkey_tunnel: monkey_tunnel.set_tunnel_for_host(machine) @@ -151,6 +150,7 @@ class ChaosMonkey(object): LOG.debug("Default server: %s set to machine: %r" % (self._default_server, machine)) machine.set_default_server(self._default_server) + successful_exploiter = None for exploiter in self._exploiters: if not exploiter.is_os_supported(machine): LOG.info("Skipping exploiter %s host:%r, os is not supported", @@ -240,4 +240,4 @@ class ChaosMonkey(object): except Exception, exc: LOG.error("Exception in self delete: %s", exc) - LOG.info("Monkey is shutting down") \ No newline at end of file + LOG.info("Monkey is shutting down") diff --git a/chaos_monkey/network/firewall.py b/chaos_monkey/network/firewall.py index 21c05203b..54c8a1870 100644 --- a/chaos_monkey/network/firewall.py +++ b/chaos_monkey/network/firewall.py @@ -51,9 +51,9 @@ class WinAdvFirewall(FirewallApp): def add_firewall_rule(self, name="Firewall", dir="in", action="allow", program=sys.executable, **kwargs): netsh_args = {'name': name, - 'dir' : dir, + 'dir': dir, 'action': action, - 'program' : program} + 'program': program} netsh_args.update(kwargs) try: if _run_netsh_cmd('advfirewall firewall add rule', netsh_args): @@ -70,7 +70,7 @@ class WinAdvFirewall(FirewallApp): try: if _run_netsh_cmd('advfirewall firewall delete rule', netsh_args): - if self._rules.has_key(name): + if name in self._rules: del self._rules[name] return True else: @@ -93,7 +93,7 @@ class WinAdvFirewall(FirewallApp): def close(self): try: for rule in self._rules.keys(): - _run_netsh_cmd('advfirewall firewall delete rule', {'name' : rule}) + _run_netsh_cmd('advfirewall firewall delete rule', {'name': rule}) except: pass @@ -117,10 +117,11 @@ class WinFirewall(FirewallApp): except: return None - def add_firewall_rule(self, rule='allowedprogram', name="Firewall", mode="ENABLE", program=sys.executable, **kwargs): + def add_firewall_rule(self, rule='allowedprogram', name="Firewall", mode="ENABLE", program=sys.executable, + **kwargs): netsh_args = {'name': name, - 'mode' : mode, - 'program' : program} + 'mode': mode, + 'program': program} netsh_args.update(kwargs) try: @@ -129,20 +130,21 @@ class WinFirewall(FirewallApp): self._rules[name] = netsh_args return True else: - return False + return False except: return None - def remove_firewall_rule(self, rule='allowedprogram', name="Firewall", mode="ENABLE", program=sys.executable, **kwargs): - netsh_args = {'program' : program} + def remove_firewall_rule(self, rule='allowedprogram', name="Firewall", mode="ENABLE", program=sys.executable, + **kwargs): + netsh_args = {'program': program} netsh_args.update(kwargs) try: if _run_netsh_cmd('firewall delete %s' % rule, netsh_args): - if self._rules.has_key(name): + if name in self._rules: del self._rules[name] return True else: - return False + return False except: return None @@ -153,7 +155,7 @@ class WinFirewall(FirewallApp): for rule in self._rules.values(): if rule.get('program') == sys.executable and 'ENABLE' == rule.get('mode'): return True - return False + return False def close(self): try: @@ -162,6 +164,7 @@ class WinFirewall(FirewallApp): except: pass + if sys.platform == "win32": try: win_ver = int(platform.version().split('.')[0]) diff --git a/chaos_monkey/network/info.py b/chaos_monkey/network/info.py index 22c340979..9d7f2861e 100644 --- a/chaos_monkey/network/info.py +++ b/chaos_monkey/network/info.py @@ -10,10 +10,12 @@ from random import randint if sys.platform == "win32": import netifaces + def local_ips(): local_hostname = socket.gethostname() return socket.gethostbyname_ex(local_hostname)[2] + def get_host_subnets(only_ips=False): network_adapters = [] valid_ips = local_ips() @@ -28,11 +30,11 @@ if sys.platform == "win32": return network_adapters else: - import fcntl + import fcntl + def get_host_subnets(only_ips=False): """Get the list of Linux network adapters.""" - import fcntl max_bytes = 8096 is_64bits = sys.maxsize > 2 ** 32 if is_64bits: @@ -77,12 +79,12 @@ else: def get_free_tcp_port(min_range=1000, max_range=65535): start_range = min(1, min_range) max_range = min(65535, max_range) - + in_use = [conn.laddr[1] for conn in psutil.net_connections()] for i in range(min_range, max_range): port = randint(start_range, max_range) - + if port not in in_use: return port @@ -104,7 +106,7 @@ def get_ips_from_interfaces(): ipint = ipaddress.ip_interface(u"%s/%s" % interface) # limit subnet scans to class C only if ipint.network.num_addresses > 255: - ipint = ipaddress.ip_interface(u"%s/24" % interface[0]) + ipint = ipaddress.ip_interface(u"%s/24" % interface[0]) for addr in ipint.network.hosts(): if str(addr) == interface[0]: continue diff --git a/chaos_monkey/network/network_scanner.py b/chaos_monkey/network/network_scanner.py index 9c03ca4b8..143057974 100644 --- a/chaos_monkey/network/network_scanner.py +++ b/chaos_monkey/network/network_scanner.py @@ -41,9 +41,9 @@ class NetworkScanner(object): scanner = scan_type() victims_count = 0 - for range in self._ranges: - LOG.debug("Scanning for potential victims in the network %r", range) - for victim in range: + for net_range in self._ranges: + LOG.debug("Scanning for potential victims in the network %r", net_range) + for victim in net_range: if stop_callback and stop_callback(): LOG.debug("Got stop signal") break diff --git a/chaos_monkey/network/range.py b/chaos_monkey/network/range.py index f62e895d1..5163a6aad 100644 --- a/chaos_monkey/network/range.py +++ b/chaos_monkey/network/range.py @@ -49,7 +49,7 @@ class RelativeRange(NetworkRange): def __repr__(self): return "" % (socket.inet_ntoa(struct.pack(">L", self._base_address - self._size)), - socket.inet_ntoa(struct.pack(">L", self._base_address + self._size))) + socket.inet_ntoa(struct.pack(">L", self._base_address + self._size))) def _get_range(self): lower_end = -(self._size / 2) diff --git a/chaos_monkey/network/smbfinger.py b/chaos_monkey/network/smbfinger.py index 608f9bea3..bf8e5bfec 100644 --- a/chaos_monkey/network/smbfinger.py +++ b/chaos_monkey/network/smbfinger.py @@ -18,7 +18,7 @@ class Packet(object): def __init__(self, **kw): self.fields = odict(self.__class__.fields) - for k,v in kw.items(): + for k, v in kw.items(): if callable(v): self.fields[k] = v(self.fields[k]) else: @@ -52,43 +52,45 @@ class SMBNego(Packet): ("bcc", "\x62\x00"), ("data", "") ]) - + def calculate(self): - self.fields["bcc"] = struct.pack("i", len(''.join(Packet)))+Packet + + Packet = str(h) + str(n) + Buffer = struct.pack(">i", len(''.join(Packet))) + Packet s.send(Buffer) data = s.recv(2048) - + if data[8:10] == "\x72\x00": - Header = SMBHeader(cmd="\x73",flag1="\x18",flag2="\x17\xc8",uid="\x00\x00") + Header = SMBHeader(cmd="\x73", flag1="\x18", flag2="\x17\xc8", uid="\x00\x00") Body = SMBSessionFingerData() Body.calculate() - Packet = str(Header)+str(Body) - Buffer = struct.pack(">i", len(''.join(Packet)))+Packet + Packet = str(Header) + str(Body) + Buffer = struct.pack(">i", len(''.join(Packet))) + Packet - s.send(Buffer) + s.send(Buffer) data = s.recv(2048) if data[8:10] == "\x73\x16": - length = struct.unpack('