monkey/chaos_monkey/network/range.py

72 lines
2.4 KiB
Python
Raw Normal View History

2015-08-30 15:27:35 +08:00
import socket
import random
import struct
from abc import ABCMeta, abstractmethod
2015-11-30 20:11:19 +08:00
from model.host import VictimHost
2015-08-30 15:27:35 +08:00
__author__ = 'itamar'
2015-08-30 15:27:35 +08:00
class NetworkRange(object):
__metaclass__ = ABCMeta
def __init__(self, base_address, shuffle=True):
self._base_address = base_address
self._shuffle = shuffle
self._config = __import__('config').WormConfiguration
@abstractmethod
def _get_range(self):
raise NotImplementedError()
def __iter__(self):
base_range = self._get_range()
if self._shuffle:
random.shuffle(base_range)
for x in base_range:
yield VictimHost(socket.inet_ntoa(struct.pack(">L", self._base_address + x)))
class ClassCRange(NetworkRange):
def __init__(self, base_address, shuffle=True):
base_address = struct.unpack(">L", socket.inet_aton(base_address))[0] & 0xFFFFFF00
super(ClassCRange, self).__init__(base_address, shuffle=shuffle)
def __repr__(self):
return "<ClassCRange %s-%s>" % (socket.inet_ntoa(struct.pack(">L", self._base_address + 1)),
2015-11-30 16:56:20 +08:00
socket.inet_ntoa(struct.pack(">L", self._base_address + 254)))
2015-08-30 15:27:35 +08:00
def _get_range(self):
return range(1, 254)
class RelativeRange(NetworkRange):
def __init__(self, base_address, shuffle=True):
base_address = struct.unpack(">L", socket.inet_aton(base_address))[0]
super(RelativeRange, self).__init__(base_address, shuffle=shuffle)
self._size = self._config.range_size
def __repr__(self):
return "<RelativeRange %s-%s>" % (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):
2016-01-13 16:27:49 +08:00
lower_end = -(self._size / 2)
higher_end = lower_end + self._size
return range(lower_end, higher_end + 1)
2015-08-30 15:27:35 +08:00
class FixedRange(NetworkRange):
def __init__(self, base_address, shuffle=True):
base_address = 0
super(FixedRange, self).__init__(base_address, shuffle=shuffle)
self._fixed_addresses = self._config.range_fixed
def __repr__(self):
return "<FixedRange %s>" % (",".join(self._fixed_addresses))
def _get_range(self):
return [struct.unpack(">L", socket.inet_aton(address))[0]
2015-11-30 16:56:20 +08:00
for address in self._fixed_addresses]