Beispiel #1
0
    def __init__(self):

        python2_exe = settings.read('python2_exe', '')
        if not python2_exe:
            self.__python2_exe = self.__get_python2_interpreter()
            settings.write("python2_exe", self.__python2_exe)
        else:
            self.__python2_exe = python2_exe

        settings.write("python2_exe", self.__python2_exe)

        self.gnuradio_install_dir = settings.read('gnuradio_install_dir', "")
        self.use_gnuradio_install_dir = settings.read(
            'use_gnuradio_install_dir', os.name == "nt", bool)

        self.gnuradio_is_installed = settings.read('gnuradio_is_installed', -1,
                                                   int)
        if self.gnuradio_is_installed == -1:
            self.set_gnuradio_installed_status()
        else:
            self.gnuradio_is_installed = bool(self.gnuradio_is_installed)

        if not hasattr(sys, 'frozen'):
            self.path = os.path.dirname(os.path.realpath(__file__))
        else:
            self.path = os.path.dirname(sys.executable)

        self.device_backends = {}
        """:type: dict[str, BackendContainer] """

        self.get_backends()
Beispiel #2
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_DialogFilterBandwidth()
        self.ui.setupUi(self)
        self.setWindowFlags(Qt.Window)

        bw_type = settings.read("bandpass_filter_bw_type", "Medium", str)
        custom_bw = settings.read("bandpass_filter_custom_bw", 0.1, float)

        for item in dir(self.ui):
            item = getattr(self.ui, item)
            if isinstance(item, QLabel):
                name = item.objectName().replace("label", "")
                key = next((key for key in Filter.BANDWIDTHS.keys()
                            if name.startswith(key.replace(" ", ""))), None)
                if key is not None and name.endswith("Bandwidth"):
                    item.setText("{0:n}".format(Filter.BANDWIDTHS[key]))
                elif key is not None and name.endswith("KernelLength"):
                    item.setText(
                        str(
                            Filter.get_filter_length_from_bandwidth(
                                Filter.BANDWIDTHS[key])))
            elif isinstance(item, QRadioButton):
                item.setChecked(
                    bw_type.replace(" ", "_") == item.objectName().replace(
                        "radioButton", ""))

        self.ui.doubleSpinBoxCustomBandwidth.setValue(custom_bw)
        self.ui.spinBoxCustomKernelLength.setValue(
            Filter.get_filter_length_from_bandwidth(custom_bw))

        self.create_connects()
    def __init__(self,
                 freq,
                 sample_rate,
                 bandwidth,
                 gain,
                 if_gain,
                 baseband_gain,
                 receiving: bool,
                 ip='127.0.0.1',
                 parent=None):
        super().__init__(parent)
        self.ip = ip
        self.gr_port = 1337
        self._sample_rate = sample_rate
        self._freq = freq
        self._gain = gain
        self._if_gain = if_gain
        self._baseband_gain = baseband_gain
        self._bandwidth = bandwidth
        self._freq_correction = 1
        self._direct_sampling_mode = 0
        self._antenna_index = 0
        self._channel_index = 0
        self._receiving = receiving  # False for Sender-Thread
        self.device = "USRP"
        self.current_index = 0

        self.is_in_spectrum_mode = False

        self.context = None
        self.socket = None

        gnuradio_path_file = os.path.join(tempfile.gettempdir(),
                                          "gnuradio_path.txt")
        if settings.read("use_gnuradio_install_dir", False, bool):
            gnuradio_dir = settings.read("gnuradio_install_dir", "")
            with open(gnuradio_path_file, "w") as f:
                f.write(gnuradio_dir)
            if os.path.isfile(
                    os.path.join(gnuradio_dir, "gr-python27", "pythonw.exe")):
                self.python2_interpreter = os.path.join(
                    gnuradio_dir, "gr-python27", "pythonw.exe")
            else:
                self.python2_interpreter = os.path.join(
                    gnuradio_dir, "gr-python27", "python.exe")
        else:
            try:
                os.remove(gnuradio_path_file)
            except OSError:
                pass
            self.python2_interpreter = settings.read("python2_exe", "")

        self.queue = Queue()
        self.data = None  # Placeholder for SenderThread
        self.current_iteration = 0  # Counts number of Sendings in SenderThread

        self.tb_process = None
