Ejemplo n.º 1
0
    def start(self):

        if self.fakenet_config.get('diverttraffic') and self.fakenet_config[
                'diverttraffic'].lower() == 'yes':

            if (('networkmode' not in self.diverter_config)
                    or (self.diverter_config['networkmode'].lower()
                        not in ['singlehost', 'multihost', 'auto'])):
                self.logger.error(
                    'Error: You must configure a NetworkMode for Diverter, either SingleHost, MultiHost, or Auto'
                )
                sys.exit(1)

            # Select platform specific diverter
            platform_name = platform.system()

            ip_addrs = dict()
            ip_addrs[4] = get_ips([4])  # Get IPv4 addrs
            ip_addrs[6] = get_ips([6])  # Get IPv6 addrs

            if platform_name == 'Windows':

                # Check Windows version
                if platform.release() in [
                        '2000', 'XP', '2003Server', 'post2003'
                ]:
                    self.logger.error(
                        'Error: FakeNet-NG only supports Windows Vista+.')
                    self.logger.error(
                        'Please use the original Fakenet for older versions of Windows.'
                    )
                    sys.exit(1)

                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'singlehost'

                from diverters.windows import Diverter
                self.diverter = Diverter(self.diverter_config,
                                         self.listeners_config, self.logger)

            elif platform_name.lower().startswith('linux'):
                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'multihost'

                from diverters.linux import Diverter
                self.diverter = Diverter(self.diverter_config,
                                         self.listeners_config, ip_addrs,
                                         self.logger)

            else:
                self.logger.error(
                    'Error: Your system %s is currently not supported.',
                    platform_name)
                sys.exit(1)

        # Start all of the listeners
        for listener_name in self.listeners_config:

            listener_config = self.listeners_config[listener_name]
            # Pass remote logger configs in case we want to enable it for listener
            listener_config.update(self.remoteloggers)

            # Anonymous listener
            if not 'listener' in listener_config:
                self.logger.info('Anonymous %s listener on %s port %s...',
                                 listener_name, listener_config['protocol'],
                                 listener_config['port'])
                continue

            # Get a specific provider for the listener name
            try:
                listener_module = getattr(listeners,
                                          listener_config['listener'])
                listener_provider = getattr(listener_module,
                                            listener_config['listener'])

            except AttributeError as e:
                self.logger.error('Listener %s is not implemented.',
                                  listener_config['listener'])
                self.logger.error("%s" % e)

            else:

                listener_provider_instance = listener_provider(
                    listener_config, listener_name, self.logging_level)

                # Store listener provider object
                self.running_listener_providers.append(
                    listener_provider_instance)

                try:
                    listener_provider_instance.start()
                except Exception, e:
                    self.logger.error('Error starting %s listener:',
                                      listener_config['listener'])
                    self.logger.error(" %s" % e)
