Ejemplo n.º 1
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return min(int(text.replace(' ', ''), 16), (1 << 31) - 1)

    def textFromValue(self, value):
        s = ''

        for i, c in enumerate(reversed(hex(value).replace('0x', '').upper())):
            if i % 2 == 0:
                s = ' ' + s

            s = c + s

        s = s.strip()

        if len(s.replace(' ', '')) % 2 == 1:
            s = '0' + s

        return s
Ejemplo n.º 2
0
    def validate_text(self, text):
        """
        Validates and updates the entered text if necessary.
        Spaces are replaced by _ and capital letters are replaced by small.
        :param text: The text entered
        :type text: String
        """
        text_edit = self.sender()
        cursor_position = text_edit.cursorPosition()
        text_edit.setValidator(None)
        if len(text) == 0:
            return

        name_regex = QRegExp('^(?=.{0,40}$)[ _a-zA-Z][a-zA-Z0-9_ ]*$')
        name_validator = QRegExpValidator(name_regex)
        text_edit.setValidator(name_validator)
        QApplication.processEvents()
        last_character = text[-1:]
        state = name_validator.validate(text, text.index(last_character))[0]

        if state != QValidator.Acceptable:
            self.show_notification(
                '"{}" is not allowed at this position.'.format(last_character))
            text = text[:-1]
        else:
            # remove space and underscore at the beginning of the text
            if len(text) > 1:
                if text[0] == ' ' or text[0] == '_':
                    text = text[1:]

        self.blockSignals(True)
        text_edit.setText(text)
        text_edit.setCursorPosition(cursor_position)
        self.blockSignals(False)
        text_edit.setValidator(None)
Ejemplo n.º 3
0
class RomanSpinBox(QSpinBox):

    def __init__(self, parent=None):
        super(RomanSpinBox, self).__init__(parent)
        regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)"
                        r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$")
        regex.setCaseSensitivity(Qt.CaseInsensitive)
        self.validator = QRegExpValidator(regex, self)
        self.setRange(1, 3999)
        self.connect(self.lineEdit(), SIGNAL("textEdited(QString)"),
                     self.fixCase)


    def fixCase(self, text):
        self.lineEdit().setText(text.toUpper())


    def validate(self, text, pos):
        return self.validator.validate(text, pos)


    def valueFromText(self, text):
        return intFromRoman(unicode(text))


    def textFromValue(self, value):
        return romanFromInt(value)
Ejemplo n.º 4
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(
            QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return min(int(text.replace(' ', ''), 16), (1 << 31) - 1)

    def textFromValue(self, value):
        s = ''

        for i, c in enumerate(reversed(hex(value).replace('0x', '').upper())):
            if i % 2 == 0:
                s = ' ' + s

            s = c + s

        s = s.strip()

        if len(s.replace(' ', '')) % 2 == 1:
            s = '0' + s

        return s
Ejemplo n.º 5
0
 def checkState(value, pattern):
     regexp = QRegExp(pattern)
     validator = QRegExpValidator(regexp)
     state = validator.validate(value, 0)[0]
     if state == QValidator.Acceptable:
         return True
     else:
         return False
Ejemplo n.º 6
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return int(text, 16)

    def textFromValue(self, value):
        s = hex(value).replace('0x', '').upper()

        if len(s) == 1:
            s = '0' + s

        return s
Ejemplo n.º 7
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return int(text, 16)

    def textFromValue(self, value):
        s = hex(value).replace('0x', '').upper()

        if len(s) == 1:
            s = '0' + s

        return s
Ejemplo n.º 8
0
    def validate_text(self, text):
        """
        Validates and updates the entered text if necessary.
        Spaces are replaced by _ and capital letters are replaced by small.
        :param text: The text entered
        :type text: String
        """
        text_edit = self.sender()
        cursor_position = text_edit.cursorPosition()
        text_edit.setValidator(None)
        if len(text) == 0:
            return
        locale = QSettings().value("locale/userLocale")[0:2]

        if locale == 'en':
            name_regex = QRegExp('^(?=.{0,40}$)[ _a-zA-Z][a-zA-Z0-9_ ]*$')
            name_validator = QRegExpValidator(name_regex)
            text_edit.setValidator(name_validator)
            QApplication.processEvents()
            last_character = text[-1:]
            state = name_validator.validate(text, text.index(last_character))[0]
            if state != QValidator.Acceptable:
                msg = u'\'{0}\' is not allowed at this position.'.format(
                    last_character
                )
                self.show_notification(msg)
                text = text[:-1]

        # remove space and underscore at the beginning of the text
        if len(text) > 1:
            if text[0] == ' ' or text[0] == '_':
                text = text[1:]

        self.blockSignals(True)
        text_edit.setText(text)
        text_edit.setCursorPosition(cursor_position)
        self.blockSignals(False)
        text_edit.setValidator(None)
Ejemplo n.º 9
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None):
        super(SpinBoxHex, self).__init__(parent)
        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)
        self.setRange(0, 255)


    def fixCase(self, text):
        self.lineEdit().setText(text.toUpper())


    def validate(self, text, pos):
        return self.validator.validate(text, pos)


    def valueFromText(self, text):
        return text.toInt(16)[0]

    def textFromValue(self, value):
        s = QString.number(value, base=16).toUpper()
        if len(s) == 1:
            s = '0' + s
            
        return s
