예제 #1
0
 def __init__(self, parent=None):
     super(frm_Settings, self).__init__(parent)
     self.setWindowTitle('WiFi-Pompkin - Settings')
     self.Settings = SettingsINI('core/config/app/config.ini')
     self.loadtheme(self.XmlThemeSelected())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #2
0
 def __init__(self, parent=None):
     super(SettingsRegister, self).__init__(parent)
     self.setWindowTitle('WiFi-Pumpkin - Settings')
     self.Settings = SettingsINI(C.CONFIG_INI)
     self.loadtheme(self.get_theme_qss())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #3
0
 def __init__(self, parent = None):
     super(frm_Settings, self).__init__(parent)
     self.setWindowTitle('settings WiFi-Pompkin')
     self.Settings = SettingsINI('core/config/app/config.ini')
     self.bdfproxyConf  = SettingsINI(self.Settings.get_setting('plugins','bdfproxy_patch_config'))
     self.loadtheme(self.XmlThemeSelected())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #4
0
 def __init__(self, parent = None):
     super(frm_Settings, self).__init__(parent)
     self.setWindowTitle('settings WiFi-Pompkin')
     self.Settings = SettingsINI('core/config/app/config.ini')
     self.bdfproxyConf  = SettingsINI(self.Settings.get_setting('plugins','bdfproxy_config'))
     self.loadtheme(self.XmlThemeSelected())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #5
0
 def __init__(self, parent = None):
     super(frm_Settings, self).__init__(parent)
     self.__class__.instances.append(weakref.proxy(self))
     self.setWindowTitle('WiFi-Pumpkin - Settings')
     self.Settings = SettingsINI(C.CONFIG_INI)
     self.loadtheme(self.get_theme_qss())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #6
0
    def __init__(self, settings=None, **kwargs):
        QtGui.QDialog.__init__(self, **kwargs)
        self.setupUi(self)

        if isinstance(settings, SettingsINI):
            self.Config = settings
        else:
            self.Config = SettingsINI(settings)

        self.configure_settings(self.Config)
        self.connect_buttons()
예제 #7
0
파일: main.py 프로젝트: gitter-badger/zeex
 def project_settings_ini(self, project_settings_path, project_root_dir,
                          project_log_dir):
     settings = SettingsINI(filename=project_settings_path)
     settings.set('GENERAL', 'ROOT_DIRECTORY', value=project_root_dir)
     settings.set('GENERAL', 'LOG_DIRECTORY', value=project_log_dir)
     settings.save()
     return settings
예제 #8
0
def check_dep_pumpkin():
    # check hostapd
    hostapd = popen('which hostapd').read().split('\n')
    if not path.isfile(hostapd[0]): notinstall('hostapd')
    # checck source.tar.gz tamplate module
    if not path.isfile(C.TEMPLATES):
        system(C.EXTRACT_TEMP)

    # check if hostapd is found and save path
    settings = SettingsINI(C.CONFIG_INI)
    hostapd_path = settings.get_setting('accesspoint','hostapd_path')
    if not path.isfile(hostapd_path) and len(hostapd[0]) > 2:
        return settings.set_setting('accesspoint','hostapd_path',hostapd[0])
    elif not path.isfile(hostapd[0]):
        return settings.set_setting('accesspoint','hostapd_path','0')
예제 #9
0
def check_dep_pumpkin():
    # check hostapd
    hostapd = popen('which hostapd').read().split('\n')
    if not path.isfile(hostapd[0]): notinstall('hostapd')
    # checck source.tar.gz tamplate module
    if not path.isfile(C.TEMPLATES):
        system(C.EXTRACT_TEMP)

    # check if hostapd is found and save path
    settings = SettingsINI(C.CONFIG_INI)
    hostapd_path = settings.get_setting('accesspoint', 'hostapd_path')
    if not path.isfile(hostapd_path) and len(hostapd[0]) > 2:
        return settings.set_setting('accesspoint', 'hostapd_path', hostapd[0])
    elif not path.isfile(hostapd[0]):
        return settings.set_setting('accesspoint', 'hostapd_path', '0')
예제 #10
0
def check_dep_pumpkin():
    # check hostapd
    hostapd = popen('which hostapd').read().split('\n')
    if not path.isfile(hostapd[0]): notinstall('hostapd')
    # checck source.tar.gz tamplate module
    if not path.isfile(
            'templates/fakeupdate/Windows_Update/Settins_WinUpdate.html'):
        system('cd templates/ && tar -xf fakeupdate.tar.gz')

    # check if hostapd is found and save path
    settings = SettingsINI('core/config/app/config.ini')
    hostapd_path = settings.get_setting('accesspoint', 'hostapd_path')
    if not path.isfile(hostapd_path) and len(hostapd[0]) > 2:
        return settings.set_setting('accesspoint', 'hostapd_path', hostapd[0])
    elif not path.isfile(hostapd[0]):
        return settings.set_setting('accesspoint', 'hostapd_path', '0')
예제 #11
0
class PluginTemplate(QObject):
    name = 'plugin master'
    version = '1.0'
    config = SettingsINI('core/config/app/proxy.ini')
    loggers = {}
    send_output = pyqtSignal(object)

    def init_logger(self, session):
        self.loggers['Pumpkin-Proxy'] = self.setup_logger(
            'Pumpkin-Proxy', 'logs/AccessPoint/pumpkin-proxy.log', session)
        self.log = self.loggers['Pumpkin-Proxy']

    def setup_logger(self,
                     logger_name,
                     log_file,
                     key=str(),
                     level=logging.INFO):
        if self.loggers.get(logger_name):
            return self.loggers.get(logger_name)
        else:
            logger = logging.getLogger(logger_name)
            formatter = logging.Formatter(
                'SessionID[{}] %(asctime)s : %(message)s'.format(key))
            fileHandler = logging.FileHandler(log_file, mode='a')
            fileHandler.setFormatter(formatter)
            logger.setLevel(logging.INFO)
            logger.addHandler(fileHandler)
        return logger

    def request(self, flow):
        raise NotImplementedError

    def response(self, flow):
        raise NotImplementedError
예제 #12
0
    def downloadCaptiveportals(self):
        ''' check interfaces on background '''
        try:
            data_file = urlopen(C.EXTRACAPTIVETHEMES)
            with open(C.CAPTIVETHEMESZIP, 'wb') as output:
                output.write(data_file.read())
        except Exception as e:
            self.btn_updateCaptive.setEnabled(True)
            self.btn_updateCaptive.setText('Update')
            return QtGui.QMessageBox.information(self, 'Error: Download data ',
                                                 str(e))

        zip_ref = ZipFile(C.CAPTIVETHEMESZIP, 'r')
        zip_ref.extractall(C.TEMPPATH)
        zip_ref.close()

        source_path_templates = C.CAPTIVEPATH_TMP_TEMPLATES
        source_path_plugins = C.CAPTIVEPATH_TMP_PLUGINS
        config_captive = SettingsINI(C.PATHCAPTIVEFINI)

        for plugin in config_captive.get_all_childname('plugins'):
            if (not plugin in self.config.get_all_childname('plugins')):

                system('cp -r {src} {dst}'.format(
                    src=source_path_templates + plugin,
                    dst=C.CAPTIVE_PATH_TEMPLATES))
                self.config.set_setting('plugins', plugin, False)

                for subplugin in config_captive.get_all_childname(
                        'set_{}'.format(plugin)):
                    if subplugin != 'Default':
                        self.config.set_setting('set_{}'.format(plugin),
                                                subplugin, False)
                    else:
                        self.config.set_setting('set_{}'.format(plugin),
                                                subplugin, True)

                system('cp {src} {dst}'.format(src='{}{}.py'.format(
                    source_path_plugins, plugin),
                                               dst=C.CAPTIVE_PATH_PLUGINS))

        self.btn_updateCaptive.setEnabled(True)
        self.btn_updateCaptive.setText('Update')
        QtGui.QMessageBox.information(
            self, 'Update Captive-Portals',
            "Already up-to-date. Please restart WiFi-Pumpkin to apply this update."
        )
예제 #13
0
def check_dep_pumpkin():
    # check hostapd
    hostapd = popen('which hostapd').read().split('\n')
    if not path.isfile(hostapd[0]): notinstall('hostapd')
    # checck source.tar.gz tamplate module
    if not path.isfile('templates/Update/Windows_Update/Settins_WinUpdate.html'):
        copy('settings/source.tar.gz','templates/')
        system('cd templates/ && tar -xf source.tar.gz')
        remove('templates/source.tar.gz')

    # check if hostapd is found and save path
    settings = SettingsINI('core/config/app/config.ini')
    hostapd_path = settings.get_setting('accesspoint','hostapd_path')
    if not path.isfile(hostapd_path) and len(hostapd[0]) > 2:
        return settings.set_setting('accesspoint','hostapd_path',hostapd[0])
    elif not path.isfile(hostapd[0]):
        return settings.set_setting('accesspoint','hostapd_path','0')
예제 #14
0
 def __init__(self, parent = None):
     super(frm_Settings, self).__init__(parent)
     self.setWindowTitle('WiFi-Pompkin - Settings')
     self.Settings = SettingsINI(C.CONFIG_INI)
     self.loadtheme(self.get_theme_qss())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #15
0
 def __init__(self, parent = None):
     super(frm_Settings, self).__init__(parent)
     self.setWindowTitle('WiFi-Pompkin - Settings')
     self.Settings = SettingsINI('core/config/app/config.ini')
     self.loadtheme(self.XmlThemeSelected())
     self.setGeometry(0, 0, 420, 440)
     self.center()
     self.Qui()
예제 #16
0
 def __init__(self):
     QtGui.QTableWidget.__init__(self)
     self.column, self.row = 0, 0
     self.max_column = 4
     self.loadtheme(
         SettingsINI(C.CONFIG_INI).get_setting('settings', 'themes'))
     self.items_widgets = {}
     self.APclients = {}
     self.setColumnCount(self.max_column)
예제 #17
0
def check_dep_pumpkin():
    hostapd = popen('which hostapd').read().split('\n')
    dhcpd = popen('which dhcpd').read().split('\n')
    deps = []
    lista = [dhcpd[0], hostapd[0]]
    for i in lista:
        deps.append(path.isfile(i))
    for k, g in enumerate(deps):
        if deps[k] == False:
            if k == 0: notinstall('isc-dhcp-server')
            if k == 1: notinstall('hostapd')
    if not path.isfile(
            'templates/Update/Windows_Update/Settins_WinUpdate.html'):
        copy('settings/source.tar.gz', 'templates/')
        system('cd templates/ && tar -xf source.tar.gz')
        remove('templates/source.tar.gz')

    # check if hostapd is found and save path
    settings = SettingsINI('core/config/app/config.ini')
    hostapd_path = settings.get_setting('accesspoint', 'hostapd_path')
    if not path.isfile(hostapd_path) and len(hostapd[0]) > 2:
        return settings.set_setting('accesspoint', 'hostapd_path', hostapd[0])
    elif not path.isfile(hostapd[0]):
        return settings.set_setting('accesspoint', 'hostapd_path', '0')
예제 #18
0
class PSniffer(object):
    ''' plugins data sniffers'''
    name = 'plugin TCP proxy master'
    version = '1.0'
    config = SettingsINI('core/config/app/proxy.ini')
    loggers = {}
    output = pyqtSignal(object)
    session = None

    def filterPackets(self, pkt):
        ''' intercept packetes data '''
        raise NotImplementedError

    def get_http_headers(self, http_payload):
        ''' get header dict http request'''
        try:
            headers_raw = http_payload[:http_payload.index("\r\n\r\n") + 2]
            headers = dict(
                findall(r'(?P<name>.*?):(?P<value>.*?)\r\n', headers_raw))
        except:
            return None
        if 'Content-Type' not in headers:
            return None

        return headers

    def setup_logger(self,
                     logger_name,
                     log_file,
                     key=str(),
                     level=logging.INFO):
        if self.loggers.get(logger_name):
            return self.loggers.get(logger_name)
        else:
            logger = logging.getLogger(logger_name)
            formatter = logging.Formatter(
                'SessionID[{}] %(asctime)s : %(message)s'.format(key))
            fileHandler = logging.FileHandler(log_file, mode='a')
            fileHandler.setFormatter(formatter)
            logger.setLevel(logging.INFO)
            logger.addHandler(fileHandler)
        return logger

    def hexdumpPackets(self, pkt):
        ''' show packets hexdump '''
        return hexdump(pkt)