Ejemplo n.º 2
0
    def start(self):

        if self.fakenet_config.get('diverttraffic') and self.fakenet_config['diverttraffic'].lower() == 'yes':

            if (('networkmode' not in self.diverter_config) or
                    (self.diverter_config['networkmode'].lower() not in
                    ['singlehost', 'multihost', 'auto'])):
                self.logger.error('Error: You must configure a NetworkMode for Diverter, either SingleHost, MultiHost, or Auto')
                sys.exit(1)

            # Select platform specific diverter
            platform_name = platform.system()

            iface_ip_info = IfaceIpInfo()

            ip_addrs = dict()
            ip_addrs[4] = iface_ip_info.get_ips([4])
            ip_addrs[6] = iface_ip_info.get_ips([6])
            fn_addr = '0.0.0.0'

            if platform_name == 'Windows':

                # Check Windows version
                if platform.release() in ['2000', 'XP', '2003Server', 'post2003']:
                    self.logger.error('Error: FakeNet-NG only supports Windows Vista+.')
                    self.logger.error('       Please use the original Fakenet for older versions of Windows.')
                    sys.exit(1)

                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'singlehost'

                from diverters.windows import Diverter
                self.diverter = Diverter(self.diverter_config, self.listeners_config, ip_addrs, self.logging_level)

            elif platform_name.lower().startswith('linux'):
                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'multihost'

                if self.diverter_config['networkmode'].lower() == 'multihost':
                    if (self.diverter_config['linuxrestrictinterface'].lower()
                            != 'off'):
                        fn_iface = self.diverter_config['linuxrestrictinterface']
                        if fn_iface in iface_ip_info.ifaces:
                            try:
                                # default to first link
                                fn_addr = iface_ip_info.get_ips([4], fn_iface)[0]
                            except LookupError as e:
                                self.logger.error('Couldn\'t get IP for %s' %
                                                  (fn_iface))
                                sys.exit(1)
                        else:
                            self.logger.error(
                                'Invalid interface %s specified. Proceeding '
                                'without interface restriction. Exiting.',
                                fn_iface)
                            sys.exit(1)

                from diverters.linux import Diverter
                self.diverter = Diverter(self.diverter_config, self.listeners_config, ip_addrs, self.logging_level)

            else:
                self.logger.error(
                    'Error: Your system %s is currently not supported.' %
                    (platform_name))
                sys.exit(1)

        # Start all of the listeners
        for listener_name in self.listeners_config:

            listener_config = self.listeners_config[listener_name]
            listener_config['ipaddr'] = fn_addr
            # Anonymous listener
            if not 'listener' in listener_config:
                self.logger.info('Anonymous %s listener on %s port %s...', listener_name, listener_config['protocol'], listener_config['port'])
                continue

            # Get a specific provider for the listener name
            try:
                listener_module   = getattr(listeners, listener_config['listener'])
                listener_provider = getattr(listener_module, listener_config['listener'])

            except AttributeError as e:
                self.logger.error('Listener %s is not implemented.', listener_config['listener'])
                self.logger.error("%s" % e)

            else:

                listener_provider_instance = listener_provider(
                        listener_config, listener_name, self.logging_level)

                # Store listener provider object
                self.running_listener_providers.append(listener_provider_instance)

                try:
                    listener_provider_instance.start()
                except Exception, e:
                    self.logger.error('Error starting %s listener on port %s:', listener_config['listener'], listener_config['port'])
                    self.logger.error(" %s" % e)
Ejemplo n.º 3
0
    def start(self):

        if self.fakenet_config.get('diverttraffic') and self.fakenet_config[
                'diverttraffic'].lower() == 'yes':

            # Select platform specific diverter
            if platform.system() == 'Windows':

                # Check Windows version
                if platform.release() in [
                        '2000', 'XP', '2003Server', 'post2003'
                ]:
                    self.logger.error(
                        'Error: FakeNet-NG only supports Windows Vista+.')
                    self.logger.error(
                        '       Please use the original Fakenet for older versions of Windows.'
                    )
                    sys.exit(1)

                # Check architecture
                if platform.machine(
                ) == 'AMD64' and platform.architecture()[0] != '64bit':
                    self.logger.error(
                        'Error: Please install 64-bit Python interpreter to support diverter functions.'
                    )
                    sys.exit(1)

                from diverters.windows import Diverter
                self.diverter = Diverter(self.diverter_config,
                                         self.listeners_config,
                                         self.logging_level)

            else:
                self.logger.error(
                    'Error: Your system %s is currently not supported.',
                    platform.system())
                sys.exit(1)

        # Start all of the listeners
        for listener_name in self.listeners_config:

            listener_config = self.listeners_config[listener_name]

            # Anonymous listener
            if not 'listener' in listener_config:
                self.logger.info('Anonymous %s listener on %s port %s...',
                                 listener_name, listener_config['protocol'],
                                 listener_config['port'])
                continue

            # Get a specific provider for the listener name
            try:
                listener_module = getattr(listeners,
                                          listener_config['listener'])
                listener_provider = getattr(listener_module,
                                            listener_config['listener'])

            except AttributeError as e:
                self.logger.error('Listener %s is not implemented.',
                                  listener_config['listener'])
                self.logger.error("%s" % e)

            else:
                # Listener provider object
                listener_provider_instance = listener_provider(
                    listener_config, listener_name, self.logging_level)

                # Store listener provider object
                self.running_listener_providers.append(
                    listener_provider_instance)

                try:
                    listener_provider_instance.start()
                except Exception, e:
                    self.logger.error('Error starting %s listener:',
                                      listener_config['listener'])
                    self.logger.error(" %s" % e)