class LM_DoubleSpinBox_with_calc(QDoubleSpinBox):
    '''
    This class is a special spinbox which allows the user to enter a math-expression. As soon as the edit is finished
    the expression will be evaluated and result will be entered in spinBox.
    To evaluate if the entered formula is valid, check "canBeCommitted" (bool). If true, you can read value.
    IMPORTANT: You can not use any "suffix" or "prefix" (which is ignoring the Regex...)
    '''
    def __init__(self, parent=None):
        super(LM_DoubleSpinBox_with_calc, self).__init__(parent)
        #setup a special validator (allowed are leading '=', 0-9 , . ( ) * / + - ... no caracters ... excel-like
        self.validator = QRegExpValidator(
            QRegExp("(^={1}\d*([-+*/(),.]*\d*)*)|([0-9,.])*"))
        self.expression = ""  # this is the variable which holds the expression
        self.setSpecialValueText(
            ""
        )  # this is only an action to avoid error messages if the field is empty
        self.setCorrectionMode(QAbstractSpinBox.CorrectToPreviousValue)
        self.canBeCommitted = True  #this variable holds the status, if the user has entered a valid formula or not

    def valueFromText(self, string):
        '''
        If the user has entered "anything" and hit enter or focus is lost, this function will be called, the
        call is overloaded with the entered string.
        :param string:Value entered in Widget as string
        :return: float (from string)
        '''
        string = string.replace(
            ",", ".")  #tanslate from "german" floating point value
        if string.startsWith("="):
            self.expression = string
            self.setFocusPolicy(Qt.StrongFocus)
            return float(self.value(
            ))  #dont forget about the value if user is entering a formula
        elif string.isEmpty():
            return float(self.value(
            ))  #dont forget about the value if user has cleared the lineEdit
        return float(string)

    def textFromValue(self, p_float):
        '''
        This function is called, when a value (float) should be "displayed", which have to be a string.
        :param p_float: float()
        :return: String from float
        '''
        if self.expression != "":
            expression = self.expression.replace("=", "").replace(
                ",", ".")  #forget about the "="
            try:
                result = float(eval(
                    str(expression)))  #calculate the expression
                self.expression = ""
                self.setValue(result)  #set the "value"
            except SyntaxError:  #this should not happen, because the formula is evaluated fist with "inValidCalculation"
                #print("There was a syntaxError, returning", self.expression)
                result = "=" + self.expression
            return "{0}".format(result).replace(
                ".",
                ",")  #return the display presentation of the value (string)
        return "{0}".format(p_float).replace(
            ".", ",")  #if the exression is empty, only return the string

    def validate(self, string, p_int):
        '''
        Function overrides builtin.
        Is more or less only a "switch" for bool "canBeCommited" which is true, if user has currently entered a valid
        math formula
        :param string: "content of current Spinbox"
        :param p_int: "count which should be validated"
        :return:
        '''
        if string.startsWith("="):
            if self.isValidCalculation(string):
                self.canBeCommitted = True
                return self.validator.validate(string, p_int)
            else:
                self.canBeCommitted = False
                return self.validator.validate(string, p_int)
        else:
            self.canBeCommitted = True
            return self.validator.validate(string, p_int)

    def isValidCalculation(self, string):
        '''
        Ducktyped: if the string is a valid formula which can be evaluated, this function returns True, otherwise
        False
        :param string: QString / String containing a math formula
        :return: True if valid, otherwise false.
        '''
        try:
            float(eval(str(string).replace("=", "").replace(
                ",", ".")))  #calculate the expression
            return True
        except:
            return False
Ejemplo n.º 11
0
 def validate(self, input, pos):
     res = QRegExpValidator.validate(self, input, pos)
     self.isAcceptable = res[0] == QValidator.Acceptable
     return res