예제 #19
0
    def open_project(self, contents: list = None):
        if contents:
            # New project came in off the slot.
            dirname, ini = contents
        else:
            # User must have selected off the tree.
            try:
                idx = self.ProjectsTreeView.selectedIndexes()[0]
            except IndexError:
                # User failed to select anything..
                return self.display_ok_msg("No project folder selected")

            dirname = idx.model().filePath(idx)
            ini = get_ini_file(dirname)

        # See if project is cached.
        try:

            self._project_cache[dirname].show()

        except KeyError:
            # Oh well, not cached...
            # Make sure the project is valid
            assert ini and os.path.exists(
                ini
            ), "Need a settings.ini file for project '{}'- got: '{}'".format(
                dirname, ini)
            assert dirname and os.path.exists(
                dirname), "Directory '{}' needs to exist!".format(dirname)
            p = os.path.normpath
            root_dir = p(self.SettingsDialog.rootDirectoryLineEdit.text())
            assert not p(
                dirname) == root_dir, "Project directory cannot be the root!"

            # Update ROOT_DIRECTORY in settings.
            settings = SettingsINI(ini)
            settings.set('GENERAL', 'ROOT_DIRECTORY', dirname)
            ini_name = os.path.basename(ini)

            # Make sure the ini file goes
            # in the home folder of the project.
            ini = os.path.join(dirname, ini_name)
            settings.save_as(ini, set_self=True)

            # Build & cache window
            window = ProjectMainWindow(ini)
            self._cache_project(dirname, window)
            self.signalProjectOpened.emit([dirname, ini])
            window.show()
예제 #20
0
파일: plugin.py 프로젝트: wanggh1021/KITT
class CaptiveTemplatePlugin(object):
    Name = 'plugin template captive-portal'
    version = '1.0'
    config = SettingsINI(C.CAPTIVEPORTAL_INI)
    loggers = {}

    def init_logger(self, session):
        self.loggers['CaptivePortal'] = self.setup_logger(
            'CaptivePortal', 'logs/AccessPoint/captive-portal.log', session)
        self.log = self.loggers['CaptivePortal']

    def init_language(self, lang):
        pass

    def getSellectedLanguage(self):
        selected_lang, key = None, 'set_{}'.format(self.Name)
        for lang in self.config.get_all_childname(key):
            if (self.config.get_setting(key, lang, format=bool)):
                selected_lang = lang
        return selected_lang

    def initialize(self):
        self.init_language(self.getSellectedLanguage())

    def setup_logger(self,
                     logger_name,
                     log_file,
                     key=str(),
                     level=logging.INFO):
        if self.loggers.get(logger_name):
            return self.loggers.get(logger_name)
        else:
            logger = logging.getLogger(logger_name)
            formatter = logging.Formatter(
                'SessionID[{}] %(asctime)s : %(message)s'.format(key))
            fileHandler = logging.FileHandler(log_file, mode='a')
            fileHandler.setFormatter(formatter)
            logger.setLevel(logging.INFO)
            logger.addHandler(fileHandler)
        return logger
예제 #21
0
 def __init__(self,opts, server,state,session):
     flow.FlowMaster.__init__(self,opts, server,state)
     self.config  = SettingsINI('core/config/app/proxy.ini')
     self.session = session
     self.plugins = []
     self.initializePlugins()
예제 #22
0
 def __init__(self, interface, session):
     QThread.__init__(self)
     self.interface = interface
     self.session = session
     self.stopped = False
     self.config = SettingsINI('core/config/app/tcpproxy.ini')
예제 #23
0
class MasterHandler(flow.FlowMaster):
    def __init__(self,opts, server,state,session):
        flow.FlowMaster.__init__(self,opts, server,state)
        self.config  = SettingsINI('core/config/app/proxy.ini')
        self.session = session
        self.plugins = []
        self.initializePlugins()
        
    def run(self,send):
        self.sendMethod = send
        for plugin in self.plugins:
            plugin.send_output = self.sendMethod
        self.thread = ThreadController(self)
        self.thread.start()

    def disablePlugin(self,name, status):
        ''' disable plugin by name '''
        plugin_on = []
        if status:
            for plugin in self.plugins:
                plugin_on.append(plugin.Name)
            if name not in plugin_on:
                for p in self.plugin_classes:
                    pluginconf = p()
                    if  pluginconf.Name == name:
                        pluginconf.send_output = self.sendMethod
                        print('plugin:{0:17} status:On'.format(name))
                        self.plugins.append(pluginconf)
        else:
            for plugin in self.plugins:
                if plugin.Name == name:
                    print('plugin:{0:17} status:Off'.format(name))
                    self.plugins.remove(plugin)

    def initializePlugins(self):
        self.plugin_classes = plugin.PluginTemplate.__subclasses__()
        for p in self.plugin_classes:
            if self.config.get_setting('plugins',p().Name,format=bool):
                print('plugins::{0:17} status:On'.format(p().Name))
                self.plugins.append(p())
        # initialize logging in all plugins enable
        #for instance in self.plugins:
        #    instance.init_logger(self.session)

    @controller.handler
    def request(self, flow):
        '''
        print "-- request --"
        print flow.__dict__
        print flow.request.__dict__
        print flow.request.headers.__dict__
        print "--------------"
        print
        '''
        try:
            for p in self.plugins:
                p.request(flow)
        except Exception:
            pass

    @controller.handler
    def response(self, flow):

        '''
        print
        print "-- response --"
        print flow.__dict__
        print flow.response.__dict__
        print flow.response.headers.__dict__
        print "--------------"
        print
        '''
        try:
            for p in self.plugins:
                p.response(flow)
        except Exception:
            pass
예제 #24
0
 def __init__(self,opts, server,state,session):
     flow.FlowMaster.__init__(self,opts, server,state)
     self.config  = SettingsINI(C.PUMPPROXY_INI)
     self.session = session
     self.plugins = []
     self.initializePlugins()
예제 #25
0
class ThreadSniffingPackets(QThread):
    output_plugins = pyqtSignal(object)

    def __init__(self, interface, session):
        QThread.__init__(self)
        self.interface = interface
        self.session = session
        self.stopped = False
        self.config = SettingsINI('core/config/app/tcpproxy.ini')

    def run(self):
        self.main()

    def sniffer(self, q):
        while not self.stopped:
            try:
                sniff(iface=self.interface,
                      filter="tcp and ( port 80 or port 8080 or port 10000)",
                      prn=lambda x: q.put(x),
                      store=0)
            except Exception:
                pass
            if self.stopped:
                break

    def disablePlugin(self, name, status):
        ''' disable plugin by name '''
        plugin_on = []
        if status:
            for plugin in self.plugins:
                plugin_on.append(self.plugins[plugin].Name)
            if name not in plugin_on:
                for p in self.plugin_classes:
                    pluginconf = p()
                    if pluginconf.Name == name:
                        self.plugins[name] = pluginconf
                        self.plugins[name].getInstance()._activated = True
                        print('TCPProxy::{0:17} status:On'.format(name))
        else:
            print('TCPProxy::{0:17} status:Off'.format(name))
            self.plugins.pop(self.plugins[name].Name)

    def main(self):
        self.plugins = {}
        self.plugin_classes = default.PSniffer.__subclasses__()
        for p in self.plugin_classes:
            plugin_load = p()
            self.plugins[plugin_load.Name] = plugin_load
            self.plugins[plugin_load.Name].output = self.output_plugins
            self.plugins[plugin_load.Name].session = self.session
        print '\n[*] TCPProxy running on port 80/8080:\n'
        for name in self.plugins.keys():
            if self.config.get_setting('plugins', name, format=bool):
                self.plugins[name].getInstance()._activated = True
                print('TCPProxy::{0:17} status:On'.format(name))
        print('\n')
        q = Queue.Queue()
        sniff = Thread(target=self.sniffer, args=(q, ))
        sniff.start()
        while (not self.stopped):
            try:
                pkt = q.get(timeout=0)
                for Active in self.plugins.keys():
                    if self.plugins[Active].getInstance()._activated:
                        try:
                            self.plugins[Active].filterPackets(pkt)
                        except Exception:
                            pass
            except Queue.Empty:
                pass

    def snifferParser(self, pkt):
        try:
            if pkt.haslayer(Ether) and pkt.haslayer(
                    Raw) and not pkt.haslayer(IP) and not pkt.haslayer(IPv6):
                return
            self.dport = pkt[TCP].dport
            self.sport = pkt[TCP].sport
            if pkt.haslayer(TCP) and pkt.haslayer(Raw) and pkt.haslayer(IP):
                self.src_ip_port = str(pkt[IP].src) + ':' + str(self.sport)
                self.dst_ip_port = str(pkt[IP].dst) + ':' + str(self.dport)

            if pkt.haslayer(Raw):
                self.load = pkt[Raw].load
                if self.load.startswith('GET'):
                    self.get_http_GET(self.src_ip_port, self.dst_ip_port,
                                      self.load)
                    self.searchBingGET(
                        self.load.split('\n', 1)[0].split('&')[0])
                elif self.load.startswith('POST'):
                    header, url = self.get_http_POST(self.load)
                    self.getCredentials_POST(
                        pkt.getlayer(Raw).load, url, header, self.dport,
                        self.sport)
        except:
            pass

    def searchBingGET(self, search):
        if 'search?q' in search:
            searched = search.split('search?q=', 1)[1]
            searched = searched.replace('+', ' ')
            print 'Search::BING { %s }' % (searched)

    def getCredentials_POST(self, payload, url, header, dport, sport):
        user_regex = '([Ee]mail|%5B[Ee]mail%5D|[Uu]ser|[Uu]sername|' \
        '[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[Ii][Dd])=([^&|;]*)'
        pw_regex = '([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][Ss][Ww]|' \
        '[Pp]asswrd|[Pp]assw|%5B[Pp]assword%5D)=([^&|;]*)'
        username = re.findall(user_regex, payload)
        password = re.findall(pw_regex, payload)
        if not username == [] and not password == []:
            self.output_plugins.emit({
                'POSTCreds': {
                    'User': username[0][1],
                    'Pass': password[0][1],
                    'Url': url,
                    'destination': '{}/{}'.format(sport, dport)
                }
            })

    def get_http_POST(self, load):
        dict_head = {}
        try:
            headers, body = load.split("\r\n\r\n", 1)
            header_lines = headers.split('\r\n')
            for item in header_lines:
                try:
                    dict_head[item.split()[0]] = item.split()[1]
                except Exception:
                    pass
            if 'Referer:' in dict_head.keys():
                return dict_head, dict_head['Referer:']
        except ValueError:
            return None, None
        return dict_head, None

    def stop(self):
        self.stopped = True
        print 'Thread::[{}] successfully stopped.'.format(self.objectName())
예제 #26
0
 def __init__(self,interface,session):
     QThread.__init__(self)
     self.interface  = interface
     self.session    = session
     self.stopped    = False
     self.config     = SettingsINI(C.TCPPROXY_INI)