Beispiel #4
0
    def read_options(self):
        self.ui.comboBoxDefaultView.setCurrentIndex(settings.read('default_view', 0, type=int))
        self.ui.spinBoxNumSendingRepeats.setValue(settings.read('num_sending_repeats', 0, type=int))
        self.ui.checkBoxPauseTime.setChecked(settings.read('show_pause_as_time', False, type=bool))

        self.old_show_pause_as_time = bool(self.ui.checkBoxPauseTime.isChecked())

        self.field_type_table_model.field_types = FieldType.load_from_xml()
        self.field_type_table_model.update()
Beispiel #5
0
    def read_configured_filter_bw() -> float:
        bw_type = settings.read("bandpass_filter_bw_type", "Medium", str)

        if bw_type in Filter.BANDWIDTHS:
            return Filter.BANDWIDTHS[bw_type]

        if bw_type.lower() == "custom":
            return settings.read("bandpass_filter_custom_bw", 0.1, float)

        return 0.08
Beispiel #6
0
    def __send_messages(self, messages, sample_rates):
        if len(messages):
            self.is_sending = True
        else:
            return False

        # Open and configure RfCat
        if not self.open_rfcat():
            return False
        modulation = self.modulators[
            messages[0].modulator_index].modulation_type
        if modulation == "ASK":
            modulation = "MOD_ASK_OOK"
        elif modulation == "FSK":
            modulation = "MOD_2FSK"
        elif modulation == "GFSK":
            modulation = "MOD_GFSK"
        elif modulation == "PSK":
            modulation = "MOD_MSK"
        else:  # Fallback
            modulation = "MOD_ASK_OOK"
        self.configure_rfcat(
            modulation=modulation,
            freq=self.project_manager.device_conf["frequency"],
            sample_rate=sample_rates[0],
            samples_per_symbol=messages[0].samples_per_symbol)

        repeats_from_settings = settings.read('num_sending_repeats', type=int)
        repeats = repeats_from_settings if repeats_from_settings > 0 else -1
        while (repeats > 0 or repeats
               == -1) and self.__sending_interrupt_requested == False:
            logger.debug("Start iteration ({} left)".format(
                repeats if repeats > 0 else "infinite"))
            for i, msg in enumerate(messages):
                if self.__sending_interrupt_requested:
                    break
                assert isinstance(msg, Message)
                wait_time = msg.pause / sample_rates[i]

                self.current_send_message_changed.emit(i)
                error = self.send_data(
                    self.bit_str_to_bytearray(msg.encoded_bits_str))
                if not error:
                    logger.debug("Sent message {0}/{1}".format(
                        i + 1, len(messages)))
                    logger.debug(
                        "Waiting message pause: {0:.2f}s".format(wait_time))
                    if self.__sending_interrupt_requested:
                        break
                    time.sleep(wait_time)
                else:
                    self.is_sending = False
                    Errors.generic_error("Could not connect to {0}:{1}".format(
                        self.client_ip, self.client_port),
                                         msg=error)
                    break
            if repeats > 0:
                repeats -= 1
        logger.debug("Sending finished")
        self.is_sending = False
Beispiel #7
0
    def create_context_menu(self) -> QMenu:
        menu = super().create_context_menu()

        if self.selection_is_empty:
            return menu

        menu.addSeparator()
        self._add_insert_column_menu(menu)
        menu.addSeparator()

        selected_encoding = self.selected_message.decoder

        if not all(
                self.model().protocol.messages[i].decoder is selected_encoding
                for i in self.selected_rows):
            selected_encoding = None

        encoding_group = QActionGroup(self)
        encoding_menu = menu.addMenu("Enforce encoding")

        for decoding in self.model().project_manager.decodings:
            ea = encoding_menu.addAction(decoding.name)
            ea.setCheckable(True)
            ea.setActionGroup(encoding_group)

            if selected_encoding == decoding:
                ea.setChecked(True)

            ea.setData(decoding)
            ea.triggered.connect(self.on_encoding_action_triggered)

        if settings.read("multiple_modulations", False, bool):
            selected_modulation = self.model().protocol.messages[
                self.selected_rows[0]].modulator_index

            if not all(self.model().protocol.messages[i].modulator_index ==
                       selected_modulation for i in self.selected_rows):
                selected_modulation = -1

            modulation_group = QActionGroup(self)
            modulation_menu = menu.addMenu("Modulation")

            for i, modulator in enumerate(
                    self.model().project_manager.modulators):
                ma = modulation_menu.addAction(modulator.name)
                ma.setCheckable(True)
                ma.setActionGroup(modulation_group)

                if selected_modulation == i:
                    ma.setChecked(True)

                ma.setData(i)
                ma.triggered.connect(self.on_modulation_action_triggered)

            open_modulator_dialog_action = modulation_menu.addAction(
                self.tr("..."))
            open_modulator_dialog_action.triggered.connect(
                self.on_open_modulator_dialog_action_triggered)

        return menu