Ejemplo n.º 12
0
class BruteForceView(Widget):
    def __init__(self, parent):
        super(BruteForceView, self).__init__("bruteforce", parent)
        self.category = "bf"

        regex = QRegExp("\d{1,6}")
        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditPort.setValidator(self.__validator)

        regex = QRegExp("\d{1,5}")

        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditMaximum.setValidator(self.__validator)

        # Connect buttons
        self.pushButtonCancel.clicked.connect(self.pushButtonCancelClicked)
        self.pushButtonExploit.clicked.connect(self.pushButtonExploitClicked)
        self.toolButtonUsers.clicked.connect(self.toolButtonUsersClicked)
        self.toolButtonPasswords.clicked.connect(
            self.toolButtonPasswordsClicked)

        # Connect signal and thread
        self.__communicate = Communicate()
        self.__exploitThread = ExploitThread(self.__communicate)
        self.__communicate.finishExploit.connect(self.setResultExploit)

        # Button and progressbar
        self.setProgressBarState(0)
        self.pushButtonCancel.setEnabled(False)

        # Generator
        self.__generatorUsers = Generator()
        self.__generatorPasswords = Generator()

    def check(self):
        if Network.ping(self.exploit.ip):
            if not self.isPort() or not str(
                    self.lineEditUsers.text()) or not str(
                        self.lineEditPasswords.text()) or not str(
                            self.lineEditMaximum.text()):
                MessageBox.critical("Error",
                                    "You have to complete the information")
                return False
            else:
                users = str(self.lineEditUsers.text())
                lusers = str(self.lineEditLengthsUsers.text())
                passwords = str(self.lineEditPasswords.text())
                lpasswords = str(self.lineEditLengthsPasswords.text())
                maximum = str(self.lineEditMaximum.text())
                if not self.__generatorUsers.check(
                        users, lusers,
                        maximum) or not self.__generatorPasswords.check(
                            passwords, lpasswords, maximum):
                    MessageBox.critical("Error", "Each range need a length")
                    return False
                else:
                    return True
        else:
            MessageBox.critical("Error", "Destination Host Unreachable")
            return False

    def isPort(self):
        if str(self.lineEditPort.text()):
            state = self.__validator.validate(self.lineEditPort.text(), 0)[0]
            return state == QValidator.Acceptable
        else:
            return False

    def pushButtonCancelClicked(self):
        self.__exploitThread.terminate()
        self.setProgressBarState(3)
        self.pushButtonCancel.setEnabled(False)
        self.pushButtonExploit.setEnabled(True)

    def pushButtonExploitClicked(self):
        if self.check():
            self.plainTextEditData.clear()
            try:
                self.setProgressBarState(2)
                self.pushButtonExploit.setEnabled(False)
                self.pushButtonCancel.setEnabled(True)

                if str(self.lineEditUsers.text()):
                    if exists(str(self.lineEditUsers.text())):
                        users = Parse.getContentFromFile(
                            str(self.lineEditUsers.text()))
                    else:
                        users = self.__generatorUsers.create()
                else:
                    users = None

                if str(self.lineEditPasswords.text()):
                    if exists(str(self.lineEditPasswords.text())):
                        passwords = Parse.getContentFromFile(
                            str(self.lineEditPasswords.text()))
                    else:
                        passwords = self.__generatorPasswords.create()
                else:
                    passwords = None

                if not users or not passwords:
                    MessageBox.critical(
                        "Error",
                        "An error happened while items generation or read the dictionary."
                    )
                    self.pushButtonCancelClicked()

                data = {
                    "port": int(self.lineEditPort.text()),
                    "users": users,
                    "passwords": passwords
                }

                self.__exploitThread.setExploit(self.exploit, data)
                self.__exploitThread.start()
            except Exception as e:
                MessageBox.critical("Error", str(e.args))

    def setExploit(self, exploit):
        self.exploit = exploit
        self.plainTextEditData.appendPlainText("")
        default = self.exploit.default()
        if default:
            try:
                self.lineEditPort.setText(default["port"])
                self.lineEditUsers.setText(default["users"])
                self.lineEditPasswords.setText(default["passwords"])
            except KeyError:
                pass

    def setProgressBarState(self, state):
        if state == 0:
            self.progressBar.hide()
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 1:
            self.progressBar.setFormat("Waiting")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 2:
            self.progressBar.setFormat("Exploiting")
            self.progressBar.setRange(0, 0)
            self.progressBar.show()
        elif state == 3:
            self.progressBar.setFormat("Completed")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(1)
            self.progressBar.show()

    def setResultExploit(self, result):
        if "Success" in result:
            self.exploit.vulnerable = True
            self.vulnerable = True

        self.plainTextEditData.appendPlainText(result)
        self.setProgressBarState(3)
        self.pushButtonExploit.setEnabled(True)

    def toolButtonUsersClicked(self):
        self.lineEditUsers.setText(FileDialog.getOpenFileName("txt"))

    def toolButtonPasswordsClicked(self):
        self.lineEditPasswords.setText(FileDialog.getOpenFileName("txt"))