예제 #27
0
class frm_Settings(QDialog):
    def __init__(self, parent=None):
        super(frm_Settings, self).__init__(parent)
        self.setWindowTitle('WiFi-Pompkin - Settings')
        self.Settings = SettingsINI(C.CONFIG_INI)
        self.loadtheme(self.get_theme_qss())
        self.setGeometry(0, 0, 420, 440)
        self.center()
        self.Qui()

    def loadtheme(self, theme):
        ''' load theme widgets '''
        sshFile = ("core/%s.qss" % (theme))
        with open(sshFile, "r") as fh:
            self.setStyleSheet(fh.read())

    def get_theme_qss(self):
        ''' get theme selected path'''
        return self.Settings.get_setting('settings', 'themes')

    def center(self):
        ''' set center widgets '''
        frameGm = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

    def save_settings(self):
        self.Settings.set_setting('settings', 'scapy_deauth',
                                  self.pageTab1.d_scapy.isChecked())
        self.Settings.set_setting('settings', 'mdk3_deauth',
                                  self.pageTab1.d_mdk.isChecked())
        self.Settings.set_setting('settings', 'scan_scapy',
                                  self.pageTab1.scan_scapy.isChecked())
        self.Settings.set_setting('settings', 'scan_airodump',
                                  self.pageTab1.scan_airodump.isChecked())
        self.Settings.set_setting('accesspoint', 'dhcpd_server',
                                  self.pageTab1.dhcpdserver.isChecked())
        self.Settings.set_setting('accesspoint', 'pydhcp_server',
                                  self.pageTab1.pydhcpserver.isChecked())
        self.Settings.set_setting('accesspoint', 'pydns_server',
                                  self.pageTab1.ch_pyDNS_server.isChecked())
        self.Settings.set_setting('accesspoint', 'dnsproxy_server',
                                  self.pageTab1.ch_DNSproxy_server.isChecked())
        if self.pageTab1.theme1.isChecked():
            self.Settings.set_setting('settings', 'themes',
                                      str(self.pageTab1.theme1.objectName()))
        elif self.pageTab1.theme2.isChecked():
            self.Settings.set_setting('settings', 'themes',
                                      str(self.pageTab1.theme2.objectName()))
        elif self.pageTab1.theme3.isChecked():
            self.Settings.set_setting('settings', 'themes',
                                      str(self.pageTab1.theme3.objectName()))
        if self.pageTab1.AP_0.isChecked():
            self.Settings.set_setting('accesspoint', 'hostapd_custom', False)
        elif self.pageTab1.AP_1.isChecked():
            self.Settings.set_setting('accesspoint', 'hostapd_custom', True)

        self.Settings.set_setting('settings', 'mdk3',
                                  str(self.txt_arguments.text()))
        self.Settings.set_setting('settings', 'scanner_rangeIP',
                                  str(self.txt_ranger.text()))
        self.Settings.set_setting('accesspoint', 'ssid',
                                  str(self.pageTab1.Apname.text()))
        self.Settings.set_setting('accesspoint', 'channel',
                                  str(self.pageTab1.channel.value()))
        self.Settings.set_setting('accesspoint', 'persistNetwokManager',
                                  self.pageTab1.network_manager.isChecked())
        self.Settings.set_setting(
            'accesspoint', 'checkConnectionWifi',
            self.pageTab1.checkConnectionWifi.isChecked())
        self.Settings.set_setting('accesspoint', 'check_support_ap_mode',
                                  self.check_interface_mode_AP.isChecked())
        self.Settings.set_setting('settings', 'redirect_port',
                                  str(self.redirectport.text()))
        if not path.isfile(self.pageTab1.edit_hostapd_path.text()):
            return QMessageBox.warning(self, 'Path Hostapd Error',
                                       'hostapd binary path is not found')
        self.Settings.set_setting('accesspoint', 'hostapd_path',
                                  self.pageTab1.edit_hostapd_path.text())
        with open(C.HOSTAPDCONF_PATH2, 'w') as apconf:
            apconf.write(self.ListHostapd.toPlainText())
        self.close()

    def listItemclicked(self, pos):
        ''' add,remove and edit rules iptables from WIFi-Pumpkin'''
        item = self.ListRules.selectedItems()
        self.listMenu = QMenu()
        menu = QMenu()
        additem = menu.addAction('Add')
        editem = menu.addAction('Edit')
        removeitem = menu.addAction('Remove ')
        clearitem = menu.addAction('clear')
        action = menu.exec_(self.ListRules.viewport().mapToGlobal(pos))
        if action == removeitem:
            if item != []:
                self.ListRules.takeItem(self.ListRules.currentRow())
        elif action == additem:
            text, resp = QInputDialog.getText(self, 'Add rules iptables',
                                              'Enter the rules iptables:')
            if resp:
                try:
                    itemsexits = []
                    for index in xrange(self.ListRules.count()):
                        itemsexits.append(
                            str(self.ListRules.item(index).text()))
                    for i in itemsexits:
                        if search(str(text), i):
                            return QMessageBox.information(
                                self, 'Rules exist',
                                'this rules already exist!')
                    item = QListWidgetItem()
                    item.setText(text)
                    item.setSizeHint(QSize(30, 30))
                    self.ListRules.addItem(item)
                except Exception as e:
                    return QMessageBox.information(self, 'error', str(e))
        elif action == editem:
            text, resp = QInputDialog.getText(
                self,
                'Add rules for iptables',
                'Enter the rules iptables:',
                text=self.ListRules.item(self.ListRules.currentRow()).text())
            if resp:
                try:
                    itemsexits = []
                    for index in xrange(self.ListRules.count()):
                        itemsexits.append(
                            str(self.ListRules.item(index).text()))
                    for i in itemsexits:
                        if search(str(text), i):
                            return QMessageBox.information(
                                self, 'Rules exist',
                                'this rules already exist!')
                    item = QListWidgetItem()
                    item.setText(text)
                    item.setSizeHint(QSize(30, 30))
                    self.ListRules.insertItem(self.ListRules.currentRow(),
                                              item)
                except Exception as e:
                    return QMessageBox.information(self, 'error', str(e))
        elif action == clearitem:
            self.ListRules.clear()

    def Qui(self):
        self.Main = QVBoxLayout()
        self.formGroupAd = QFormLayout()
        self.form = QFormLayout()
        self.tabcontrol = QTabWidget()

        # tabs
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()

        self.page_1 = QVBoxLayout(self.tab1)
        self.page_2 = QFormLayout(self.tab2)
        self.page_3 = QFormLayout(self.tab3)
        self.page_4 = QFormLayout(self.tab4)

        self.tabcontrol.addTab(self.tab1, 'General')
        self.tabcontrol.addTab(self.tab2, 'Advanced')
        self.tabcontrol.addTab(self.tab3, 'Iptables')
        self.tabcontrol.addTab(self.tab4, 'Hostpad')

        self.pageTab1 = SettingsTabGeneral(self.Settings)
        self.page_1.addLayout(self.pageTab1)

        self.groupAdvanced = QGroupBox()
        self.groupAdvanced.setTitle('Advanced Settings:')
        self.groupAdvanced.setLayout(self.formGroupAd)

        self.btn_save = QPushButton('Save')
        self.btn_save.clicked.connect(self.save_settings)
        self.btn_save.setFixedWidth(80)
        self.btn_save.setIcon(QIcon('icons/Save.png'))

        #page Adavanced
        self.txt_ranger = QLineEdit(self)
        self.txt_arguments = QLineEdit(self)
        self.scan1 = QRadioButton('Ping Scan:: Very fast IP scan')
        self.scan2 = QRadioButton('Python-Nmap:: Get hostname from IP')
        self.redirectport = QLineEdit(self)
        self.check_interface_mode_AP = QCheckBox(
            'Check if interface supports AP/Mode')
        self.check_interface_mode_AP.setChecked(
            self.Settings.get_setting('accesspoint',
                                      'check_support_ap_mode',
                                      format=bool))
        self.check_interface_mode_AP.setToolTip(
            'if you disable this options in next time, the interface is not should '
            'checked if has support AP mode.')

        # page Iptables
        self.ListRules = QListWidget(self)
        self.ListRules.setFixedHeight(300)
        self.ListRules.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.ListRules.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ListRules.connect(self.ListRules,
                               SIGNAL('customContextMenuRequested(QPoint)'),
                               self.listItemclicked)
        for ech in self.Settings.get_all_childname('iptables'):
            item = QListWidgetItem()
            item.setText(
                str(self.Settings.get_setting('iptables', ech, format=str)))
            item.setSizeHint(QSize(30, 30))
            self.ListRules.addItem(item)

        # page hostpad
        self.ListHostapd = QTextEdit(self)
        self.ListHostapd.setFixedHeight(300)
        with open(C.HOSTAPDCONF_PATH2, 'r') as apconf:
            self.ListHostapd.setText(apconf.read())

        # grup page 2
        self.gruButtonPag2 = QButtonGroup()
        self.gruButtonPag2.addButton(self.scan1)
        self.gruButtonPag2.addButton(self.scan2)

        self.txt_ranger.setText(
            self.Settings.get_setting('settings', 'scanner_rangeIP'))
        self.txt_arguments.setText(
            self.Settings.get_setting('settings', 'mdk3'))
        self.scan2.setEnabled(False)
        self.scan1.setChecked(True)
        #settings tab Advanced
        self.redirectport.setText(
            self.Settings.get_setting('settings', 'redirect_port'))

        #add tab Advanced
        self.formGroupAd.addRow(QLabel('Thread Scan IP-Address:'))
        self.formGroupAd.addRow(self.scan1)
        self.formGroupAd.addRow(self.scan2)
        self.formGroupAd.addRow(self.check_interface_mode_AP)
        self.formGroupAd.addRow('Port sslstrip:', self.redirectport)
        self.formGroupAd.addRow(QLabel('mdk3 Args:'), self.txt_arguments)
        self.formGroupAd.addRow(QLabel('Range Scanner:'), self.txt_ranger)
        self.page_2.addRow(self.groupAdvanced)

        #add tab iptables
        self.page_3.addWidget(QLabel('Iptables:'))
        self.page_3.addRow(self.ListRules)

        #add tab hostpad
        self.page_4.addWidget(QLabel('settings hostapd:'))
        self.page_4.addRow(self.ListHostapd)

        self.form.addRow(self.tabcontrol)
        self.form.addRow(self.btn_save)
        self.Main.addLayout(self.form)
        self.setLayout(self.Main)