Beispiel #8
0
    def __init__(self, message_type: MessageType, parent=None):
        super().__init__(parent)
        self.ui = Ui_DialogMessageType()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        operator_descriptions = list(OPERATION_DESCRIPTION.values())
        operator_descriptions.sort()

        self.setWindowTitle(self.tr("Rules for {}".format(message_type.name)))
        self.message_type = message_type
        self.original_ruleset = copy.deepcopy(message_type.ruleset)
        self.original_assigned_status = message_type.assigned_by_ruleset
        self.ruleset_table_model = RulesetTableModel(message_type.ruleset, operator_descriptions, parent=self)
        self.ui.tblViewRuleset.setModel(self.ruleset_table_model)

        self.ui.btnRemoveRule.setEnabled(len(message_type.ruleset) > 0)
        self.set_ruleset_ui_status()

        self.ui.rbAssignAutomatically.setChecked(self.message_type.assigned_by_ruleset)
        self.ui.rbAssignManually.setChecked(self.message_type.assign_manually)

        self.ui.tblViewRuleset.setItemDelegateForColumn(2, ComboBoxDelegate(["Bit", "Hex", "ASCII"], parent=self))
        self.ui.tblViewRuleset.setItemDelegateForColumn(3, ComboBoxDelegate(operator_descriptions, parent=self))

        for i in range(len(message_type.ruleset)):
            self.open_editors(i)

        self.ui.cbRulesetMode.setCurrentIndex(self.message_type.ruleset.mode.value)

        self.create_connects()
        self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
Beispiel #9
0
    def save_all(self):
        if self.num_frames == 0:
            return

        try:
            not_show = settings.read('not_show_save_dialog', False, type=bool)
        except TypeError:
            not_show = False

        if not not_show:
            cb = QCheckBox("Don't ask me again.")
            msg_box = QMessageBox(
                QMessageBox.Question, self.tr("Confirm saving all signals"),
                self.tr("All changed signal files will be overwritten. OK?"))
            msg_box.addButton(QMessageBox.Yes)
            msg_box.addButton(QMessageBox.No)
            msg_box.setCheckBox(cb)

            reply = msg_box.exec()
            not_show_again = cb.isChecked()
            settings.write("not_show_save_dialog", not_show_again)
            self.not_show_again_changed.emit()

            if reply != QMessageBox.Yes:
                return

        for f in self.signal_frames:
            if f.signal is None or f.signal.filename == "":
                continue
            f.signal.save()
Beispiel #10
0
    def __init__(self, signal, parent=None):
        super().__init__(parent)
        self.signal = signal
        self.ui = Ui_SignalDetails()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        file = self.signal.filename

        self.ui.lblName.setText(self.signal.name)

        if os.path.isfile(file):
            self.ui.lblFile.setText(file)
            self.ui.lblFileSize.setText(
                locale.format_string("%.2fMB",
                                     os.path.getsize(file) / (1024**2)))
            self.ui.lFileCreated.setText(time.ctime(os.path.getctime(file)))
        else:
            self.ui.lblFile.setText(self.tr("signal file not found"))
            self.ui.lblFileSize.setText("-")
            self.ui.lFileCreated.setText("-")

        self.ui.lblSamplesTotal.setText("{0:n}".format(
            self.signal.num_samples).replace(",", " "))
        self.ui.dsb_sample_rate.setValue(self.signal.sample_rate)
        self.set_duration()

        self.ui.dsb_sample_rate.valueChanged.connect(
            self.on_dsb_sample_rate_value_changed)
        self.restoreGeometry(
            settings.read("{}/geometry".format(self.__class__.__name__),
                          type=bytes))