Ejemplo n.º 13
0
class BruteForceView(Widget):

    def __init__(self, parent):
        super(BruteForceView, self).__init__("bruteforce", parent)
        self.category = "bf"

        regex = QRegExp("\d{1,6}")
        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditPort.setValidator(self.__validator)

        regex = QRegExp("\d{1,5}")

        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditMaximum.setValidator(self.__validator)

        # Connect buttons
        self.pushButtonCancel.clicked.connect(self.pushButtonCancelClicked)
        self.pushButtonExploit.clicked.connect(self.pushButtonExploitClicked)
        self.toolButtonUsers.clicked.connect(self.toolButtonUsersClicked)
        self.toolButtonPasswords.clicked.connect(self.toolButtonPasswordsClicked)

        # Connect signal and thread
        self.__communicate = Communicate()
        self.__exploitThread = ExploitThread(self.__communicate)
        self.__communicate.finishExploit.connect(self.setResultExploit)

        # Button and progressbar
        self.setProgressBarState(0)
        self.pushButtonCancel.setEnabled(False)

        # Generator
        self.__generatorUsers = Generator()
        self.__generatorPasswords = Generator()

    def check(self):
        if Network.ping(self.exploit.ip):
            if not self.isPort() or not str(self.lineEditUsers.text()) or not str(self.lineEditPasswords.text()) or not str(self.lineEditMaximum.text()):
                MessageBox.critical("Error", "You have to complete the information")
                return False
            else:
                users = str(self.lineEditUsers.text())
                lusers = str(self.lineEditLengthsUsers.text())
                passwords = str(self.lineEditPasswords.text())
                lpasswords = str(self.lineEditLengthsPasswords.text())
                maximum = str(self.lineEditMaximum.text())
                if not self.__generatorUsers.check(users, lusers, maximum) or not self.__generatorPasswords.check(passwords, lpasswords, maximum):
                    MessageBox.critical("Error", "Each range need a length")
                    return False
                else:
                    return True
        else:
            MessageBox.critical("Error", "Destination Host Unreachable")
            return False

    def isPort(self):
        if str(self.lineEditPort.text()):
            state = self.__validator.validate(self.lineEditPort.text(), 0)[0]
            return state == QValidator.Acceptable
        else:
            return False

    def pushButtonCancelClicked(self):
        self.__exploitThread.terminate()
        self.setProgressBarState(3)
        self.pushButtonCancel.setEnabled(False)
        self.pushButtonExploit.setEnabled(True)

    def pushButtonExploitClicked(self):
        if self.check():
            self.plainTextEditData.clear()
            try:
                self.setProgressBarState(2)
                self.pushButtonExploit.setEnabled(False)
                self.pushButtonCancel.setEnabled(True)

                if str(self.lineEditUsers.text()):
                    if exists(str(self.lineEditUsers.text())):
                        users = Parse.getContentFromFile(str(self.lineEditUsers.text()))
                    else:
                        users = self.__generatorUsers.create()
                else:
                    users = None

                if str(self.lineEditPasswords.text()):
                    if exists(str(self.lineEditPasswords.text())):
                        passwords = Parse.getContentFromFile(str(self.lineEditPasswords.text()))
                    else:
                        passwords = self.__generatorPasswords.create()
                else:
                    passwords = None

                if not users or not passwords:
                    MessageBox.critical("Error", "An error happened while items generation or read the dictionary.")
                    self.pushButtonCancelClicked()

                data = {"port": int(self.lineEditPort.text()), "users": users, "passwords": passwords}

                self.__exploitThread.setExploit(self.exploit, data)
                self.__exploitThread.start()
            except Exception as e:
                MessageBox.critical("Error", str(e.args))

    def setExploit(self, exploit):
        self.exploit = exploit
        self.plainTextEditData.appendPlainText("")
        default = self.exploit.default()
        if default:
            try:
                self.lineEditPort.setText(default["port"])
                self.lineEditUsers.setText(default["users"])
                self.lineEditPasswords.setText(default["passwords"])
            except KeyError:
                pass

    def setProgressBarState(self, state):
        if state == 0:
            self.progressBar.hide()
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 1:
            self.progressBar.setFormat("Waiting")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 2:
            self.progressBar.setFormat("Exploiting")
            self.progressBar.setRange(0, 0)
            self.progressBar.show()
        elif state == 3:
            self.progressBar.setFormat("Completed")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(1)
            self.progressBar.show()

    def setResultExploit(self, result):
        if "Success" in result:
            self.exploit.vulnerable = True
            self.vulnerable = True

        self.plainTextEditData.appendPlainText(result)
        self.setProgressBarState(3)
        self.pushButtonExploit.setEnabled(True)

    def toolButtonUsersClicked(self):
        self.lineEditUsers.setText(FileDialog.getOpenFileName("txt"))

    def toolButtonPasswordsClicked(self):
        self.lineEditPasswords.setText(FileDialog.getOpenFileName("txt"))