예제 #28
0
class ThreadSniffingPackets(QThread):
    output_plugins = pyqtSignal(object)
    def __init__(self,interface,session):
        QThread.__init__(self)
        self.interface  = interface
        self.session    = session
        self.stopped    = False
        self.config     = SettingsINI(C.TCPPROXY_INI)

    def run(self):
        self.main()

    def sniffer(self,q):
        while not self.stopped:
            try:
                sniff(iface=self.interface,
                      filter="tcp and ( port 80 or port 8080 or port 10000)",
                      prn =lambda x : q.put(x), store=0)
            except Exception:pass
            if self.stopped:
                break

    def disablePlugin(self,name, status):
        ''' disable plugin by name '''
        plugin_on = []
        if status:
            for plugin in self.plugins:
                plugin_on.append(self.plugins[plugin].Name)
            if name not in plugin_on:
                for p in self.plugin_classes:
                    pluginconf = p()
                    if  pluginconf.Name == name:
                        self.plugins[name] = pluginconf
                        self.plugins[name].getInstance()._activated = True
                        print('TCPProxy::{0:17} status:On'.format(name))
        else:
            print('TCPProxy::{0:17} status:Off'.format(name))
            self.plugins.pop(self.plugins[name].Name)

    def main(self):
        self.plugins = {}
        self.plugin_classes = default.PSniffer.__subclasses__()
        for p in self.plugin_classes:
            plugin_load = p()
            self.plugins[plugin_load.Name] = plugin_load
            self.plugins[plugin_load.Name].output = self.output_plugins
            self.plugins[plugin_load.Name].session = self.session
        print '\n[*] TCPProxy running on port 80/8080:\n'
        for name in self.plugins.keys():
            if self.config.get_setting('plugins', name, format=bool):
                self.plugins[name].getInstance()._activated = True
                print('TCPProxy::{0:17} status:On'.format(name))
        print('\n')
        q = queue.Queue()
        sniff = Thread(target =self.sniffer, args = (q,))
        sniff.start()
        while (not self.stopped):
            try:
                pkt = q.get(timeout = 0)
                for Active in self.plugins.keys():
                    if self.plugins[Active].getInstance()._activated:
                        try:
                            self.plugins[Active].filterPackets(pkt)
                        except Exception: pass
            except queue.Empty:
              pass

    def snifferParser(self,pkt):
        try:
            if pkt.haslayer(Ether) and pkt.haslayer(Raw) and not pkt.haslayer(IP) and not pkt.haslayer(IPv6):
                return
            self.dport = pkt[TCP].dport
            self.sport = pkt[TCP].sport
            if pkt.haslayer(TCP) and pkt.haslayer(Raw) and pkt.haslayer(IP):
                self.src_ip_port = str(pkt[IP].src)+':'+str(self.sport)
                self.dst_ip_port = str(pkt[IP].dst)+':'+str(self.dport)

            if pkt.haslayer(Raw):
                self.load = pkt[Raw].load
                if self.load.startswith('GET'):
                    self.get_http_GET(self.src_ip_port,self.dst_ip_port,self.load)
                    self.searchBingGET(self.load.split('\n', 1)[0].split('&')[0])
                elif self.load.startswith('POST'):
                    header,url = self.get_http_POST(self.load)
                    self.getCredentials_POST(pkt.getlayer(Raw).load,url,header,self.dport,self.sport)
        except:
            pass

    def searchBingGET(self,search):
        if 'search?q' in search :
            searched = search.split('search?q=',1)[1]
            searched = searched.replace('+',' ')
            print 'Search::BING { %s }'%(searched)

    def getCredentials_POST(self,payload,url,header,dport,sport):
        user_regex = '([Ee]mail|%5B[Ee]mail%5D|[Uu]ser|[Uu]sername|' \
        '[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[Ii][Dd])=([^&|;]*)'
        pw_regex = '([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][Ss][Ww]|' \
        '[Pp]asswrd|[Pp]assw|%5B[Pp]assword%5D)=([^&|;]*)'
        username = re.findall(user_regex, payload)
        password = re.findall(pw_regex, payload)
        if not username ==[] and not password == []:
            self.output_plugins.emit({'POSTCreds':{'User':username[0][1],
            'Pass': password[0][1],'Url':url,'destination':'{}/{}'.format(sport,dport)}})

    def get_http_POST(self,load):
        dict_head = {}
        try:
            headers, body = load.split("\r\n\r\n", 1)
            header_lines = headers.split('\r\n')
            for item in header_lines:
                try:
                    dict_head[item.split()[0]] = item.split()[1]
                except Exception:
                    pass
            if 'Referer:' in dict_head.keys():
                return dict_head ,dict_head['Referer:']
        except ValueError:
            return None,None
        return dict_head, None

    def stop(self):
        self.stopped = True
        print 'Thread::[{}] successfully stopped.'.format(self.objectName())
예제 #29
0
class frm_Settings(QDialog):
    def __init__(self, parent = None):
        super(frm_Settings, self).__init__(parent)
        self.setWindowTitle('settings WiFi-Pompkin')
        self.Settings = SettingsINI('core/config/app/config.ini')
        self.bdfproxyConf  = SettingsINI(self.Settings.get_setting('plugins','bdfproxy_config'))
        self.loadtheme(self.XmlThemeSelected())
        self.setGeometry(0, 0, 420, 440)
        self.center()
        self.Qui()

    def loadtheme(self,theme):
        ''' load theme widgets '''
        sshFile=("core/%s.qss"%(theme))
        with open(sshFile,"r") as fh:
            self.setStyleSheet(fh.read())

    def XmlThemeSelected(self):
        ''' get theme selected path'''
        return self.Settings.get_setting('settings','themes')

    def center(self):
        ''' set center widgets '''
        frameGm = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

    def save_settings(self):
        self.Settings.set_setting('settings','scapy_deauth',self.pageTab1.d_scapy.isChecked())
        self.Settings.set_setting('settings','mdk3_deauth',self.pageTab1.d_mdk.isChecked())
        self.Settings.set_setting('settings','scan_scapy',self.pageTab1.scan_scapy.isChecked())
        self.Settings.set_setting('settings','scan_airodump',self.pageTab1.scan_airodump.isChecked())
        self.Settings.set_setting('accesspoint','dhcpd_server',self.pageTab1.dhcpdserver.isChecked())
        self.Settings.set_setting('accesspoint','pydhcp_server',self.pageTab1.pydhcpserver.isChecked())
        if self.pageTab1.theme1.isChecked():
            self.Settings.set_setting('settings','themes',str(self.pageTab1.theme1.objectName()))
        elif self.pageTab1.theme2.isChecked():
            self.Settings.set_setting('settings','themes',str(self.pageTab1.theme2.objectName()))
        elif self.pageTab1.theme3.isChecked():
            self.Settings.set_setting('settings','themes',str(self.pageTab1.theme3.objectName()))
        if self.pageTab1.AP_0.isChecked():
            self.Settings.set_setting('accesspoint','hostapd_custom',False)
        elif self.pageTab1.AP_1.isChecked():
            self.Settings.set_setting('accesspoint','hostapd_custom',True)

        self.Settings.set_setting('settings','mdk3',str(self.txt_arguments.text()))
        self.Settings.set_setting('settings','scanner_rangeIP',str(self.txt_ranger.text()))
        self.Settings.set_setting('accesspoint','ssid', str(self.pageTab1.Apname.text()))
        self.Settings.set_setting('accesspoint','channel', str(self.pageTab1.channel.value()))
        self.Settings.set_setting('accesspoint','persistNetwokManager',self.pageTab1.network_manager.isChecked())
        self.Settings.set_setting('accesspoint','check_support_ap_mode',self.check_interface_mode_AP.isChecked())
        self.Settings.set_setting('settings','redirect_port', str(self.redirectport.text()))
        if not path.isfile(self.pageTab1.edit_hostapd_path.text()):
            return QMessageBox.warning(self,'Path Hostapd Error','hostapd binary path is not found')
        self.Settings.set_setting('accesspoint','hostapd_path',self.pageTab1.edit_hostapd_path.text())
        with open('core/config/hostapd/hostapd+.conf','w') as apconf:
            apconf.write(self.ListHostapd.toPlainText())
        self.close()


    def listItemclicked(self,pos):
        ''' add,remove and edit rules iptables from WIFi-Pumpkin'''
        item = self.ListRules.selectedItems()
        self.listMenu= QMenu()
        menu = QMenu()
        additem = menu.addAction('Add')
        editem = menu.addAction('Edit')
        removeitem = menu.addAction('Remove ')
        clearitem = menu.addAction('clear')
        action = menu.exec_(self.ListRules.viewport().mapToGlobal(pos))
        if action == removeitem:
            if item != []:
                self.ListRules.takeItem(self.ListRules.currentRow())
        elif action == additem:
            text, resp = QInputDialog.getText(self, 'Add rules iptables',
            'Enter the rules iptables:')
            if resp:
                try:
                    itemsexits = []
                    for index in xrange(self.ListRules.count()):
                        itemsexits.append(str(self.ListRules.item(index).text()))
                    for i in itemsexits:
                        if search(str(text),i):
                            return QMessageBox.information(self,'Rules exist','this rules already exist!')
                    item = QListWidgetItem()
                    item.setText(text)
                    item.setSizeHint(QSize(30,30))
                    self.ListRules.addItem(item)
                except Exception as e:
                    return QMessageBox.information(self,'error',str(e))
        elif action == editem:
            text, resp = QInputDialog.getText(self, 'Add rules iptables',
            'Enter the rules iptables:',text=self.ListRules.item(self.ListRules.currentRow()).text())
            if resp:
                try:
                    itemsexits = []
                    for index in xrange(self.ListRules.count()):
                        itemsexits.append(str(self.ListRules.item(index).text()))
                    for i in itemsexits:
                        if search(str(text),i):
                            return QMessageBox.information(self,'Rules exist','this rules already exist!')
                    item = QListWidgetItem()
                    item.setText(text)
                    item.setSizeHint(QSize(30,30))
                    self.ListRules.insertItem(self.ListRules.currentRow(),item)
                except Exception as e:
                    return QMessageBox.information(self,'error',str(e))
        elif action == clearitem:
            self.ListRules.clear()

    def Qui(self):
        self.Main = QVBoxLayout()
        self.formGroupAd  = QFormLayout()
        self.form = QFormLayout()
        self.tabcontrol = QTabWidget()

        # tabs
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()

        self.page_1 = QVBoxLayout(self.tab1)
        self.page_2 = QFormLayout(self.tab2)
        self.page_3 = QFormLayout(self.tab3)
        self.page_4 = QFormLayout(self.tab4)

        self.tabcontrol.addTab(self.tab1, 'General')
        self.tabcontrol.addTab(self.tab2, 'Advanced')
        self.tabcontrol.addTab(self.tab3,'Iptables')
        self.tabcontrol.addTab(self.tab4,'hostpad')

        self.pageTab1 = SettingsTabGeneral(self.Settings)
        self.page_1.addLayout(self.pageTab1)

        self.groupAdvanced = QGroupBox()
        self.groupAdvanced.setTitle('Advanced settings:')
        self.groupAdvanced.setLayout(self.formGroupAd)

        self.btn_save = QPushButton('Save')
        self.btn_save.clicked.connect(self.save_settings)
        self.btn_save.setFixedWidth(80)
        self.btn_save.setIcon(QIcon('icons/Save.png'))


        #page Adavanced
        self.bdfProxy_port = QSpinBox()
        self.bdfProxy_port.setMaximum(10000)
        self.txt_ranger = QLineEdit(self)
        self.txt_arguments = QLineEdit(self)
        self.scan1 = QRadioButton('Ping Scan:: Very fast scan IP')
        self.scan2 = QRadioButton('Python-Nmap:: Get hostname from IP')
        self.redirectport = QLineEdit(self)
        self.check_interface_mode_AP = QCheckBox('Check if interface has been support AP/Mode')
        self.check_interface_mode_AP.setChecked(self.Settings.get_setting('accesspoint','check_support_ap_mode',format=bool))
        self.check_interface_mode_AP.setToolTip('if you disable this options in next time, the interface is not should '
        'checked if has support AP mode.')

        # page Iptables
        self.ListRules = QListWidget(self)
        self.ListRules.setFixedHeight(300)
        self.ListRules.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.ListRules.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ListRules.connect(self.ListRules,
        SIGNAL('customContextMenuRequested(QPoint)'),
        self.listItemclicked)
        for ech in self.Settings.get_all_childname('iptables'):
            item = QListWidgetItem()
            item.setText(str(self.Settings.get_setting('iptables',ech,format=str)))
            item.setSizeHint(QSize(30,30))
            self.ListRules.addItem(item)

        # page hostpad
        self.ListHostapd = QTextEdit(self)
        self.ListHostapd.setFixedHeight(300)
        with open('core/config/hostapd/hostapd+.conf','r') as apconf:
            self.ListHostapd.setText(apconf.read())

        # grup page 2
        self.gruButtonPag2 = QButtonGroup()
        self.gruButtonPag2.addButton(self.scan1)
        self.gruButtonPag2.addButton(self.scan2)

        self.txt_ranger.setText(self.Settings.get_setting('settings','scanner_rangeIP'))
        self.txt_arguments.setText(self.Settings.get_setting('settings','mdk3'))
        self.bdfProxy_port.setValue(int(self.bdfproxyConf.get_setting('Overall','proxyPort')))
        self.bdfProxy_port.setEnabled(False)
        self.scan2.setEnabled(False)
        self.scan1.setChecked(True)
        #settings tab Advanced
        self.redirectport.setText(self.Settings.get_setting('settings','redirect_port'))

        #add tab Advanced
        self.formGroupAd.addRow(QLabel('Thread Scan IP-Address:'))
        self.formGroupAd.addRow(self.scan1)
        self.formGroupAd.addRow(self.scan2)
        self.formGroupAd.addRow(self.check_interface_mode_AP)
        self.formGroupAd.addRow('Port BDFProxy-ng',self.bdfProxy_port)
        self.formGroupAd.addRow('Port sslstrip:',self.redirectport)
        self.formGroupAd.addRow(QLabel('mdk3 Args:'),self.txt_arguments)
        self.formGroupAd.addRow(QLabel('Range Scanner:'),self.txt_ranger)
        self.page_2.addRow(self.groupAdvanced)

        #add tab iptables
        self.page_3.addWidget(QLabel('Iptables:'))
        self.page_3.addRow(self.ListRules)

        #add tab hostpad
        self.page_4.addWidget(QLabel('settings hostapd:'))
        self.page_4.addRow(self.ListHostapd)

        self.form.addRow(self.tabcontrol)
        self.form.addRow(self.btn_save)
        self.Main.addLayout(self.form)
        self.setLayout(self.Main)