Beispiel #11
0
    def add_signal_frame(self, proto_analyzer, index=-1):
        self.__set_getting_started_status(False)
        sig_frame = SignalFrame(proto_analyzer,
                                self.undo_stack,
                                self.project_manager,
                                parent=self)
        sframes = self.signal_frames

        if len(proto_analyzer.signal.filename) == 0:
            # new signal from "create signal from selection"
            sig_frame.ui.btnSaveSignal.show()

        self.__create_connects_for_signal_frame(signal_frame=sig_frame)
        sig_frame.signal_created.connect(self.emit_signal_created)
        sig_frame.not_show_again_changed.connect(
            self.not_show_again_changed.emit)
        sig_frame.ui.lineEditSignalName.setToolTip(
            self.tr("Sourcefile: ") + proto_analyzer.signal.filename)
        sig_frame.apply_to_all_clicked.connect(self.on_apply_to_all_clicked)

        prev_signal_frame = sframes[-1] if len(sframes) > 0 else None
        if prev_signal_frame is not None and hasattr(prev_signal_frame, "ui"):
            sig_frame.ui.cbProtoView.setCurrentIndex(
                prev_signal_frame.ui.cbProtoView.currentIndex())

        sig_frame.blockSignals(True)

        index = self.num_frames if index == -1 else index
        self.ui.splitter.insertWidget(index, sig_frame)
        sig_frame.blockSignals(False)

        default_view = settings.read('default_view', 0, int)
        sig_frame.ui.cbProtoView.setCurrentIndex(default_view)

        return sig_frame
Beispiel #12
0
    def plain_to_html(self, view, show_pauses=True) -> str:
        time = settings.read('show_pause_as_time', type=bool)
        if show_pauses and time and self.signal:
            srate = self.signal.sample_rate
        else:
            srate = None

        result = []
        for message in self.messages:
            cur_str = ""
            if message.participant:
                color = settings.PARTICIPANT_COLORS[
                    message.participant.color_index]
                red, green, blue = color.red(), color.green(), color.blue()
                fgcolor = "#000000" if (red * 0.299 + green * 0.587 +
                                        blue * 0.114) > 186 else "#ffffff"
                cur_str += '<span style="background-color: rgb({0},{1},{2}); color: {3}">'.format(
                    red, green, blue, fgcolor)

                # cur_str += '<span style="color: rgb({0},{1},{2})">'.format(red, green, blue)

            cur_str += message.view_to_string(view=view,
                                              decoded=False,
                                              show_pauses=False,
                                              sample_rate=srate)

            if message.participant:
                cur_str += '</span>'

            cur_str += message.get_pause_str(sample_rate=srate)
            result.append(cur_str)

        return "<br>".join(result)
Beispiel #13
0
    def load_installed_plugins(self):
        """ :rtype: list of Plugin """
        result = []
        plugin_dirs = [
            d for d in os.listdir(self.plugin_path)
            if os.path.isdir(os.path.join(self.plugin_path, d))
        ]
        for d in plugin_dirs:
            if d == "__pycache__":
                continue
            try:
                class_module = self.load_plugin(d)
                plugin = class_module()
                plugin.plugin_path = os.path.join(self.plugin_path,
                                                  plugin.name)
                plugin.load_description()
                if plugin.name in settings.all_keys():
                    plugin.enabled = settings.read(plugin.name,
                                                   False,
                                                   type=bool)
                else:
                    plugin.enabled = False
                result.append(plugin)
            except ImportError as e:
                logger.warning("Could not load plugin {0} ({1})".format(d, e))
                continue

        return result