Ejemplo n.º 4
0
class Fakenet(object):
    def __init__(self, logging_level=logging.INFO):

        self.logger = logging.getLogger('FakeNet')
        self.logger.setLevel(logging_level)

        self.logging_level = logging_level

        # Diverter used to intercept and redirect traffic
        self.diverter = None

        # FakeNet options and parameters
        self.fakenet_config_dir = ''
        self.fakenet_config = dict()

        # Diverter options and parameters
        self.diverter_config = dict()

        # Listener options and parameters
        self.listeners_config = OrderedDict()

        # List of running listener providers
        self.running_listener_providers = list()

    def parse_config(self, config_filename):

        if not config_filename:

            config_filename = os.path.join(os.path.dirname(__file__),
                                           'configs', 'default.ini')

        if not os.path.exists(config_filename):

            config_filename = os.path.join(os.path.dirname(__file__),
                                           'configs', config_filename)

            if not os.path.exists(config_filename):

                self.logger.critical('Could not open configuration file %s',
                                     config_filename)
                sys.exit(1)

        self.fakenet_config_dir = os.path.dirname(config_filename)
        config = ConfigParser()
        config.read(config_filename)

        self.logger.info('Loaded configuration file: %s', config_filename)

        # Parse configuration
        for section in config.sections():

            if section == 'FakeNet':
                self.fakenet_config = dict(config.items(section))

            elif section == 'Diverter':
                self.diverter_config = dict(config.items(section))

            elif config.getboolean(section, 'enabled'):
                self.listeners_config[section] = dict(config.items(section))

        # Expand listeners
        self.listeners_config = self.expand_listeners(self.listeners_config)

    def expand_ports(self, ports_list):
        ports = []
        for i in ports_list.split(','):
            if '-' not in i:
                ports.append(int(i))
            else:
                l, h = map(int, i.split('-'))
                ports += range(l, h + 1)
        return ports

    def expand_listeners(self, listeners_config):

        listeners_config_expanded = OrderedDict()

        for listener_name in listeners_config:

            listener_config = self.listeners_config[listener_name]
            ports = self.expand_ports(listener_config['port'])

            if len(ports) > 1:

                for port in ports:

                    listener_config['port'] = port
                    listeners_config_expanded["%s_%d" %
                                              (listener_name,
                                               port)] = listener_config.copy()

            else:
                listeners_config_expanded[listener_name] = listener_config

        return listeners_config_expanded

    def start(self):

        if self.fakenet_config.get('diverttraffic') and self.fakenet_config[
                'diverttraffic'].lower() == 'yes':

            if (('networkmode' not in self.diverter_config)
                    or (self.diverter_config['networkmode'].lower()
                        not in ['singlehost', 'multihost', 'auto'])):
                self.logger.critical('Error: You must configure a ' +
                                     'NetworkMode for Diverter, either ' +
                                     'SingleHost, MultiHost, or Auto')
                sys.exit(1)

            # Select platform specific diverter
            platform_name = platform.system()

            iface_ip_info = IfaceIpInfo()

            ip_addrs = dict()
            ip_addrs[4] = iface_ip_info.get_ips([4])
            ip_addrs[6] = iface_ip_info.get_ips([6])
            fn_addr = '0.0.0.0'

            if platform_name == 'Windows':

                # Check Windows version
                if platform.release() in [
                        '2000', 'XP', '2003Server', 'post2003'
                ]:
                    self.logger.critical('Error: FakeNet-NG only supports ' +
                                         'Windows Vista+.')
                    self.logger.critical('       Please use the original ' +
                                         'Fakenet for older versions of ' +
                                         'Windows.')
                    sys.exit(1)

                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'singlehost'

                from diverters.windows import Diverter
                self.diverter = Diverter(self.diverter_config,
                                         self.listeners_config, ip_addrs,
                                         self.logging_level)

            elif platform_name.lower().startswith('linux'):
                if self.diverter_config['networkmode'].lower() == 'auto':
                    self.diverter_config['networkmode'] = 'multihost'

                if self.diverter_config['networkmode'].lower() == 'multihost':
                    if (self.diverter_config['linuxrestrictinterface'].lower()
                            != 'off'):
                        fn_iface = self.diverter_config[
                            'linuxrestrictinterface']
                        if fn_iface in iface_ip_info.ifaces:
                            try:
                                # default to first link
                                fn_addr = iface_ip_info.get_ips([4],
                                                                fn_iface)[0]
                            except LookupError as e:
                                self.logger.error('Couldn\'t get IP for %s' %
                                                  (fn_iface))
                                sys.exit(1)
                        else:
                            self.logger.error(
                                'Invalid interface %s specified. Proceeding '
                                'without interface restriction. Exiting.',
                                fn_iface)
                            sys.exit(1)

                from diverters.linux import Diverter
                self.diverter = Diverter(self.diverter_config,
                                         self.listeners_config, ip_addrs,
                                         self.logging_level)

            else:
                self.logger.critical(
                    'Error: Your system %s is currently not supported.' %
                    (platform_name))
                sys.exit(1)

        # Start all of the listeners
        for listener_name in self.listeners_config:

            listener_config = self.listeners_config[listener_name]
            listener_config['ipaddr'] = fn_addr
            listener_config['configdir'] = self.fakenet_config_dir
            # Anonymous listener
            if not 'listener' in listener_config:
                self.logger.debug('Anonymous %s listener on %s port %s...',
                                  listener_name, listener_config['protocol'],
                                  listener_config['port'])
                continue

            # Get a specific provider for the listener name
            try:
                listener_module = getattr(listeners,
                                          listener_config['listener'])
                listener_provider = getattr(listener_module,
                                            listener_config['listener'])

            except AttributeError as e:
                self.logger.error('Listener %s is not implemented.',
                                  listener_config['listener'])
                self.logger.error("%s" % e)

            else:

                listener_provider_instance = listener_provider(
                    listener_config, listener_name, self.logging_level)

                # Store listener provider object
                self.running_listener_providers.append(
                    listener_provider_instance)

                try:
                    listener_provider_instance.start()
                except Exception as e:
                    self.logger.error('Error starting %s listener on port %s:',
                                      listener_config['listener'],
                                      listener_config['port'])
                    self.logger.error(" %s" % e)
                    sys.exit(1)

        # Start the diverter
        if self.diverter:
            self.diverter.start()

        for listener in self.running_listener_providers:

            # Only listeners that implement acceptListeners(listeners)
            # interface receive running_listener_providers
            try:
                listener.acceptListeners(self.running_listener_providers)
            except AttributeError:
                self.logger.debug(
                    "acceptListeners() not implemented by Listener %s" %
                    listener.name)

            # Only listeners that implement acceptDiverter(diverter)
            # interface receive diverter
            try:
                listener.acceptDiverter(self.diverter)
            except AttributeError:
                self.logger.debug(
                    "acceptDiverter() not implemented by Listener %s" %
                    listener.name)

    def stop(self):

        self.logger.info("Stopping...")

        for running_listener_provider in self.running_listener_providers:
            running_listener_provider.stop()

        if self.diverter:
            self.diverter.stop()