예제 #30
0
    check_dep_pumpkin()
    from os import getuid
    if not getuid() == 0:
        exit('[{}!{}] WiFi-Pumpkin must be run as root.'.format(RED, ENDC))

    from PyQt4.QtGui import QApplication, QIcon, QStyleFactory
    main = QApplication(argv)
    checkAppQTDesigner(main.style().objectName())

    print('Loading GUI...')
    app = Initialize()
    app.setWindowIcon(QIcon('icons/icon.ico'))
    app.center()
    # check if Wireless connection
    conf = SettingsINI('core/config/app/config.ini')
    if conf.get_setting('accesspoint', 'checkConnectionWifi', format=bool):
        networkcontrol = CLI_NetworkManager(
        )  # add all interface avaliable for exclude
        app.networkcontrol = networkcontrol
        if networkcontrol.run():
            if networkcontrol.isWiFiConnected() and len(
                    networkcontrol.ifaceAvaliable) > 0:
                settings = UI_NetworkManager(app)
                settings.setWindowIcon(QIcon('icons/icon.ico'))
                settings.show()
                exit(main.exec_())
    app.show()

    print('WiFi-Pumpkin Running!')
    exit(main.exec_())
예제 #31
0
    def __init__(self, parent, **kwargs):
        super(PumpkinMitmproxy, self).__init__(parent)
        self.mainLayout = QtGui.QVBoxLayout()
        self.config = SettingsINI(C.PUMPPROXY_INI)
        self.plugins = []
        self.main_method = parent
        self.bt_SettingsDict = {}
        self.check_PluginDict = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QtGui.QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)
        self.dockwidget = PumpkinProxyDock(None, title=self.Name)
        self.search[self.Name] = str(
            'iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080'
        )

        # create for add dock logging
        self.tabcontrol = QtGui.QTabWidget()
        self.tab1 = QtGui.QWidget()
        self.tab2 = QtGui.QWidget()
        self.page_1 = QtGui.QVBoxLayout(self.tab1)
        self.page_2 = QtGui.QVBoxLayout(self.tab2)
        self.tableLogging = dockPumpkinProxy()

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        #self.tabcontrol.addTab(self.tab2, 'Logging')

        self.TabPlugins = QtGui.QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                      QtGui.QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders = OrderedDict([('Plugins', []), ('Settings', []),
                                     ('Description', [])])
        self.TabPlugins.setHorizontalHeaderLabels(list(self.THeaders.keys()))
        self.TabPlugins.horizontalHeader().resizeSection(0, 158)
        self.TabPlugins.horizontalHeader().resizeSection(1, 80)

        # add on tab
        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.tableLogging)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton(
                    'Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(
                    partial(self.setSettingsPlgins, plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton('None')
            self.check_PluginDict[plugin.Name] = QtGui.QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(
                partial(self.setPluginOption, plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QtGui.QCheckBox()):
                    self.TabPlugins.setCellWidget(m, n, item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(
                        m, n, self.bt_SettingsDict[item['name']])
                else:
                    item = QtGui.QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(list(self.THeaders.keys()))

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(
                self.config.get_setting('plugins', box, format=bool))

        self.mainLayout.addWidget(self.tabcontrol)
        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.setLayout(self.layout)
예제 #32
0
    def __init__(self,main_method,parent = None):
        super(PumpkinMitmproxy, self).__init__(parent)
        self.mainLayout     = QVBoxLayout()
        self.config         = SettingsINI('core/config/app/proxy.ini')
        self.plugins        = []
        self.main_method    = main_method
        self.bt_SettingsDict    = {}
        self.check_PluginDict   = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)

        self.TabPlugins = QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders  = OrderedDict([ ('Plugins',[]),('Settings',[]),('Description',[])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0,158)
        self.TabPlugins.horizontalHeader().resizeSection(1,80)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QPushButton('Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(partial(self.setSettingsPlgins,plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QPushButton('None')
            self.check_PluginDict[plugin.Name] = QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(partial(self.setPluginOption,plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QCheckBox()):
                    self.TabPlugins.setCellWidget(m,n,item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(m,n,self.bt_SettingsDict[item['name']])
                else:
                    item = QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(self.config.get_setting('plugins',box,format=bool))

        self.mainLayout.addWidget(self.TabPlugins)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.addLayout(self.layout)
예제 #33
0
파일: handler.py 프로젝트: reo12345/reo
class MasterHandler(flow.FlowMaster):
    def __init__(self, opts, server, state, session):
        flow.FlowMaster.__init__(self, opts, server, state)
        self.config = SettingsINI('core/config/app/proxy.ini')
        self.session = session
        self.plugins = []
        self.initializePlugins()

    def run(self, send):
        self.sendMethod = send
        for plugin in self.plugins:
            plugin.send_output = self.sendMethod
        self.thread = ThreadController(self)
        self.thread.start()

    def disablePlugin(self, name, status):
        ''' disable plugin by name '''
        plugin_on = []
        if status:
            for plugin in self.plugins:
                plugin_on.append(plugin.Name)
            if name not in plugin_on:
                for p in self.plugin_classes:
                    pluginconf = p()
                    if pluginconf.Name == name:
                        pluginconf.send_output = self.sendMethod
                        print('PumpkinProxy::{0:17} status:On'.format(name))
                        self.plugins.append(pluginconf)
        else:
            for plugin in self.plugins:
                if plugin.Name == name:
                    print('PumpkinProxy::{0:17} status:Off'.format(name))
                    self.plugins.remove(plugin)

    def initializePlugins(self):
        self.plugin_classes = plugin.PluginTemplate.__subclasses__()
        for p in self.plugin_classes:
            if self.config.get_setting('plugins', p().Name, format=bool):
                print('PumpkinProxy::{0:17} status:On'.format(p().Name))
                self.plugins.append(p())
        # initialize logging in all plugins enable
        #for instance in self.plugins:
        #    instance.init_logger(self.session)

    @controller.handler
    def request(self, flow):
        '''
        print "-- request --"
        print flow.__dict__
        print flow.request.__dict__
        print flow.request.headers.__dict__
        print "--------------"
        print
        '''
        try:
            for p in self.plugins:
                p.request(flow)
        except Exception:
            pass

    @controller.handler
    def response(self, flow):
        '''
        print
        print "-- response --"
        print flow.__dict__
        print flow.response.__dict__
        print flow.response.headers.__dict__
        print "--------------"
        print
        '''
        try:
            for p in self.plugins:
                p.response(flow)
        except Exception:
            pass
    def __init__(self,main_method,parent = None):
        super(PacketsSniffer, self).__init__(parent)
        self.mainLayout     = QVBoxLayout()
        self.config         = SettingsINI(C.TCPPROXY_INI)
        self.plugins        = []
        self.main_method    = main_method
        self.bt_SettingsDict    = {}
        self.check_PluginDict   = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)

        self.tabcontrol = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.page_1 = QVBoxLayout(self.tab1)
        self.page_2 = QVBoxLayout(self.tab2)
        self.tableLogging  = dockTCPproxy()

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        self.tabcontrol.addTab(self.tab2, 'Logging')

        self.TabPlugins = QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders  = OrderedDict([ ('Plugins',[]),('Author',[]),('Description',[])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0,158)
        self.TabPlugins.horizontalHeader().resizeSection(1,120)

        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.tableLogging)
        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            self.bt_SettingsDict[plugin.Name] = QPushButton(plugin.Author)
            self.check_PluginDict[plugin.Name] = QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(partial(self.setPluginOption,plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Author'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QCheckBox()):
                    self.TabPlugins.setCellWidget(m,n,item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(m,n,self.bt_SettingsDict[item['name']])
                else:
                    item = QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(self.config.get_setting('plugins',box,format=bool))

        self.mainLayout.addWidget(self.tabcontrol)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.addLayout(self.layout)
예제 #35
0
class PumpkinMitmproxy(ProxyMode):
    ''' settings  Transparent Proxy '''
    Name = "Pumpkin Proxy"
    Author = "Pumpkin-Dev"
    Description = "Intercepting HTTP data, this proxy server that allows to intercept requests and response on the fly"
    Icon = "icons/pumpkinproxy.png"
    ModSettings = True
    Hidden = False
    ModType = "proxy"  # proxy or server
    _cmd_array = []
    sendError = QtCore.pyqtSignal(str)

    def __init__(self, parent, **kwargs):
        super(PumpkinMitmproxy, self).__init__(parent)
        self.mainLayout = QtGui.QVBoxLayout()
        self.config = SettingsINI(C.PUMPPROXY_INI)
        self.plugins = []
        self.main_method = parent
        self.bt_SettingsDict = {}
        self.check_PluginDict = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QtGui.QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)
        self.dockwidget = PumpkinProxyDock(None, title=self.Name)
        self.search[self.Name] = str(
            'iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080'
        )

        # create for add dock logging
        self.tabcontrol = QtGui.QTabWidget()
        self.tab1 = QtGui.QWidget()
        self.tab2 = QtGui.QWidget()
        self.page_1 = QtGui.QVBoxLayout(self.tab1)
        self.page_2 = QtGui.QVBoxLayout(self.tab2)
        self.tableLogging = dockPumpkinProxy()

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        #self.tabcontrol.addTab(self.tab2, 'Logging')

        self.TabPlugins = QtGui.QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                      QtGui.QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders = OrderedDict([('Plugins', []), ('Settings', []),
                                     ('Description', [])])
        self.TabPlugins.setHorizontalHeaderLabels(list(self.THeaders.keys()))
        self.TabPlugins.horizontalHeader().resizeSection(0, 158)
        self.TabPlugins.horizontalHeader().resizeSection(1, 80)

        # add on tab
        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.tableLogging)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton(
                    'Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(
                    partial(self.setSettingsPlgins, plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton('None')
            self.check_PluginDict[plugin.Name] = QtGui.QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(
                partial(self.setPluginOption, plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QtGui.QCheckBox()):
                    self.TabPlugins.setCellWidget(m, n, item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(
                        m, n, self.bt_SettingsDict[item['name']])
                else:
                    item = QtGui.QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(list(self.THeaders.keys()))

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(
                self.config.get_setting('plugins', box, format=bool))

        self.mainLayout.addWidget(self.tabcontrol)
        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.setLayout(self.layout)

    def setPluginOption(self, name, status):
        ''' get each plugins status'''
        # enable realtime disable and enable plugin
        if self.FSettings.Settings.get_setting('accesspoint',
                                               'statusAP',
                                               format=bool):
            self.reactor.ThreadPumpkinProxy.m.disablePlugin(name, status)
        self.config.set_setting('plugins', name, status)

    def setSettingsPlgins(self, plugin):
        ''' open settings options for each plugins'''
        key = 'set_{}'.format(plugin)
        self.widget = PumpkinProxySettings(key,
                                           self.config.get_all_childname(key))
        self.widget.show()

    def search_all_ProxyPlugins(self):
        ''' load all plugins function '''
        try:
            plugin_classes = plugin.PluginTemplate.__subclasses__()
            for p in plugin_classes:
                self.plugins.append(p())
        except NameError:
            infoLabel = ServiceNotify(C.PUMPKINPROXY_notify,
                                      title='Package Requirement')
            self.mainLayout.addWidget(infoLabel)

    def boot(self):
        self.reactor = ThreadPumpkinProxy(self.parent.currentSessionID)
        self.reactor.send.connect(self.LogOutput)
        self.reactor.setObjectName(self.Name)
        self.SetRules("PumpkinProxy")

    def LogOutput(self, data):
        if self.FSettings.Settings.get_setting('accesspoint',
                                               'statusAP',
                                               format=bool):
            self.dockwidget.writeModeData(data)
            self.logger.info(data)

    def Serve(self, on=True):
        if on:
            self.tableLogging.clearContents()
            plugin_classes = plugin.PluginTemplate.__subclasses__()
            for p in plugin_classes:
                self.plugins.append(p())
        # pumpkinproxy not use reactor twistted
        #self.server.start()
    def onProxyEnabled(self):
        self.SetRules(self.Name)
예제 #36
0
    check_dep_pumpkin()
    from os import getuid
    if not getuid() == 0:
        exit('[{}!{}] WiFi-Pumpkin must be run as root.'.format(C.RED,C.ENDC))

    app = ApplicationLoop(argv)
    if app.isRunning():
        QtGui.QMessageBox.warning(None,'Already Running','the wifi-pumpkin is already running')
        exit('WiFi-Pumpkin Already Running.')

    print('Loading GUI...')
    main = Initialize()
    main.setWindowIcon(QtGui.QIcon('icons/icon.png'))
    main.center()
    # check if Wireless connection
    conf = SettingsINI(C.CONFIG_INI)
    if  conf.get_setting('accesspoint','checkConnectionWifi',format=bool):
        networkcontrol = CLI_NetworkManager() # add all interface avaliable for exclude
        main.networkcontrol = networkcontrol
        if networkcontrol.run():
            if  networkcontrol.isWiFiConnected() and len(networkcontrol.ifaceAvaliable) > 0:
                settings = UI_NetworkManager(main)
                settings.setWindowIcon(QtGui.QIcon('icons/icon.png'))
                settings.show()
                exit(app.exec_())
    main.show()

    print('WiFi-Pumpkin Running!')
    exit(app.exec_())
예제 #37
0
class SettingsDialog(QtGui.QDialog, Ui_settingsDialog):
    signalSettingsExported = QtCore.Signal(SettingsINI, str)
    signalSettingsImported = QtCore.Signal(SettingsINI, str)
    signalSettingsSaved = QtCore.Signal(SettingsINI, str)
    _themes_dir = THEMES_DIR

    def __init__(self, settings=None, **kwargs):
        QtGui.QDialog.__init__(self, **kwargs)
        self.setupUi(self)

        if isinstance(settings, SettingsINI):
            self.Config = settings
        else:
            self.Config = SettingsINI(settings)

        self.configure_settings(self.Config)
        self.connect_buttons()

    @property
    def _settings_filename(self):
        return self.Config._filename

    def connect_buttons(self):
        self.btnSave.clicked.connect(self.save_settings)
        self.btnExport.clicked.connect(self.export_settings)
        self.btnImport.clicked.connect(self.import_settings)
        self.btnLogDirectory.clicked.connect(self.open_log_directory)
        self.btnRootDirectory.clicked.connect(self.open_root_directory)
        self.btnSetDefault.clicked.connect(partial(self.export_settings, self.Config.default_path, set_self=True))
        self.btnReset.clicked.connect(self.reset_settings)

    def configure_settings(self, config):
        """
        Configures settings based on a SettingsINI object.
        Defaults are contained in here.
        Top-level configurations read from.:
            GENERAL
            INPUT
            OUTPUT
            DATABASE
            FIELDS
        """
        if not isinstance(config, SettingsINI):
            raise NotImplementedError("config must be a SettingsINI object.")
            
        try:
            genconfig = config['GENERAL']
            inconfig  = config['INPUT']
            outconfig = config['OUTPUT']
            dbconfig  = config['DATABASE']
        except KeyError as e:
            raise KeyError("SettingsINI object missing config option '{}'".format(e))
            
        # Get items/set defaults.
        ROOT_DIR =        genconfig.get('ROOT_DIRECTORY',  DEFAULT_ROOT_DIR)
        LOG_DIR =         genconfig.get('LOG_DIRECTORY',   DEFAULT_LOG_DIR)
        LOG_LEVEL =       genconfig.get('LOG_LEVEL',       "Low")
        CLOUD_PROVIDER =  genconfig.get('CLOUD_PROVIDER',  "S3")
        THEME_NAME     =  genconfig.get('THEME',           DEFAULT_THEME)
        HEADER_CASE =     inconfig.get('HEADER_CASE',      "Lower")
        HEADER_SPACE =    inconfig.get('HEADER_SPACE',     "_")
        AUTO_SORT =       inconfig.get('AUTO_SORT',        False)
        AUTO_DEDUPE =     inconfig.get('AUTO_DEDUPE',      False)
        OUTPUT_FORMAT =   outconfig.get('OUTPUT_FORMAT',   ".csv")
        FILENAME_PFX =    outconfig.get('FILENAME_PREFIX', "z_")
        CHART_FILE =      outconfig.get('CHART_FILENAME',  "")
        SEPARATOR =       outconfig.get('SEPARATOR',       ",")
        ENCODING =        outconfig.get('ENCODING',        "UTF_8")
        DB_FLAVOR =       dbconfig.get('FLAVOR',           "SQLITE")
        DB_URL =          dbconfig.get('URL',              "")
        DB_NAME =         dbconfig.get('DEFAULT_DATABASE', None)
        DB_USERNAME =     dbconfig.get('USERNAME',         None)
        DB_PASSWORD =     dbconfig.get('PASSWORD',         None)
        DB_PORT =         dbconfig.get('PORT',             None)


        DEDUPE_FIELDS =   config.get_safe('FIELDS', 'DEDUPE', fallback=[])
        SORT_FIELDS   =   config.get_safe('FIELDS', 'SORT',   fallback=['updatedate', 'insertdate'])
        STRING_FIELDS =   config.get_safe('FIELDS', 'STRING', fallback=['address1','firstname','lastname',
                                                              'city','state','zipcode', 'fullname',
                                                              'email','homephone','cellphone'])
        INTEGER_FIELDS =  config.get_safe('FIELDS', 'INTEGER',fallback=['id','users_id'])
        DATE_FIELDS   =   config.get_safe('FIELDS', 'DATE',   fallback=['insertdate','updatedate'])
        FLOAT_FIELDS =    config.get_safe('FIELDS', 'FLOAT',   fallback=[])

        #Make sure the directories exist.
        for fp in [ROOT_DIR, LOG_DIR]:
            try:
                if not os.path.exists(fp):
                    os.mkdir(fp)
            except OSError as e:
                raise OSError("Cannot initialize settings directory {}".format(fp))
                sys.exit(1)

        self.autoSortCheckBox.setCheckable(True)
        self.autoDedupeCheckBox.setCheckable(True)

        if AUTO_SORT:
            self.autoSortCheckBox.setChecked(True)

        if AUTO_DEDUPE:
            self.autoSortCheckBox.setChecked(True)
        
        #LINE EDITS
        self.rootDirectoryLineEdit.setText(      ROOT_DIR)
        self.logDirectoryLineEdit.setText(       LOG_DIR)
        self.fileNamePrefixLineEdit.setText(     FILENAME_PFX)
        self.chartSettingsFileLineEdit.setText(  CHART_FILE)
        self.urlLineEdit.setText(                DB_URL)
        self.defaultDatabaseLineEdit.setText(    DB_NAME)
        self.usernameLineEdit.setText(           DB_USERNAME)
        self.passwordLineEdit.setText(           DB_PASSWORD)
        self.portLineEdit.setText(               DB_PORT)
        
        #COMBO BOXES
        configureComboBox(self.logLevelComboBox,      ['Low', 'Medium', 'High'],         LOG_LEVEL)
        configureComboBox(self.cloudProviderComboBox, ['Google Drive', 'S3', 'DropBox'], CLOUD_PROVIDER)
        configureComboBox(self.headerCaseComboBox,    ['lower', 'UPPER', 'Proper'],      HEADER_CASE)
        configureComboBox(self.headerSpacesComboBox,  [' ', '_'],                        HEADER_SPACE)
        configureComboBox(self.fileFormatComboBox,    DEFAULT_FILE_FORMATS,              OUTPUT_FORMAT)
        configureComboBox(self.flavorComboBox,        DEFAULT_FLAVORS,                   DB_FLAVOR)
        configureComboBox(self.separatorComboBox,     DEFAULT_SEPARATORS,                SEPARATOR)
        configureComboBox(self.encodingComboBox,      DEFAULT_CODECS,                    ENCODING)
        configureComboBox(self.themeComboBox,         DEFAULT_THEME_OPTIONS,             THEME_NAME)
        self.set_theme(THEME_NAME)
        
        #Field Models
        self.dedupeFieldsModel = FieldsListModel(items=DEDUPE_FIELDS)
        self.sortFieldsModel   = FieldsListModel(items=SORT_FIELDS)
        self.strFieldsModel    = FieldsListModel(items=STRING_FIELDS)
        self.intFieldsModel    = FieldsListModel(items=INTEGER_FIELDS)
        self.dateFieldsModel   = FieldsListModel(items=DATE_FIELDS)
        self.floatFieldsModel  = FieldsListModel(items=FLOAT_FIELDS)
        
        self.dedupeFieldsListView.setModel(self.dedupeFieldsModel)
        self.sortFieldsColumnView.setModel(self.sortFieldsModel)
        self.strFieldsListView.setModel(   self.strFieldsModel)
        self.intFieldsListView.setModel(   self.intFieldsModel)
        self.dateFieldsListView.setModel(  self.dateFieldsModel)
        self.floatFieldsListView.setModel( self.floatFieldsModel)

        self.save_settings(to_path=None, write=False)
        
    def save_settings(self, to_path=None, write=False):
        self.set_theme()

        self.Config.set('GENERAL', 'ROOT_DIRECTORY', self.rootDirectoryLineEdit.text())
        self.Config.set('GENERAL', 'LOG_DIRECTORY', self.logDirectoryLineEdit.text())
        self.Config.set('GENERAL', 'LOG_LEVEL', self.logLevelComboBox.currentText())
        self.Config.set('GENERAL', 'CLOUD_PROVIDER', self.cloudProviderComboBox.currentText())
        self.Config.set('GENERAL', 'THEME', self.themeComboBox.currentText())

        self.Config.set('INPUT', 'HEADER_CASE', self.headerCaseComboBox.currentText())
        self.Config.set('INPUT', 'HEADER_SPACE', self.headerSpacesComboBox.currentText())
        self.Config.set_safe('INPUT', 'AUTO_SORT', self.autoSortCheckBox.isChecked())
        self.Config.set_safe('INPUT', 'AUTO_DEDUPE', self.autoDedupeCheckBox.isChecked())

        self.Config.set('OUTPUT', 'OUTPUT_FORMAT', self.fileFormatComboBox.currentText())
        self.Config.set('OUTPUT', 'FILENAME_PREFIX', self.fileNamePrefixLineEdit.text())
        self.Config.set('OUTPUT', 'CHART_FILENAME', self.chartSettingsFileLineEdit.text())

        self.Config.set('DATABASE', 'FLAVOR', self.flavorComboBox.currentText())
        self.Config.set('DATABASE', 'URL', self.urlLineEdit.text())
        self.Config.set('DATABASE', 'DEFAULT_DATABASE', self.defaultDatabaseLineEdit.text())
        self.Config.set('DATABASE', 'USERNAME', self.usernameLineEdit.text())
        self.Config.set('DATABASE', 'PASSWORD', self.passwordLineEdit.text())

        self.Config.set_safe('FIELDS', 'DEDUPE',  self.dedupeFieldsModel.get_data_list())
        self.Config.set_safe('FIELDS', 'SORT',    self.sortFieldsModel.get_data_list())
        self.Config.set_safe('FIELDS', 'STRING',  self.strFieldsModel.get_data_list())
        self.Config.set_safe('FIELDS', 'DATE',    self.dateFieldsModel.get_data_list())
        self.Config.set_safe('FIELDS', 'INTEGER', self.intFieldsModel.get_data_list())
        self.Config.set_safe('FIELDS', 'FLOAT', self.floatFieldsModel.get_data_list())

        if write or to_path is not None:
            if to_path is None:
                to_path = self.Config._filename

            self.Config._filename = to_path

            self.Config.save()

        self.signalSettingsSaved.emit(self.Config, self.Config.filename)

    def clear_settings(self):
        self.cloudProviderComboBox.clear()
        self.encodingComboBox.clear()
        self.fileFormatComboBox.clear()
        self.flavorComboBox.clear()
        self.headerCaseComboBox.clear()
        self.headerSpacesComboBox.clear()
        self.logLevelComboBox.clear()
        self.separatorComboBox.clear()
        self.themeComboBox.clear()


    def export_settings(self, to=None, set_self=False):
        if to is None:
            to = QtGui.QFileDialog.getSaveFileName()[0]
        self.save_settings(to_path=None, write=False)
        self.Config.save_as(to, set_self=set_self)
        self.signalSettingsExported.emit(self.Config, to)

    def set_theme(self, theme_name=None):
        if theme_name is None:
            theme_name = self.themeComboBox.currentText()
            if isinstance(theme_name, int):
                print("No theme selected.")
                theme_name = THEME_NAME2

        theme_path = normpath(self._themes_dir, theme_name)

        if os.path.exists(theme_path):
            with open(theme_path, "r") as fh:
                app = QtCore.QCoreApplication.instance()
                app.setStyleSheet(fh.read())
        else:
            print("Couldnt find theme {}!".format(theme_path))

    def import_settings(self, filename=None):
        if filename is None:
            filename = QtGui.QFileDialog.getOpenFileName()

        self.Config.save()
        self.Config.clear()
        self.Config.read(filename)
        self.Config._filename = filename
        self.clear_settings()
        self.configure_settings(self.Config)

    def reset_settings(self):
        self.Config.clear()
        self.Config.read(self.Config.backup_path)
        self.Config.save_as(self.Config.default_path, set_self=True)
        self.clear_settings()
        self.configure_settings(self.Config)

    def open_root_directory(self):
        dirname = QtGui.QFileDialog.getExistingDirectory()
        self.rootDirectoryLineEdit.setText(dirname)

    def open_log_directory(self):
        dirname = QtGui.QFileDialog.getExistingDirectory()
        self.logDirectoryLineEdit.setText(dirname)






        
예제 #38
0
    def __init__(self, parent, **kwargs):
        super(CaptivePortal, self).__init__(parent)
        self.mainLayout = QtGui.QVBoxLayout()
        self.config = SettingsINI(C.CAPTIVEPORTAL_INI)
        self.plugins = []
        self.plugin_activated = None
        self.main_method = parent
        self.bt_SettingsDict = {}
        self.check_PluginDict = {}
        self.ClientsLogged = {}
        self.btn_previewSettings = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QtGui.QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)
        self.dockwidget = CaptivePortalDock(None, title=self.Name)

        # create for add dock logging
        self.tabcontrol = QtGui.QTabWidget()
        self.tab1 = QtGui.QWidget()
        self.tab2 = QtGui.QWidget()
        self.page_1 = QtGui.QVBoxLayout(self.tab1)
        self.page_2 = QtGui.QVBoxLayout(self.tab2)

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        self.tabcontrol.addTab(self.tab2, 'Manager')
        self.TabCtrlClients = QtGui.QTableWidget()
        self.TabCtrlClients.setColumnCount(3)
        #self.TabCtrlClients.setRowCount(len(self.plugins))
        self.TabCtrlClients.resizeRowsToContents()
        self.TabCtrlClients.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                          QtGui.QSizePolicy.Preferred)
        self.TabCtrlClients.horizontalHeader().setStretchLastSection(True)
        self.TabCtrlClients.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.TabCtrlClients.setEditTriggers(
            QtGui.QAbstractItemView.NoEditTriggers)
        self.TabCtrlClients.verticalHeader().setVisible(False)
        self.TabCtrlClients.verticalHeader().setDefaultSectionSize(27)
        self.TabCtrlClients.setSortingEnabled(True)
        self.THeadersCtrlClients = OrderedDict([('IpAddress', []),
                                                ('MacAddress', []),
                                                ('Status Internet', [])])
        self.TabCtrlClients.setHorizontalHeaderLabels(
            self.THeadersCtrlClients.keys())

        self.mainLayout_settings = QtGui.QVBoxLayout()
        #scroll area
        self.scrollwidget_settings = QtGui.QWidget()
        self.scrollwidget_settings.setLayout(self.mainLayout_settings)
        self.scroll_settings = QtGui.QScrollArea()
        self.scroll_settings.setWidgetResizable(True)
        self.scroll_settings.setWidget(self.scrollwidget_settings)

        # create widgets
        self.argsLabel = QtGui.QLabel('')
        self.hBox = QtGui.QHBoxLayout()
        self.btnEnable = QtGui.QPushButton('Allow')
        self.btncancel = QtGui.QPushButton('Deny')

        # size buttons
        self.btnEnable.setFixedWidth(100)
        self.btncancel.setFixedWidth(100)

        self.comboxBoxIPAddress = QtGui.QComboBox()
        self.btncancel.setIcon(QtGui.QIcon('icons/cancel.png'))
        self.btnEnable.setIcon(QtGui.QIcon('icons/accept.png'))

        # group settings
        self.GroupSettings = QtGui.QGroupBox()
        self.GroupSettings.setTitle('Manage clients access:')
        self.SettingsLayout = QtGui.QFormLayout()
        self.hBox.addWidget(self.comboxBoxIPAddress)
        self.hBox.addWidget(self.btnEnable)
        self.hBox.addWidget(self.btncancel)
        self.SettingsLayout.addRow(self.hBox)
        self.GroupSettings.setLayout(self.SettingsLayout)
        #self.GroupSettings.setFixedWidth(450)

        #group logger
        self.GroupLogger = QtGui.QGroupBox()
        self.logger_portal = QtGui.QListWidget()
        self.GroupLogger.setTitle('Logger events:')
        self.LoggerLayout = QtGui.QVBoxLayout()
        self.LoggerLayout.addWidget(self.logger_portal)
        self.GroupLogger.setLayout(self.LoggerLayout)
        #self.GroupLogger.setFixedWidth(450)

        #connections
        # self.btnLoader.clicked.connect(self.SearchProxyPlugins)
        self.connect(self.comboxBoxIPAddress,
                     QtCore.SIGNAL('currentIndexChanged(QString)'),
                     self.checkStatusClient)
        self.btnEnable.clicked.connect(self.enableInternetConnection)
        self.btncancel.clicked.connect(self.disableInternetConnection)
        # self.btnbrownser.clicked.connect(self.get_filenameToInjection)
        # add widgets
        self.mainLayout_settings.addWidget(self.GroupSettings)
        self.mainLayout_settings.addWidget(self.GroupLogger)

        self.TabPlugins = QtGui.QTableWidget()
        self.TabPlugins.setColumnCount(5)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                      QtGui.QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders = OrderedDict([('Captive Name', []), ('Preview', []),
                                     ('Author', []), ('Settings', []),
                                     ('Description', [])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0, 158)
        self.TabPlugins.horizontalHeader().resizeSection(1, 80)

        # add on tab
        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.scroll_settings)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton(
                    'Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(
                    partial(self.setSettingsPlgins, plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton('None')

            if (path.isfile(plugin.Preview)):
                self.btn_previewSettings[plugin.Name] = QtGui.QPushButton(
                    'Preview')
                self.btn_previewSettings[plugin.Name].setObjectName(
                    plugin.Preview)
                self.btn_previewSettings[plugin.Name].clicked.connect(
                    partial(self.showPreviewCaptivePortal, plugin.Name))
            else:
                self.btn_previewSettings[plugin.Name] = QtGui.QPushButton(
                    'Not found')

            self.check_PluginDict[plugin.Name] = QtGui.QRadioButton(
                plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(
                partial(self.setPluginOption, plugin.Name))
            self.THeaders['Captive Name'].append(
                self.check_PluginDict[plugin.Name])
            self.THeaders['Preview'].append(
                self.btn_previewSettings[plugin.Name])
            self.THeaders['Author'].append(plugin.Author)
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QtGui.QRadioButton()):
                    self.TabPlugins.setCellWidget(m, n, item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(
                        m, n, self.bt_SettingsDict[item['name']])
                elif type(item) == type(QtGui.QPushButton()):
                    self.TabPlugins.setCellWidget(m, n, item)
                else:
                    item = QtGui.QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(
                self.config.get_setting('plugins', box, format=bool))

        self.btn_updateCaptive = QtGui.QPushButton("Update")
        self.btn_updateCaptive.setIcon(QtGui.QIcon('icons/updates_.png'))
        self.btn_updateCaptive.setFixedWidth(130)
        self.btn_updateCaptive.clicked.connect(self.disableBtnForUpdates)

        self.mainLayout.addWidget(self.tabcontrol)
        self.mainLayout.addWidget(self.btn_updateCaptive)
        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.setLayout(self.layout)
class PumpkinMitmproxy(QVBoxLayout):
    ''' settings  Transparent Proxy '''
    sendError = pyqtSignal(str)
    def __init__(self,main_method,parent = None):
        super(PumpkinMitmproxy, self).__init__(parent)
        self.mainLayout     = QVBoxLayout()
        self.config         = SettingsINI(C.PUMPPROXY_INI)
        self.plugins        = []
        self.main_method    = main_method
        self.bt_SettingsDict    = {}
        self.check_PluginDict   = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)

        # create for add dock logging
        self.tabcontrol = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.page_1 = QVBoxLayout(self.tab1)
        self.page_2 = QVBoxLayout(self.tab2)
        self.tableLogging  = dockPumpkinProxy()

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        self.tabcontrol.addTab(self.tab2, 'Logging')

        self.TabPlugins = QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders  = OrderedDict([ ('Plugins',[]),('Settings',[]),('Description',[])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0,158)
        self.TabPlugins.horizontalHeader().resizeSection(1,80)

        # add on tab
        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.tableLogging)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QPushButton('Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(partial(self.setSettingsPlgins,plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QPushButton('None')
            self.check_PluginDict[plugin.Name] = QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(partial(self.setPluginOption,plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QCheckBox()):
                    self.TabPlugins.setCellWidget(m,n,item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(m,n,self.bt_SettingsDict[item['name']])
                else:
                    item = QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(self.config.get_setting('plugins',box,format=bool))

        self.mainLayout.addWidget(self.tabcontrol)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.addLayout(self.layout)

    def setPluginOption(self, name,status):
        ''' get each plugins status'''
        # enable realtime disable and enable plugin
        if self.main_method.PopUpPlugins.check_pumpkinProxy.isChecked() and \
            self.main_method.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool):
                self.main_method.Thread_PumpkinProxy.m.disablePlugin(name, status)
        self.config.set_setting('plugins',name,status)

    def setSettingsPlgins(self,plugin):
        ''' open settings options for each plugins'''
        key = 'set_{}'.format(plugin)
        self.widget = PumpkinProxySettings(key,self.config.get_all_childname(key))
        self.widget.show()

    def search_all_ProxyPlugins(self):
        ''' load all plugins function '''
        plugin_classes = plugin.PluginTemplate.__subclasses__()
        for p in plugin_classes:
            self.plugins.append(p())
예제 #40
0
 def __init__(self, interface, session):
     QThread.__init__(self)
     self.interface = interface
     self.session = session
     self.stopped = False
     self.config = SettingsINI(C.TCPPROXY_INI)
예제 #41
0
    if not getuid() == 0:
        exit('[{}!{}] WiFi-Pumpkin must be run as root.'.format(C.RED, C.ENDC))

    app = ApplicationLoop(argv)
    if app.isRunning():
        QtGui.QMessageBox.warning(None, 'Already Running',
                                  'the wifi-pumpkin is already running')
        exit('WiFi-Pumpkin Already Running.')

    print('Loading GUI...')
    main = Initialize()
    main.passSettings()
    main.setWindowIcon(QtGui.QIcon('icons/icon.png'))
    main.center()
    # check if Wireless connection
    conf = SettingsINI(C.CONFIG_INI)
    if conf.get_setting('accesspoint', 'checkConnectionWifi', format=bool):
        networkcontrol = CLI_NetworkManager(
        )  # add all interface avaliable for exclude
        main.networkcontrol = networkcontrol
        if networkcontrol.run():
            if networkcontrol.isWiFiConnected() and len(
                    networkcontrol.ifaceAvaliable) > 0:
                settings = UI_NetworkManager(main)
                settings.setWindowIcon(QtGui.QIcon('icons/icon.png'))
                settings.show()
                exit(app.exec_())
    main.show()

    print('WiFi-Pumpkin Running!')
    exit(app.exec_())
예제 #42
0
class TCPProxy(ProxyMode):
    Name = "TCP Proxy"
    Author = "Pumpkin-Dev"
    Description = "Sniff for intercept network traffic on UDP,TCP protocol get password,hash,image,etc..."
    Icon = "icons/tcpproxy.png"
    Hidden = False
    LogFile = C.LOG_TCPPROXY
    _cmd_array = []
    ModSettings = True
    ModType = "proxy"  # proxy or server
    TypePlugin = 2  # 1 != for  checkbox

    def __init__(self, parent=None, **kwargs):
        super(TCPProxy, self).__init__(parent)
        self.mainLayout = QtGui.QVBoxLayout()
        self.config = SettingsINI(C.TCPPROXY_INI)
        self.plugins = []
        self.parent = parent
        self.bt_SettingsDict = {}
        self.check_PluginDict = {}
        self.search_all_ProxyPlugins()
        # scroll area
        self.scrollwidget = QtGui.QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QtGui.QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)

        setup_logger("NetCreds", C.LOG_CREDSCAPTURE, "CapturedCreds")
        self.LogCredsMonitor = logging.getLogger("NetCreds")

        self.tabcontrol = QtGui.QTabWidget()
        self.tab1 = QtGui.QWidget()
        self.tab2 = QtGui.QWidget()
        self.page_1 = QtGui.QVBoxLayout(self.tab1)
        self.page_2 = QtGui.QVBoxLayout(self.tab2)
        self.tableLogging = dockTCPproxy()

        self.tabcontrol.addTab(self.tab1, 'Plugins')
        self.tabcontrol.addTab(self.tab2, 'Logging')

        self.TabPlugins = QtGui.QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                      QtGui.QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders = OrderedDict([('Plugins', []), ('Author', []),
                                     ('Description', [])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0, 158)
        self.TabPlugins.horizontalHeader().resizeSection(1, 120)

        self.dockwidget = TCPProxyDock(None, title=self.Name)

        self.page_1.addWidget(self.TabPlugins)
        self.page_2.addWidget(self.tableLogging)
        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            self.bt_SettingsDict[plugin.Name] = QtGui.QPushButton(
                plugin.Author)
            self.check_PluginDict[plugin.Name] = QtGui.QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(
                partial(self.setPluginOption, plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Author'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QtGui.QCheckBox()):
                    self.TabPlugins.setCellWidget(m, n, item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(
                        m, n, self.bt_SettingsDict[item['name']])
                else:
                    item = QtGui.QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(
                self.config.get_setting('plugins', box, format=bool))

        self.mainLayout.addWidget(self.tabcontrol)
        self.layout = QtGui.QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.setLayout(self.layout)

    def onProxyDisabled(self):
        self.handler = self.parent.Plugins.MITM
        self.handler.CredMonitor.controlui.setChecked(False)
        self.handler.URLMonitor.controlui.setChecked(False)

    def onProxyEnabled(self):
        self.handler = self.parent.Plugins.MITM
        self.handler.CredMonitor.controlui.setChecked(True)
        self.handler.URLMonitor.controlui.setChecked(True)

    def setPluginOption(self, name, status):
        ''' get each plugins status'''
        # enable realtime disable and enable plugin
        if self.FSettings.Settings.get_setting('accesspoint',
                                               'statusAP',
                                               format=bool):
            self.reactor.disablePlugin(name, status)
        self.config.set_setting('plugins', name, status)

    def search_all_ProxyPlugins(self):
        ''' load all plugins function '''
        plugin_classes = default.PSniffer.__subclasses__()
        for p in plugin_classes:
            if p().Name != 'httpCap':
                self.plugins.append(p())

    def boot(self):
        self.handler = self.parent.Plugins.MITM
        self.reactor = TCPProxyCore(str(self.Wireless.WLANCard.currentText()),
                                    self.parent.currentSessionID)
        self.reactor.setObjectName(self.Name)
        self.reactor._ProcssOutput.connect(self.LogOutput)

    def LogOutput(self, data):
        if self.FSettings.Settings.get_setting('accesspoint',
                                               'statusAP',
                                               format=bool):
            if data.keys()[0] == 'urlsCap':
                self.handler.URLMonitor.dockwidget.writeModeData(data)
                self.logger.info(
                    '[ {0[src]} > {0[dst]} ] {1[Method]} {1[Host]}{1[Path]}'.
                    format(data['urlsCap']['IP'], data['urlsCap']['Headers']))
            elif data.keys()[0] == 'POSTCreds':
                self.handler.CredMonitor.dockwidget.writeModeData(data)
                self.LogCredsMonitor.info('URL: {}'.format(
                    data['POSTCreds']['Url']))
                self.LogCredsMonitor.info('UserName: {}'.format(
                    data['POSTCreds']['User']))
                self.LogCredsMonitor.info('UserName: {}'.format(
                    data['POSTCreds']['Pass']))
                self.LogCredsMonitor.info('Packets: {}'.format(
                    data['POSTCreds']['Destination']))
            elif data.keys()[0] == 'image':
                self.handler.ImageCapture.SendImageTableWidgets(data['image'])
            else:
                self.tableLogging.writeModeData(data)
                self.LogTcpproxy.info('[{}] {}'.format(data.keys()[0],
                                                       data[data.keys()[0]]))
예제 #43
0
파일: handler.py 프로젝트: reo12345/reo
 def __init__(self, opts, server, state, session):
     flow.FlowMaster.__init__(self, opts, server, state)
     self.config = SettingsINI('core/config/app/proxy.ini')
     self.session = session
     self.plugins = []
     self.initializePlugins()
예제 #44
0
class PumpkinMitmproxy(QVBoxLayout):
    ''' settings  Transparent Proxy '''
    sendError = pyqtSignal(str)
    def __init__(self,main_method,parent = None):
        super(PumpkinMitmproxy, self).__init__(parent)
        self.mainLayout     = QVBoxLayout()
        self.config         = SettingsINI('core/config/app/proxy.ini')
        self.plugins        = []
        self.main_method    = main_method
        self.bt_SettingsDict    = {}
        self.check_PluginDict   = {}
        self.search_all_ProxyPlugins()
        #scroll area
        self.scrollwidget = QWidget()
        self.scrollwidget.setLayout(self.mainLayout)
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.scrollwidget)

        self.TabPlugins = QTableWidget()
        self.TabPlugins.setColumnCount(3)
        self.TabPlugins.setRowCount(len(self.plugins))
        self.TabPlugins.resizeRowsToContents()
        self.TabPlugins.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.TabPlugins.horizontalHeader().setStretchLastSection(True)
        self.TabPlugins.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.TabPlugins.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.TabPlugins.verticalHeader().setVisible(False)
        self.TabPlugins.verticalHeader().setDefaultSectionSize(27)
        self.TabPlugins.setSortingEnabled(True)
        self.THeaders  = OrderedDict([ ('Plugins',[]),('Settings',[]),('Description',[])])
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())
        self.TabPlugins.horizontalHeader().resizeSection(0,158)
        self.TabPlugins.horizontalHeader().resizeSection(1,80)

        # get all plugins and add into TabWidget
        Headers = []
        for plugin in self.plugins:
            if plugin.ConfigParser:
                self.bt_SettingsDict[plugin.Name] = QPushButton('Settings')
                self.bt_SettingsDict[plugin.Name].clicked.connect(partial(self.setSettingsPlgins,plugin.Name))
            else:
                self.bt_SettingsDict[plugin.Name] = QPushButton('None')
            self.check_PluginDict[plugin.Name] = QCheckBox(plugin.Name)
            self.check_PluginDict[plugin.Name].setObjectName(plugin.Name)
            self.check_PluginDict[plugin.Name].clicked.connect(partial(self.setPluginOption,plugin.Name))
            self.THeaders['Plugins'].append(self.check_PluginDict[plugin.Name])
            self.THeaders['Settings'].append({'name': plugin.Name})
            self.THeaders['Description'].append(plugin.Description)
        for n, key in enumerate(self.THeaders.keys()):
            Headers.append(key)
            for m, item in enumerate(self.THeaders[key]):
                if type(item) == type(QCheckBox()):
                    self.TabPlugins.setCellWidget(m,n,item)
                elif type(item) == type(dict()):
                    self.TabPlugins.setCellWidget(m,n,self.bt_SettingsDict[item['name']])
                else:
                    item = QTableWidgetItem(item)
                    self.TabPlugins.setItem(m, n, item)
        self.TabPlugins.setHorizontalHeaderLabels(self.THeaders.keys())

        # check status all checkbox plugins
        for box in self.check_PluginDict.keys():
            self.check_PluginDict[box].setChecked(self.config.get_setting('plugins',box,format=bool))

        self.mainLayout.addWidget(self.TabPlugins)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.scroll)
        self.addLayout(self.layout)

    def setPluginOption(self, name,status):
        ''' get each plugins status'''
        # enable realtime disable and enable plugin
        if self.main_method.PopUpPlugins.check_pumpkinProxy.isChecked() and \
            self.main_method.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool):
                self.main_method.Thread_PumpkinProxy.m.disablePlugin(name, status)
        self.config.set_setting('plugins',name,status)

    def setSettingsPlgins(self,plugin):
        ''' open settings options for each plugins'''
        key = 'set_{}'.format(plugin)
        self.widget = PumpkinProxySettings(key,self.config.get_all_childname(key))
        self.widget.show()

    def search_all_ProxyPlugins(self):
        ''' load all plugins function '''
        plugin_classes = plugin.PluginTemplate.__subclasses__()
        for p in plugin_classes:
            self.plugins.append(p())