Beispiel #14
0
    def bootstrap(self, conf_dict: dict, enforce_default=False):
        def set_val(ui_widget, key: str, default):
            try:
                value = conf_dict[key]
            except KeyError:
                value = default if enforce_default else None

            if value is not None:
                ui_widget.setValue(value)

        self.set_bandwidth_status()

        self.ui.cbDevice.setCurrentText(conf_dict.get("name", ""))
        dev_name = self.ui.cbDevice.currentText()
        self.set_device_ui_items_visibility(dev_name, overwrite_settings=True)

        set_val(self.ui.spinBoxFreq, "frequency", config.DEFAULT_FREQUENCY)
        set_val(self.ui.spinBoxSampleRate, "sample_rate",
                config.DEFAULT_SAMPLE_RATE)
        set_val(self.ui.spinBoxBandwidth, "bandwidth",
                config.DEFAULT_BANDWIDTH)
        set_val(self.ui.spinBoxGain, self.rx_tx_prefix + "gain",
                config.DEFAULT_GAIN)
        set_val(self.ui.spinBoxIFGain, self.rx_tx_prefix + "if_gain",
                config.DEFAULT_IF_GAIN)
        set_val(self.ui.spinBoxBasebandGain,
                self.rx_tx_prefix + "baseband_gain", config.DEFAULT_BB_GAIN)
        set_val(self.ui.spinBoxFreqCorrection, "freq_correction",
                config.DEFAULT_FREQ_CORRECTION)
        set_val(self.ui.spinBoxNRepeat, "num_sending_repeats",
                settings.read('num_sending_repeats', 1, type=int))

        self.ui.lineEditSubdevice.setText(conf_dict.get("subdevice", ""))

        if self.rx_tx_prefix + "antenna_index" in conf_dict:
            self.ui.comboBoxAntenna.setCurrentIndex(
                conf_dict[self.rx_tx_prefix + "antenna_index"])

        if self.rx_tx_prefix + "gain" not in conf_dict:
            self.set_default_rf_gain()

        if self.rx_tx_prefix + "if_gain" not in conf_dict:
            self.set_default_if_gain()

        if self.rx_tx_prefix + "baseband_gain" not in conf_dict:
            self.set_default_bb_gain()

        if self.is_rx:
            checked = conf_dict.get("apply_dc_correction", True)
            if isinstance(checked, str):
                checked = True if checked == "True" else False
            self.ui.checkBoxDCCorrection.setChecked(checked)

        checked = conf_dict.get("bias_tee_enabled", False)
        if isinstance(checked, str):
            checked = True if checked == "True" else False
        self.ui.checkBoxBiasTee.setChecked(checked)

        self.emit_editing_finished_signals()
Beispiel #15
0
    def __init__(self, new_project=True, project_manager: ProjectManager = None, parent=None):
        super().__init__(parent)
        if not new_project:
            assert project_manager is not None

        self.ui = Ui_ProjectDialog()
        self.ui.setupUi(self)
        self.setWindowFlags(Qt.Window)

        if new_project:
            self.participant_table_model = ParticipantTableModel([])
        else:
            self.participant_table_model = ParticipantTableModel(project_manager.participants)

            self.ui.spinBoxSampleRate.setValue(project_manager.device_conf["sample_rate"])
            self.ui.spinBoxFreq.setValue(project_manager.device_conf["frequency"])
            self.ui.spinBoxBandwidth.setValue(project_manager.device_conf["bandwidth"])
            self.ui.spinBoxGain.setValue(project_manager.device_conf.get("gain", config.DEFAULT_GAIN))
            self.ui.txtEdDescription.setPlainText(project_manager.description)
            self.ui.lineEdit_Path.setText(project_manager.project_path)
            self.ui.lineEditBroadcastAddress.setText(project_manager.broadcast_address_hex)

            self.ui.btnSelectPath.hide()
            self.ui.lineEdit_Path.setDisabled(True)
            self.setWindowTitle("Edit project settings")
            self.ui.lNewProject.setText("Edit project")

        self.ui.tblParticipants.setModel(self.participant_table_model)
        self.participant_table_model.update()

        self.ui.lineEditBroadcastAddress.setValidator(QRegExpValidator(QRegExp("([a-fA-F ]|[0-9]){,}")))

        self.sample_rate = self.ui.spinBoxSampleRate.value()
        self.freq = self.ui.spinBoxFreq.value()
        self.bandwidth = self.ui.spinBoxBandwidth.value()
        self.gain = self.ui.spinBoxGain.value()
        self.description = self.ui.txtEdDescription.toPlainText()
        self.broadcast_address_hex = self.ui.lineEditBroadcastAddress.text()

        self.path = self.ui.lineEdit_Path.text()
        self.new_project = new_project
        self.committed = False
        self.setModal(True)

        completer = QCompleter()
        completer.setModel(QDirModel(completer))
        self.ui.lineEdit_Path.setCompleter(completer)

        self.create_connects()
        # add two participants
        if self.participant_table_model.rowCount() == 0 and new_project:
            self.ui.btnAddParticipant.click()
            self.ui.btnAddParticipant.click()

        if new_project:
            self.ui.lineEdit_Path.setText(os.path.realpath(os.path.join(os.curdir, "new")))

        self.on_line_edit_path_text_edited()
        self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
def set_icon_theme():
    if sys.platform != "linux" or settings.read("icon_theme_index", 0,
                                                int) == 0:
        # noinspection PyUnresolvedReferences
        import urh.ui.xtra_icons_rc
        QIcon.setThemeName("oxy")
    else:
        QIcon.setThemeName("")
Beispiel #17
0
 def __create_connects_for_signal_frame(self, signal_frame: SignalFrame):
     signal_frame.hold_shift = settings.read('hold_shift_to_drag',
                                             True,
                                             type=bool)
     signal_frame.drag_started.connect(self.frame_dragged)
     signal_frame.frame_dropped.connect(self.frame_dropped)
     signal_frame.files_dropped.connect(self.on_files_dropped)
     signal_frame.closed.connect(self.close_frame)
Beispiel #18
0
    def __init__(self, modulators, tree_model=None, parent=None):
        """
        :type modulators: list of Modulator
        """
        super().__init__(parent)

        self.ui = Ui_DialogModulation()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        self.lock_samples_in_view = False

        if tree_model is not None:
            self.ui.treeViewSignals.setModel(tree_model)
            self.ui.treeViewSignals.expandAll()
            self.ui.gVOriginalSignal.signal_tree_root = tree_model.rootItem

        self.ui.comboBoxCustomModulations.clear()
        for modulator in modulators:
            self.ui.comboBoxCustomModulations.addItem(modulator.name)
        if len(modulators) == 1:
            self.ui.btnRemoveModulation.setDisabled(True)

        self.modulators = modulators

        self.set_ui_for_current_modulator()

        self.ui.cbShowDataBitsOnly.setText(
            self.tr("Show Only Data Sequence\n"))
        self.ui.cbShowDataBitsOnly.setEnabled(False)
        self.protocol = None  # type: ProtocolAnalyzer
        self.search_results = []
        self.ui.cbShowDataBitsOnly.setEnabled(False)
        self.ui.btnSearchNext.setEnabled(False)
        self.ui.btnSearchPrev.setEnabled(False)

        self.ui.chkBoxLockSIV.setDisabled(True)

        self.original_bits = ""

        self.restore_bits_action = self.ui.linEdDataBits.addAction(
            QIcon.fromTheme("edit-undo"), QLineEdit.TrailingPosition)
        self.restore_bits_action.setEnabled(False)

        self.configure_parameters_action = self.ui.lineEditParameters.addAction(
            QIcon.fromTheme("configure"), QLineEdit.TrailingPosition)

        self.create_connects()
        self.restoreGeometry(
            settings.read("{}/geometry".format(self.__class__.__name__),
                          type=bytes))

        self.set_bits_per_symbol_enabled_status()
        self.set_modulation_profile_status()

        # Ensure full srceen shown after resize
        QTimer.singleShot(100, self.show_full_scene)
Beispiel #19
0
    def add_empty_row_behind(self, row_index: int, num_bits: int):
        message = Message(plain_bits=[0]*num_bits,
                          pause=settings.read("default_fuzzing_pause", 10**6, int),
                          message_type=self.protocol.default_message_type)

        tmp_protocol = ProtocolAnalyzer(None)
        tmp_protocol.messages = [message]
        undo_action = InsertBitsAndPauses(self.protocol, row_index+1, tmp_protocol)
        self.undo_stack.push(undo_action)
Beispiel #20
0
    def redo(self):
        if settings.read('use_default_fuzzing_pause', True, bool):
            default_pause = settings.read("default_fuzzing_pause", 10**6, int)
        else:
            default_pause = None

        if self.fuz_mode == "Successive":
            added_indices = self.proto_analyzer_container.fuzz_successive(
                default_pause=default_pause)
        elif self.fuz_mode == "Concurrent":
            added_indices = self.proto_analyzer_container.fuzz_concurrent(
                default_pause=default_pause)
        elif self.fuz_mode == "Exhaustive":
            added_indices = self.proto_analyzer_container.fuzz_exhaustive(
                default_pause=default_pause)
        else:
            added_indices = []

        self.added_message_indices.extend(added_indices)
Beispiel #21
0
    def __init__(self):

        self.__gr_python_interpreter = settings.read('gr_python_interpreter',
                                                     '')
        if not self.__gr_python_interpreter:
            self.__gr_python_interpreter = settings.read("python2_exe",
                                                         '')  # legacy

        self.set_gnuradio_installed_status()

        if not hasattr(sys, 'frozen'):
            self.path = os.path.dirname(os.path.realpath(__file__))
        else:
            self.path = os.path.dirname(sys.executable)

        self.device_backends = {}
        """:type: dict[str, BackendContainer] """

        self.get_backends()
Beispiel #22
0
    def __init__(self,
                 project_manager: ProjectManager,
                 is_tx: bool,
                 continuous_send_mode=False,
                 parent=None,
                 testing_mode=False):
        super().__init__(parent)
        self.is_tx = is_tx
        self.update_interval = 25

        # This flag is needed. Will cause memory leak otherwise.
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.setWindowFlags(Qt.Window)
        self.testing_mode = testing_mode

        self.ui = Ui_SendRecvDialog()
        self.ui.setupUi(self)
        util.set_splitter_stylesheet(self.ui.splitter)

        self.ui.txtEditErrors.setFont(util.get_monospace_font())

        self.graphics_view = None  # type: QGraphicsView

        self.backend_handler = BackendHandler()

        self.ui.btnStop.setEnabled(False)
        self.ui.btnSave.setEnabled(False)

        self.start = 0

        self.device_settings_widget = DeviceSettingsWidget(
            project_manager,
            is_tx,
            backend_handler=self.backend_handler,
            continuous_send_mode=continuous_send_mode)
        self.ui.scrollAreaWidgetContents_2.layout().insertWidget(
            0, self.device_settings_widget)

        if testing_mode:
            self.device_settings_widget.ui.cbDevice.setCurrentText(
                NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        self.timer = QTimer(self)

        try:
            self.restoreGeometry(
                settings.read("{}/geometry".format(self.__class__.__name__)))
        except TypeError:
            pass

        self.ui.splitter.setSizes(
            [int(0.4 * self.width()),
             int(0.6 * self.width())])
Beispiel #23
0
    def __init__(self, name, avail_backends: set, supports_rx: bool,
                 supports_tx: bool):
        self.name = name
        self.avail_backends = avail_backends
        self.selected_backend = Backends[settings.read(
            name + "_selected_backend", "none")]
        if self.selected_backend not in self.avail_backends:
            self.selected_backend = Backends.none

        if self.selected_backend == Backends.none:
            if Backends.native in self.avail_backends:
                self.selected_backend = Backends.native
            elif Backends.grc in self.avail_backends:
                self.selected_backend = Backends.grc

        self.is_enabled = settings.read(name + "_is_enabled", True, bool)
        self.__supports_rx = supports_rx
        self.__supports_tx = supports_tx
        if len(self.avail_backends) == 0:
            self.is_enabled = False
Beispiel #24
0
    def get_dtype():
        if Modulator.FORCE_DTYPE is not None:
            return Modulator.FORCE_DTYPE

        dtype_str = settings.read("modulation_dtype", "float32", str)
        if dtype_str == "int8":
            return np.int8
        elif dtype_str == "int16":
            return np.int16
        else:
            return np.float32
Beispiel #25
0
    def __init__(self, modulators, selected_index=0, signal_tree_model=None, parent=None):
        """

        :type modulators: list of Modulator
        :param parent:
        """
        super().__init__(parent)
        self.ui = Ui_ModulationSettings()
        self.ui.setupUi(self)

        self.ui.labelModulationProfile.setVisible(settings.read("multiple_modulations", False, bool))
        self.ui.comboBoxModulationProfiles.setVisible(settings.read("multiple_modulations", False, bool))

        self.signal_tree_model = signal_tree_model
        self.modulators = modulators  # type: list[Modulator]
        for modulator in self.modulators:
            self.ui.comboBoxModulationProfiles.addItem(modulator.name)

        self.ui.comboBoxModulationProfiles.setCurrentIndex(selected_index)

        self.show_selected_modulation_infos()
        self.create_connects()
Beispiel #26
0
    def plain_to_string(self, view: int, show_pauses=True) -> str:
        """

        :param view: 0 - Bits ## 1 - Hex ## 2 - ASCII
        """
        time = settings.read('show_pause_as_time', type=bool)
        if show_pauses and time and self.signal:
            srate = self.signal.sample_rate
        else:
            srate = None

        return '\n'.join(
            msg.view_to_string(view, False, show_pauses, sample_rate=srate)
            for msg in self.messages)
Beispiel #27
0
    def __init__(self, device_name: str, project_manager: ProjectManager, signal=None, backend_handler=None,
                 network_raw_mode=False, signals=None, parent=None):
        super().__init__(parent)
        self.ui = Ui_SniffSettings()
        self.ui.setupUi(self)

        signals = signals if signals is not None else []
        self.project_manager = project_manager

        for encoding in self.project_manager.decodings:
            self.ui.comboBox_sniff_encoding.addItem(encoding.name)

        self.bootstrap(project_manager.device_conf, signal, enforce_default=True)

        self.sniffer = ProtocolSniffer(samples_per_symbol=self.ui.spinbox_sniff_SamplesPerSymbol.value(),
                                       center=self.ui.spinbox_sniff_Center.value(),
                                       center_spacing=self.ui.spinBoxCenterSpacing.value(),
                                       noise=self.ui.spinbox_sniff_Noise.value(),
                                       tolerance=self.ui.spinbox_sniff_ErrorTolerance.value(),
                                       modulation_type=self.ui.combox_sniff_Modulation.currentText(),
                                       bits_per_symbol=self.ui.spinBoxBitsPerSymbol.value(),
                                       device=device_name,
                                       backend_handler=BackendHandler() if backend_handler is None else backend_handler,
                                       network_raw_mode=network_raw_mode)

        self.sniffer.adaptive_noise = self.ui.checkBoxAdaptiveNoise.isChecked()
        self.sniffer.automatic_center = self.ui.checkBoxAutoCenter.isChecked()

        self.__set_center_offset_visibility()

        self.create_connects()
        self.ui.comboBox_sniff_encoding.currentIndexChanged.emit(self.ui.comboBox_sniff_encoding.currentIndex())
        self.ui.comboBox_sniff_viewtype.setCurrentIndex(settings.read('default_view', 0, int))

        # Auto Complete like a Boss
        completer = QCompleter()
        completer.setModel(QDirModel(completer))
        self.ui.lineEdit_sniff_OutputFile.setCompleter(completer)

        self.signals = signals

        if len(signals) == 0:
            self.ui.label_sniff_Signal.hide()
            self.ui.btn_sniff_use_signal.hide()
            self.ui.comboBox_sniff_signal.hide()
        else:
            for signal in signals:
                self.ui.comboBox_sniff_signal.addItem(signal.name)
    def adjust_for_current_file(self, file_path):
        if file_path is None:
            return

        if file_path in FileOperator.archives.keys():
            file_path = copy.copy(FileOperator.archives[file_path])

        recent_file_paths = settings.read("recentFiles", [], list)
        recent_file_paths = [] if recent_file_paths is None else recent_file_paths  # check None for OSX
        recent_file_paths = [p for p in recent_file_paths if p != file_path and p is not None and os.path.exists(p)]
        recent_file_paths.insert(0, file_path)
        recent_file_paths = recent_file_paths[:settings.MAX_RECENT_FILE_NR]

        self.init_recent_file_action_list(recent_file_paths)

        settings.write("recentFiles", recent_file_paths)
Beispiel #29
0
    def __init__(self,
                 protocol: ProtocolAnalyzerContainer,
                 label_index: int,
                 msg_index: int,
                 proto_view: int,
                 parent=None):
        super().__init__(parent)
        self.ui = Ui_FuzzingDialog()
        self.ui.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        self.protocol = protocol
        msg_index = msg_index if msg_index != -1 else 0
        self.ui.spinBoxFuzzMessage.setValue(msg_index + 1)
        self.ui.spinBoxFuzzMessage.setMinimum(1)
        self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages)

        self.ui.comboBoxFuzzingLabel.addItems(
            [l.name for l in self.message.message_type])
        self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index)

        self.proto_view = proto_view
        self.fuzz_table_model = FuzzingTableModel(self.current_label,
                                                  proto_view)
        self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked(
        )
        self.ui.tblFuzzingValues.setModel(self.fuzz_table_model)
        self.fuzz_table_model.update()

        self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
        self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
        self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data))
        self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data))

        self.update_message_data_string()
        self.ui.tblFuzzingValues.resize_me()

        self.create_connects()

        try:
            self.restoreGeometry(
                settings.read("{}/geometry".format(self.__class__.__name__)))
        except TypeError:
            pass
Beispiel #30
0
    def __init__(self, plugins, highlighted_plugins=None, parent=None):
        """
        :type plugins: list of Plugin
        :type highlighted_plugins: list of Plugin
        """
        super().__init__(parent)
        self.ui = Ui_FramePlugins()
        self.ui.setupUi(self)
        self.model = PluginListModel(plugins,
                                     highlighted_plugins=highlighted_plugins)
        self.ui.listViewPlugins.setModel(self.model)
        self.settings_layout = QVBoxLayout()
        self.ui.groupBoxSettings.setLayout(self.settings_layout)
        self.create_connects()

        self.restoreGeometry(
            settings.read("{}/geometry".format(self.__class__.__name__),
                          type=bytes))