Exemplo n.º 1
0
    def exec(self):
        if not self.ready():
            return ERROR

        self.__scan = Scan()

        process = subprocess.run(
            self._commandParams(),
            # ["cat", "scan.out"],
            # ["echo"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)

        if process.returncode != SUCCESS:
            self._addError(process.stderr)

        excode = process.returncode

        self.__parseOutput(process.stdout)

        if len(self.__scan.rules()) > 0:
            self._smanager.saveScan(self.__scan)
        else:
            self.__scan = None
            self._addError(
                'No rules tested, discarding scan. Check xccdf file validity')
            excode = ERROR

        return excode
Exemplo n.º 2
0
def main(endings, size_limit, search_path):
    # initiate global function variables
    movie_list = []
    longest_title = 0

    # initiate options & arguments from cli
    movie_endings = tuple(endings.split(", "))
    movie_size_limit = int(size_limit) * 1024 * 1024  # MegaBytes

    # initiate needed objects
    scanner = Scan(movie_endings, movie_size_limit)
    helper = Helper()

    # look for all available files inside directory recursively
    for root, subs, files in os.walk(search_path):
        # do available files match a movie-file?
        for file in files:
            # is movie file?
            bool_movie = scanner.is_movie(file)

            if not bool_movie:
                continue

            # is large enough?
            movie_path = os.path.join(root, file)
            movie_folder = os.path.basename(root)
            bool_large = scanner.is_large(movie_path)
            if not bool_large:
                continue

            # is movie file and large enough, try to extract a valid movie name
            extracted_data = scanner.extract_file_data(file, movie_folder)

            # if movie has valid data, create a new movie object
            if -1 in extracted_data:
                print("Problem with: " + extracted_data[0] + " " + str(extracted_data[1]))
            else:
                # data valid, create object and append it
                movie_object = Movie(extracted_data[0], extracted_data[1], movie_path, root)
                movie_list.append(movie_object)

                # does the current movie have the longest title?
                if longest_title < len(movie_object.title):
                    longest_title = len(movie_object.title)

    result_str = "Movies counted: {number}".format(number=len(movie_list))
    print(result_str)

    # try to fetch imdb rating for each movie-object
    for movie in movie_list:
        movie.fetch_rating()
        # is current movie in top 250
        movie.imdb_top = helper.is_imdb_top(movie)

    # sort movies by their rating and print them
    print("")
    movie_list.sort(key=lambda x: x.rating, reverse=True)
    for movie in movie_list:
        movie.print_data(longest_title)
Exemplo n.º 3
0
 def __init__(self):
     self.piconn = pigpio.pi()
     if not self.piconn.connected:
         print('failed to connect to pigpio deamon - start it')
         exit()
     self.proximity = Proximity(self.piconn)
     self.driver = Driver(self.piconn, self.proximity)
     self.scanner = Scan(self.piconn)
Exemplo n.º 4
0
    def do_scan_seq(self, filename):
        # note:
        # this call is automated, sz makes a series of images in a specific order
        # todo: autofocus first

        # execute scan sequence
        scan = Scan()
        return scan.scan_seq(filename)
Exemplo n.º 5
0
 def __init__(self):
     """
         Constructor, no params
     """
     self.scanner = Scan()
     self.man = Manuel()
     self.prompt = "nmapshell > "
     self.hist = []
     self.start()
Exemplo n.º 6
0
    def get_device_name(self):
        scanner = Scan(None)
        targets = scanner.scan()
        self.listbox2.delete(0, END)

        if targets:
            for target in targets:
                index = targets.index(target)
                addr  = targets[index][:17]
                self.listbox2.insert("end", addr)
Exemplo n.º 7
0
    def get_device_name(self):
        scanner = Scan(None)
        targets = scanner.scan()
        self.listbox2.delete(0, END)

        if targets:
            for target in targets:
                index = targets.index(target)
                addr  = targets[index][:17]
                self.listbox2.insert("end", addr)
Exemplo n.º 8
0
    def __init__(self, target_mac, firmware_path, datfile_path):
        self.target_mac = target_mac

        self.firmware_path = firmware_path
        self.datfile_path = datfile_path
        self.scan_obj = Scan(None)
        scan_list = self.scan_obj.scan()
        self.ble_conn = pexpect.spawn(
            "gatttool -b '%s' -t random --interactive" % target_mac)
        self.ble_conn.delaybeforesend = 0
Exemplo n.º 9
0
class ScanTest(unittest.TestCase):
    def setUp(self):
        self.scan = Scan(3176, 'be', 'normal', '123')

    def test_getLock(self):
        lock = self.scan.getLock()
        self.assertEqual(str(lock.getDoor()), '3176')

    def test_getScanTime(self):
        time = self.scan.getScanTime()
        self.assertEqual(self.scan.getScanTime(), time)

    def test_getCard(self):
        self.assertEqual(str(self.scan.getCard()), '123')
Exemplo n.º 10
0
    def __saveScan(self, scan):
        scan_slug = datetime.now().strftime('%d.%m.%Y-%H:%M:%S')
        self.__cursor.execute(self.__mysql_templates['insert_scan'],
                              (scan_slug, ))
        self.__commitToDB()

        stored_scan = Scan({
            'id': self.__cursor.lastrowid,
            'slug': scan_slug,
        })

        for rule in scan.rules():
            stored_scan.addTestedRule(rule)

        return stored_scan
Exemplo n.º 11
0
    def get_content(self, data_path):
        '''
        Sends the content listing for a given path. This detects if the path is
        scan, section or fov.
        '''

        views = []

        path_type = self.check_path_type(data_path)

        # detect if this is a scan, section or fov
        if path_type == 'FOV':

            views.append({'data_path': data_path})

        elif path_type == 'SECTION':

            views.append({'data_path': data_path})

        elif path_type == 'SCAN':

            scan = Scan.from_directory(data_path, False)  # lazy indexing

            for i, section in enumerate(scan._sections):

                views.append(
                    {'data_path': os.path.join(data_path, section.id)})

        return views
Exemplo n.º 12
0
def get_slice_volume(uid, slice_number):
    #TODO create a local cache
    logging.info("Started at: {}".format(
        datetime.now().strftime("%m/%d/%Y, %H:%M:%S")))
    try:
        scan = Scan.fromID(
            uid,
            app.config['CT_SCANS_DIR'],
            prefer_compressed_volume=False,
            compressed_volumes_dir=app.config['COMPRESSED_VOLUMES_DIR'])
        logging.info("Got scan: {}".format(
            datetime.now().strftime("%m/%d/%Y, %H:%M:%S")))

        volume = scan.volume
        slice_volume = volume[slice_number - 1]
        slice_volume = slice_volume.tobytes()
        logging.info("Got volume: {}".format(
            datetime.now().strftime("%m/%d/%Y, %H:%M:%S")))

        headers = Headers()
        headers['Content-Length'] = len(slice_volume)
        rv = app.response_class(slice_volume,
                                mimetype='application/octet-stream',
                                headers=headers)
        logging.info("Return at: {}".format(
            datetime.now().strftime("%m/%d/%Y, %H:%M:%S")))
        return rv
    except IOError:
        app.logger.warning('Cannot find scan with id %s', uid)
        abort(404)
    pass
Exemplo n.º 13
0
def get_study_metadata(work_item_id):
    try:
        # work_item = get_work_item(uid)
        work_item = get_work_item(work_item_id)
        study_metadata = {
            'uid': work_item.uid,
            'accessionNumber': work_item.accession_number,
            'patientName': work_item.patient_name,
            'patientLocation': work_item.get_patient_location(),
            'series': {}
        }

        for series in work_item.series:
            scan = Scan.fromID(series.uid,
                               app.config['CT_SCANS_DIR'],
                               read_volume=False)
            if work_item.body_part is not None:
                scan.body_part = work_item.body_part
            study_metadata['series'][series.id] = scan_metadata_to_json(scan)

            # check if the study has a report
        report_loader = reports.ReportsLoader(app.config['REPORTS_DIR'])
        report = report_loader.load_report(work_item.accession_number)

        study_metadata['report'] = report

        return jsonify(study_metadata)
    except IOError:
        app.logger.warning('Cannot find scan with work_item_id %s',
                           work_item_id)
        abort(404)
Exemplo n.º 14
0
def search_user_slice():
    if not current_user.is_admin:
        abort(403)

    sub_slice_num = request.args.get('search', '')
    series_id = int(request.args.get('series_id') or -1)

    if series_id == -1:
        return jsonify([])

    try:

        series_uids_query = models.Series.query.filter(models.Series.id.is_(series_id))
        series = series_uids_query.one()

        scan = Scan.fromID(series.uid, app.config['CT_SCANS_DIR'], read_volume=False)

        number_of_slices = scan.size[0]

        slices = [{'text': str(i), 'id': i} for i in range(1, number_of_slices + 1) if sub_slice_num in str(i)]

        return jsonify(slices)
    except NoResultFound:
        app.logger.warning('slice not found for series uid: %s', series_id)
        return jsonify([])
Exemplo n.º 15
0
def get_study_metadata(uid):
    try:
        work_item = get_work_item(uid)
        study_metadata = {
            'uid': uid,
            'accessionNumber': work_item.accession_number,
            'patientName': work_item.patient_name,
            'patientLocation': work_item.get_patient_location(),
            'series': {}
        }

        for series in work_item.series:
            # TODO: IB - the study metadata should be taken from the work-item\series models, and not loaded
            # TODO: from the file every time
            scan = Scan.fromID(series.uid,
                               app.config['CT_SCANS_DIR'],
                               read_volume=False)
            if work_item.body_part is not None:
                scan.body_part = work_item.body_part
            study_metadata['series'][series.id] = scan_metadata_to_json(scan)

        # check if the study has a report
        report_loader = reports.ReportsLoader(app.config['REPORTS_DIR'])
        report = report_loader.load_report(work_item.accession_number)

        study_metadata['report'] = report

        return jsonify(study_metadata)
    except IOError:
        app.logger.warning('Cannot find scan with id %s', uid)
        abort(404)
    except NoResultFound:
        app.logger.warning('Work list with uid %s not found for user: %s', uid,
                           current_user.username)
        abort(404)
Exemplo n.º 16
0
  def get_content(self, data_path):
    '''
    Sends the content listing for a given path. This detects if the path is scan, section or fov.
    '''

    views = []

    path_type = self.check_path_type(data_path)

    # detect if this is a scan, section or fov
    if path_type == 'FOV':

      views.append({'data_path':data_path})


    elif path_type == 'SECTION':

      views.append({'data_path':data_path})


    elif path_type == 'SCAN':

      scan = Scan.from_directory(data_path, False) # lazy indexing

      for i, section in enumerate(scan._sections):

        views.append({'data_path':os.path.join(data_path, section.id)})

    return views
Exemplo n.º 17
0
    def load_ascans(self):
        path, _ = QFileDialog.getOpenFileName(self, 'Open b-scan file', '',
                                              "B Scans (*.bin)")
        if path != "":
            self.status_bar_text.setText("Loading processed data")
            # Loading Scan
            self.scan = Scan(20000)
            self.scan.load_data(path)
            # 5000 processed ascans
            self.figure5.clear()
            ax = self.figure5.add_subplot(111)
            ax.imshow(self.scan.cut_matrix)
            self.canvas5.draw()

            self.status_bar_text.setText("Finished loading processed data")
        else:
            self.status_bar_text.setText("Path was empty!")
Exemplo n.º 18
0
 def append_if_better(self, p_candidate_scan: dict) -> None:
     try:
         if self.is_complete(p_candidate_scan):
             l_scan_profile_id: str = p_candidate_scan["ScanTaskProfileId"]
             if l_scan_profile_id in self.__m_scans:
                 l_new_scan_create_datetime: datetime = parser.parse(
                     p_candidate_scan["InitiatedAt"])
                 l_current_scan_create_datetime: datetime = self.__m_scans[
                     l_scan_profile_id].initiated_at_datetime
                 if l_new_scan_create_datetime > l_current_scan_create_datetime:
                     self.__m_scans[l_scan_profile_id] = Scan(
                         p_candidate_scan)
             else:
                 self.__m_scans[l_scan_profile_id] = Scan(p_candidate_scan)
     except Exception as e:
         self.__mPrinter.print("append_if_better() - {0}".format(str(e)),
                               Level.ERROR)
Exemplo n.º 19
0
 def discard_changes(self):
     """
     Reloads Scan from file without saving changes.
     """
     self.scans[self.scans_index] = Scan.from_files(
         self.current_scan.image_path, self.current_scan.info_path)
     self.redraw_scan()
     self.canvas.get_tk_widget().focus_force()
Exemplo n.º 20
0
 def show_scan(self):
     """
     Shows the scan page
     """
     if not self.scan_widget:
         self.scan_widget = Scan(self)
         self.scan_widget.ids.zbarcam.ids.xcamera._camera.start()
     self.clear_widgets()
     self.add_widget(self.scan_widget)
Exemplo n.º 21
0
def get_scan(uid):
    try:

        scan = Scan.fromID(uid, app.config['CT_SCANS_DIR'], read_volume=False)
        scan_data = scan_metadata_to_json(scan)
        return jsonify(scan_data)
    except IOError:
        app.logger.warning('Cannot find scan with id %s', uid)
        abort(404)
Exemplo n.º 22
0
 def __init__(self, parent=None):
     super(MyWindow, self).__init__(parent)
     self.setupUi(self)
     # 窗体图标
     self.setWindowIcon(QIcon("ip_cheat.ico"))
     self.scan = Scan()
     self.config = Config()
     self.save = Save()
     self.attack = Attack()
     self.cheat = None
     self.scan.host_scan_status.connect(self.add_host_result)
     self.scan.port_scan_status.connect(self.add_port_result)
     for val in self.config.ipv4_adp.keys():
         self.send_card.addItem(val)
     _translate = QtCore.QCoreApplication.translate
     self.need_scan_ip_T.setPlainText(_translate("MainWindow", "192.168.1.142"))
     self.save_file_path_T.setPlainText(_translate("MainWindow", "D:/PycharmProjects/IP欺骗"))
     self.cheat_port_T.setPlainText(_translate("MainWidow", "80"))
     self.send_card.setCurrentText(_translate("MainWidow", "192.168.1.1"))
Exemplo n.º 23
0
        def __init__(self, application=None, *args, **kwargs):
            self.application = application
            wx.Frame.__init__(self, None, *args, **kwargs)
            self.Bind(wx.EVT_CLOSE, lambda x: self.Destroy())
            #self.Show()
            import sys

            def val(key):
                if key in sys.argv:
                    return sys.argv[sys.argv.index('-t') + 1]
                else:
                    return None

            def is_yaml(filename):
                ext = '.yaml'
                return filename[-len(ext):] == ext

            template_file = val('-t')
            content_file = val('-c')
            kb_file = val('-k')
            scan_file = val('-s')
            report_file = val('-r')

            if template_file and report_file:
                report = Report()
                report.template_load_xml(template_file)
                if content_file:
                    if is_yaml(content_file):
                        report.content_load_yaml(content_file)
                    else:
                        report.content_load_json(content_file)
                if kb_file:
                    if is_yaml(kb_file):
                        report.kb_load_yaml(kb_file)
                    else:
                        report.kb_load_json(kb_file)
                if scan_file:
                    report.scan = Scan(scan_file)
                report.xml_apply_meta(
                    vulnparam_highlighting=self.menu_view_v.IsChecked(),
                    truncation=self.menu_view_i.IsChecked())
                report.save_report_xml(report_file)
            else:
                print 'Usage: '
                print
                print '    ' + self.application.title + '.exe'
                print '        start GUI application'
                print
                print '    ' + self.application.title + '.exe -t template-file [-c content-file] [-k kb-file] [-s scan-file] -r report-file'
                print '        generate report'
                print
                print '    ' + self.application.title + '.exe [any other arguments]'
                print '        display usage and exit'

            self.Close()
Exemplo n.º 24
0
 def _open_scan(self, filename):
     self.status('Loading scan...')
     self.menu_file_save_s.Enable(False)
     if self.scan is not None:
         del self.scan
     self.scan = Scan(
         filename, requests_and_responses=self.menu_view_r.IsChecked())
     if self.menu_view_y.IsChecked():
         self.ctrl_tc_s.SetValue(
             self.scan.dump_yaml(truncate=self.menu_view_i.IsChecked()))
     else:
         self.ctrl_tc_s.SetValue(
             self.scan.dump_json(truncate=self.menu_view_i.IsChecked()))
     self.ctrl_st_s.Enable(True)
     self.menu_file_save_s.Enable(True)
     self.menu_file_save_r.Enable(True)
     #if self.ctrl_st_c.IsEnabled():
     if self.ctrl_st_t.IsEnabled():
         self.menu_tools_merge_scan_into_content.Enable(True)
     self.status('Scan loaded')
Exemplo n.º 25
0
    def scan_tcp(self, host, port):
        """scan tcp port"""
        from scan import Scan
        result = dict()
        try:
            scanner = Scan(host = host, port = port)
            if scanner.check_tcp_port():
                result['status'] = True
                result['result'] = True
                result['data'] = (('port_status', True), )
            else:
                result['status'] = True
                result['result'] = False
                result['data'] = (('port_status', False), )
        except Exception as e:
            result['status'] = False
            result['data'] = (('error:', e.message), )
            return result

        return result
Exemplo n.º 26
0
    def get_scan(uid):
        scan = Scan.fromID(uid, read_volume=True)
        print(uid)
        print(scan.metadata)

        volume = scan.volume.tobytes()

        response = make_response(volume)
        response.headers['Content-Length'] = len(volume)
        response.headers['Content-Type'] = 'application/octet-stream'
        return response
Exemplo n.º 27
0
class MainApp:
    def __init__(self):
        self.piconn = pigpio.pi()
        if not self.piconn.connected:
            print('failed to connect to pigpio deamon - start it')
            exit()
        self.proximity = Proximity(self.piconn)
        self.driver = Driver(self.piconn, self.proximity)
        self.scanner = Scan(self.piconn)

    def run(self):
        while True:
            found, mode, width, x = self.scanner.scan()
            if found == True:
                chase = self.rotate_to_center(mode, width, x)
                if chase == True:
                    self.driver.chase(settings.CHASE_DURATION)

        del scanner
        piconn.stop()

    def rotate_to_center(self, mode, width, x):
        idata = settings.imagedata[mode]
        print(idata)
        xsector = int(x / idata['sector_width'])
        durationx = 0
        durationw = 0
        midsector = idata['mid_sector']
        if xsector > midsector:
            durationx = (xsector - midsector) * settings.MOVEMENT_DURATION
        elif xsector < midsector:
            durationx = (midsector - xsector) * settings.MOVEMENT_DURATION * -1
        if width < settings.CENTER_WIDTH:
            durationw = (int((settings.CENTER_WIDTH - width) /
                             50)) * settings.MOVEMENT_DURATION
        elif width > settings.CENTER_WIDTH:
            durationw = (int((width - settings.CENTER_WIDTH) /
                             50)) * settings.MOVEMENT_DURATION * -1

        duration = durationx + durationw
        print(
            'xsector: {} durationx: {}  width: {} durationw: {}  duration: {}'.
            format(xsector, durationx, width, durationw, duration))

        if duration > 0:
            self.driver.rotateright(duration)
        else:
            self.driver.rotateleft(duration * -1)

        # check if the car is already pointing to the target. If yet, then chase.
        if durationx == 0 and durationw == 0:
            return True

        return False
Exemplo n.º 28
0
    def search_containers(self, image, cids, output):
        f = Scan(image, cids, output)
        try:
            if f.get_release():

                t = timeit.Timer(f.scan).timeit(number=1)
                logging.debug("Scanned chroot for image {0}"
                              " completed in {1} seconds"
                              .format(image, t))

                timeit.Timer(f.report_results).timeit(number=1)
            else:
                # This is not a RHEL image or container
                f._report_not_rhel(image)
        except subprocess.CalledProcessError:
            pass

        start = time.time()
        f.DM.cleanup(f.dm_results)
        logging.debug("Removing temporary chroot for image {0} completed in"
                      " {1} seconds".format(image, time.time() - start))
        self.threads_complete += 1
def create_scan(scans):
    print('\n')
    print 'Adding new scan:\n'
    policies = get_policies()
    policy_id = policies['Basic Network Scan']
    scan_name = raw_input("Scan name: ")
    scan_targets = raw_input("Targets: ")
    scan_description = raw_input("Description: ")
    scan_data = add(scan_name, scan_description, scan_targets, policy_id)
    scan_id = scan_data['id']

    scan = Scan(scan_name, scan_description, scan_targets, scan_id)
    scans.append(scan)
Exemplo n.º 30
0
def main():
    """
    Runs the cropping tool on read_from
    :return: None
    """
    from scan import Scan

    scans = []
    images = list(read_from.glob(f"*.png"))
    infos = list(read_from.glob(f"*.txt"))
    output_to.mkdir(exist_ok=True, parents=True)

    print(f"=== Xray-QA Crop Tool ===\n"
          f"{len(images)} images found.\n"
          f"{len(infos)} txt files found.\n"
          f"{read_from} -> {output_to}\n"
          f"Crop joints to {WIDTH} x {HEIGHT}.\n"
          f"Press [ENTER] to continue, Ctrl+C to cancel.\n")

    input()

    # Read Scans from files, only those with a PNG and a txt
    intersection = set([path.stem for path in images]) & set(path.stem
                                                             for path in infos)
    images = [image for image in images if image.stem in intersection]
    infos = [info for info in infos if info.stem in intersection]
    for image, info in zip(images, infos):
        scans.append(Scan.from_files(image, info))
    scans.sort(key=lambda x: x.patient)  # Sort based on patient number

    print(f"{len(intersection)} image, txt pairs will be considered.")

    # Produce the Joint image for each
    for idx, scan in enumerate(scans):
        sys.stdout.write(
            f"\rCropping joints for patient {idx} of {len(scans)}. ({idx / len(scans) * 100: .2f}%)"
        )
        sys.stdout.flush()
        image = np.array(scan.image)
        # Note: Post-Processing could go here
        for joint in scan.joints:
            joint_image = angled_center_crop(image, joint.x, joint.y, WIDTH,
                                             HEIGHT, joint.angle)
            im = Image.fromarray(joint_image)
            im.save(output_to /
                    f"{scan.patient}_{scan.visit}_{joint.label}.png")
    sys.stdout.write(
        f"\rCropped joints for {len(scans)} patients. (100.00%)\n")
    sys.stdout.flush()
Exemplo n.º 31
0
    def open_dir(self):
        """
        Prompts the user for a directory, searches it for data, and preps the GUI to display it.
        Then calls redraw_scan() to start the image display.
        IMPORTANT: Assumes .txt infos are a subset of images. There cannot be a .txt without matching .png or this will
        ignore it.
        :return: None
        """
        self.plot.clear()
        self.scans = []
        self.scans_index = 0
        self.directory = pathlib.Path(filedialog.askdirectory())
        images = list(self.directory.glob(f"*.png"))
        infos = list(self.directory.glob(f"*.txt"))

        if len(images) == 0:
            messagebox.showerror(title="Error Opening Directory",
                                 message=f"{self.directory} has no images.")
            return
        elif len(infos) == 0:
            messagebox.showerror(
                title="Error Opening Directory",
                message=f"{self.directory} has no info files.")
            return

        intersection = set([path.stem
                            for path in images]) & set(path.stem
                                                       for path in infos)
        messagebox.showinfo(
            title="Discovery",
            message=f"{len(intersection)} scan/label pairs will be loaded.\n"
            f"{len(images)} images will be loaded.\n"
            f"{len(infos)} info files were present.")

        sync_infos = []
        for image in images:
            # If the stem (only filename) of the image matches that of the info, append it, otherwise append None.
            # This is likely O(n^2), but is only performed once to load and therefore is tolerable compared to the
            # investment of more complicated logic.
            sync_infos.append(
                next((x for x in infos if x.stem == image.stem), None))

        for image, info in zip(images, sync_infos):
            self.scans.append(Scan.from_files(image, info))

        self.scans.sort(
            key=lambda x: x.patient)  # Sort based on patient number

        self.redraw_scan()
Exemplo n.º 32
0
    def getScanBySlug(self, slug):
        scan = None

        if not self.ready():
            return scan

        self.__cursor.execute(self.__mysql_templates['fetch_scan_by_slug'],
                              (slug, ))

        res = self.__cursor.fetchall()
        if len(res) == 1:
            id, slug = res[0]
            scan = Scan({'id': id, 'slug': slug})
            self.__getScanRules(scan)

        return scan
Exemplo n.º 33
0
    def getAllScans(self):
        scans = []

        if not self.ready():
            return scans

        self.__cursor.execute(self.__mysql_templates['select_all_scans'])

        raw_scans = self.__cursor.fetchall()

        for id, slug in raw_scans:
            scan = Scan({'id': id, 'slug': slug})
            self.__getScanRules(scan)
            scans.append(scan)

        return scans
Exemplo n.º 34
0
def compress_scan_volume(ct_scans_dir,
                         compressed_volumes_dir,
                         uid,
                         overwrite=False):
    try:
        scan = Scan.fromID(uid,
                           scanfolder=ct_scans_dir,
                           compressed_volumes_dir=compressed_volumes_dir)
        if overwrite or (not scan.volume_compressed):
            logger.info('Compressing scan volume for uid %s', uid)
            scan.store_compressed_volume()
            logger.info(
                'Scan volume compression for uid %s completed successfully',
                uid)
    except Exception as e:
        logger.exception('Cannot compress scan volume for uid %s', uid)
Exemplo n.º 35
0
 def _open_scan(self, filename):
     self.status("Loading scan...")
     self.menu_file_save_s.Enable(False)
     if self.scan is not None:
         del self.scan
     self.scan = Scan(filename, requests_and_responses=self.menu_view_r.IsChecked())
     if self.menu_view_y.IsChecked():
         self.ctrl_tc_s.SetValue(self.scan.dump_yaml(truncate=self.menu_view_i.IsChecked()))
     else:
         self.ctrl_tc_s.SetValue(self.scan.dump_json(truncate=self.menu_view_i.IsChecked()))
     self.ctrl_st_s.Enable(True)
     self.menu_file_save_s.Enable(True)
     self.menu_file_save_r.Enable(True)
     # if self.ctrl_st_c.IsEnabled():
     if self.ctrl_st_t.IsEnabled():
         self.menu_tools_merge_scan_into_content.Enable(True)
     self.status("Scan loaded")
Exemplo n.º 36
0
	def __init__(self, output, translate, log, installer,options):
		#- imports necessary
		import sys, os,signal
		sys.path.append('modules/nmap-scan/model')
		from scan import Scan
		scan = Scan()

		def apagado(sig,frame):
			output.default("Kill Scan")
			sys.exit(0)
		signal.signal(signal.SIGINT, apagado)
		#- Operations
		#- Example:
		interpret = translate.init('nmap_scan', 'modules/nmap-scan/locale')
		_ = interpret.ugettext
		output.default('Nmap Scan')
		def __menu__():
			print color('magenta', '1. Select audit')
			print color('magenta', '2. Select revision')
			print color('magenta', '3. Discovery')
			print color('magenta', '4. Discover OS')
			print color('magenta', '5. Versions')
			print color('magenta', '6. Script')
			print color('magenta', '7. Custom Parameters')
			print color('magenta', '8. Ports')
			print color('magenta', '9. Get hosts with indicated open ports')
			print color('magenta', '10. Get all information of a host')
			print color('magenta', "11. Change host's name")
			print color('magenta', '12. What is my base IP')
			print color('rojo', '0. Exit')
		
		__menu__()

		control = True
		while control == True:
			options.set_completer(help.complete)
			sentencia = raw_input("Nmap >> ")
			if sentencia == '1':
				scan.select_audit()
			elif sentencia == '2':
				scan.select_revision()
			elif sentencia == '3':
				scan.discovery()
			elif sentencia == '4':
				scan.discoverOS()
			elif sentencia == '5':
				# scan.version(_, log) #M
				scan.version()
			elif sentencia == '6':
				# scan.script(_, log) #M
				scan.script()
			elif sentencia == '7':
				scan.CustomParameters()
			elif sentencia == '8':
				# scan.puertos(_, log)
				scan.puertos()
			elif sentencia == '9':
				scan.portsFile()
			elif sentencia == '10':
				scan.allInfoHost()
			elif sentencia == '11':
				scan.changeHostName()
			elif sentencia == '12':
				scan.calcIPbase()
			elif sentencia == '0':
				sys.exit()
			elif sentencia == 'exit':
				sys.exit()
			elif sentencia == 'version':
				output.default(help.version())
			elif sentencia == 'help':
				output.default(help.help())
			elif sentencia == 'menu':
				__menu__()
			else:
				output.default('No ha seleccionado una opcion correcta')
Exemplo n.º 37
0
    class __MainWindow(wx.Frame):

        # Variables set during __init__

        # report
        # application
        # scan
        # template
        # icon
        # statusbar
        # save_into_directory
        # menu_file_open_c
        # menu_file_open_k
        # menu_file_generate_c
        # menu_file_generate_k
        # menu_file_generate_r
        # menu_file_save_t
        # menu_file_save_c
        # menu_file_save_s
        # menu_file_save_k
        # menu_file_save_r
        # menu_view_c
        # menu_view_y
        # menu_view_j
        # menu_view_s
        # menu_view_v
        # menu_view_i
        # menu_view_r
        # menu_view_t
        # menu_tools_template_structure_preview
        # menu_tools_merge_scan_into_content
        # menu_tools_generate_few_passwords
        # ctrl_st_t
        # ctrl_tc_t
        # ctrl_st_c
        # ctrl_tc_c
        # ctrl_tc_c_b
        # ctrl_st_s
        # ctrl_tc_s
        # ctrl_tc_s_b
        # ctrl_st_k
        # ctrl_tc_k
        # ctrl_st_r
        # ctrl_tc_r
        # color_tc_bg_e
        # color_tc_bg_d
        # _statusbar_h
        # children

        def __init__(
            self, application=None, parent=None, *args, **kwargs
        ):  # style=wx.DEFAULT_FRAME_STYLE^wx.RESIZE_BORDER

            self.children = []
            # self.report = None
            self.report = Report()
            self.application = application
            self.scan = None
            self.save_into_directory = ""
            wx.Frame.__init__(
                self, parent, title=self.application.title + " " + self.application.version, *args, **kwargs
            )  # style=style
            self.Bind(wx.EVT_CLOSE, lambda x: self.Destroy())

            myStream = cStringIO.StringIO(base64.b64decode(icon))
            myImage = wx.ImageFromStream(myStream)
            myBitmap = wx.BitmapFromImage(myImage)
            self.icon = wx.EmptyIcon()
            self.icon.CopyFromBitmap(myBitmap)
            self.SetIcon(self.icon)

            # Menu arrangement
            menu = wx.MenuBar()

            class Index(object):
                def __init__(self, current):
                    self.__current = current - 1

                @property
                def current(self):
                    return self.__current

                @current.setter
                def current(self, x):
                    self.__current = x

                def next(self):
                    self.__current += 1
                    return self.__current

            index = Index(100)
            menu_file = wx.Menu()
            menu_file.Append(index.next(), "Open Report &Template...")
            self.Bind(wx.EVT_MENU, self.Open_Template, id=index.current)
            self.menu_file_open_c = menu_file.Append(index.next(), "Open &Content...")
            self.menu_file_open_c.Enable(False)
            self.Bind(wx.EVT_MENU, self.Open_Content, id=index.current)
            menu_file.Append(index.next(), "Open &Scan...")
            self.Bind(wx.EVT_MENU, self.Open_Scan, id=index.current)
            self.menu_file_open_k = menu_file.Append(index.next(), "Open &Knowledge Base...")
            self.menu_file_open_k.Enable(False)
            self.Bind(wx.EVT_MENU, self.Open_Knowledge_Base, id=index.current)
            # menu_file.AppendSeparator()
            # self.menu_file_generate_c = menu_file.Append(index.next(), '&Generate Content')
            # self.menu_file_generate_c.Enable(False)
            # self.Bind(wx.EVT_MENU, self.Generate_Content, id=index.current)
            # self.menu_file_generate_k = menu_file.Append(index.next(), 'G&enerate Knowledge Base')
            # self.menu_file_generate_k.Enable(False)
            # self.Bind(wx.EVT_MENU, self.Generate_Knowledge_Base, id=index.current)
            # self.menu_file_generate_r = menu_file.Append(index.next(), 'Ge&nerate Report')
            # self.menu_file_generate_r.Enable(False)
            # self.Bind(wx.EVT_MENU, self.Generate_Report, id=index.current)
            menu_file.AppendSeparator()
            self.menu_file_save_t = menu_file.Append(index.next(), "&Save Template As...")
            self.menu_file_save_t.Enable(False)
            self.Bind(wx.EVT_MENU, self.Save_Template_As, id=index.current)
            self.menu_file_save_c = menu_file.Append(index.next(), "Sav&e Content As...")
            self.menu_file_save_c.Enable(False)
            self.Bind(wx.EVT_MENU, self.Save_Content_As, id=index.current)
            # self.menu_file_save_k = menu_file.Append(index.next(), 'S&ave Knowledge Base As...')
            # self.menu_file_save_k.Enable(False)
            # self.Bind(wx.EVT_MENU, self.Save_Knowledge_Base_As, id=index.current)
            self.menu_file_save_s = menu_file.Append(index.next(), "Sa&ve Scan As...")
            self.menu_file_save_s.Enable(False)
            self.Bind(wx.EVT_MENU, self.Save_Scan_As, id=index.current)
            self.menu_file_save_r = menu_file.Append(index.next(), "Save &Report As...")
            self.menu_file_save_r.Enable(False)
            self.Bind(wx.EVT_MENU, self.Save_Report_As, id=index.current)
            menu_file.AppendSeparator()
            menu_file.Append(wx.ID_EXIT, "E&xit\tCtrl+Q", "Exit application")
            self.Bind(wx.EVT_MENU, self.Exit, id=wx.ID_EXIT)
            menu.Append(menu_file, "&File")
            menu_view = wx.Menu()
            self.menu_view_c = menu_view.Append(index.next(), "C&lean template", kind=wx.ITEM_CHECK)
            self.Bind(wx.EVT_MENU, self.Clean_template, id=index.current)
            self.menu_view_c.Check(True)
            menu_view.AppendSeparator()
            self.menu_view_y = menu_view.Append(index.next(), "&yaml", kind=wx.ITEM_RADIO)
            self.Bind(wx.EVT_MENU, self.Use_yaml, id=index.current)
            self.menu_view_j = menu_view.Append(index.next(), "&json", kind=wx.ITEM_RADIO)
            self.Bind(wx.EVT_MENU, self.Use_json, id=index.current)
            self.menu_view_y.Check(True)
            menu.Append(menu_view, "&View")
            # menu_view.AppendSeparator()
            # self.menu_view_s = menu_view.Append(index.next(), '&Status Preview', kind=wx.ITEM_CHECK)
            # self.Bind(wx.EVT_MENU, self.Status_Preview, id=index.current)
            # self.menu_view_s.Check(False)
            menu_view.AppendSeparator()
            self.menu_view_v = menu_view.Append(index.next(), "&VulnParam highlighting", kind=wx.ITEM_CHECK)
            self.Bind(wx.EVT_MENU, self.VulnParam_highlighting, id=index.current)
            self.menu_view_v.Check(True)
            self.menu_view_i = menu_view.Append(
                index.next(),
                "V&iewState truncation",
                "Warning! Application performance will noticeably decrease!",
                kind=wx.ITEM_CHECK,
            )
            self.Bind(wx.EVT_MENU, self.Viewstate_truncation, id=index.current)
            self.menu_view_i.Check(True)
            self.menu_view_r = menu_view.Append(
                index.next(),
                "Include &requests and responses",
                "Warning! Have a small scan or be very patient!",
                kind=wx.ITEM_CHECK,
            )
            self.menu_view_r.Check(False)
            menu_view.AppendSeparator()
            self.menu_view_t = menu_view.Append(index.next(), "Always on &top", kind=wx.ITEM_CHECK)
            self.Bind(wx.EVT_MENU, self.Always_on_top, id=index.current)
            self.menu_view_t.Check(True)
            menu_tools = wx.Menu()
            self.menu_tools_template_structure_preview = menu_tools.Append(index.next(), "Te&mplate structure preview")
            self.menu_tools_template_structure_preview.Enable(False)
            self.Bind(wx.EVT_MENU, self.Template_Structure_Preview, id=index.current)
            self.menu_tools_merge_scan_into_content = menu_tools.Append(index.next(), "Mer&ge Scan into Content")
            self.menu_tools_merge_scan_into_content.Enable(False)
            self.Bind(wx.EVT_MENU, self.Merge_Scan_Into_Content, id=index.current)
            self.menu_tools_generate_few_passwords = menu_tools.Append(index.next(), "Generate &few passwords")
            self.Bind(wx.EVT_MENU, self.Generate_few_passwords, id=index.current)
            menu.Append(menu_tools, "&Tools")
            menu_help = wx.Menu()
            menu_help.Append(index.next(), "&Usage")
            self.Bind(wx.EVT_MENU, self.Usage, id=index.current)
            menu_help.Append(index.next(), "&Changelog")
            self.Bind(wx.EVT_MENU, self.Changelog, id=index.current)
            menu_help.AppendSeparator()
            menu_help.Append(wx.ID_ABOUT, "&About")
            self.Bind(wx.EVT_MENU, self.About, id=wx.ID_ABOUT)
            menu.Append(menu_help, "&Help")
            self.SetMenuBar(menu)

            # Frame layout arrangement
            class FileDropTarget(wx.FileDropTarget):
                def __init__(self, target, handler):
                    wx.FileDropTarget.__init__(self)
                    self.target = target
                    self.handler = handler

                def OnDropFiles(self, x, y, filenames):
                    self.handler(filenames)

            panel = wx.Panel(self)
            vbox = wx.BoxSizer(wx.VERTICAL)
            fgs = wx.FlexGridSizer(5, 2, 9, 25)

            # Template
            self.ctrl_st_t = wx.StaticText(panel, label="Template:")
            self.ctrl_st_t.Enable(False)
            self.ctrl_tc_t = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(200, 3 * 17))

            def ctrl_tc_t_OnFocus(e):
                self.ctrl_tc_t.ShowNativeCaret(False)
                # for unknown reason this refuse to work in wxpython 3.0
                e.Skip()

            def ctrl_tc_t_OnDoubleclick(e):
                if self.ctrl_st_t.IsEnabled():
                    self.application.TextWindow(self, title="Template Preview", content=self.ctrl_tc_t.GetValue())
                e.Skip()

            self.ctrl_tc_t.Bind(wx.EVT_SET_FOCUS, ctrl_tc_t_OnFocus)
            self.ctrl_tc_t.Bind(wx.EVT_LEFT_DCLICK, ctrl_tc_t_OnDoubleclick)

            def ctrl_tc_t_OnMouseOver(e):
                self.status("You might use drag & drop", hint=True)
                e.Skip()

            # def ctrl_tc_t_OnMouseLeave(e):
            #    self.status('')
            #    e.Skip()
            self.ctrl_tc_t.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_t_OnMouseOver)
            # self.ctrl_tc_t.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_t_OnMouseLeave)
            def ctrl_tc_t_OnDropFiles(filenames):
                if len(filenames) != 1:
                    wx.MessageBox("Single file is expected!", "Error", wx.OK | wx.ICON_ERROR)
                    return
                self._open_template(filenames[0])

            ctrl_tc_t_dt = FileDropTarget(self.ctrl_tc_t, ctrl_tc_t_OnDropFiles)
            self.ctrl_tc_t.SetDropTarget(ctrl_tc_t_dt)
            fgs.AddMany([(self.ctrl_st_t, 1, wx.EXPAND), (self.ctrl_tc_t, 1, wx.EXPAND)])

            # Content + Edit
            self.ctrl_st_c = wx.StaticText(panel, label="Content:")
            self.ctrl_st_c.Enable(False)
            self.ctrl_tc_c = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(200, 3 * 17))
            self.color_tc_bg_e = self.ctrl_tc_c.GetBackgroundColour()
            self.ctrl_tc_c.Enable(False)
            self.color_tc_bg_d = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)
            self.ctrl_tc_c.SetBackgroundColour(self.color_tc_bg_d)

            def ctrl_tc_c_OnFocus(e):
                self.ctrl_tc_c.ShowNativeCaret(False)
                e.Skip()

            def ctrl_tc_c_OnDoubleclick(e):
                if self.ctrl_st_c.IsEnabled():
                    self.application.TextWindow(self, title="Content Preview", content=self.ctrl_tc_c.GetValue())
                e.Skip()

            self.ctrl_tc_c.Bind(wx.EVT_SET_FOCUS, ctrl_tc_c_OnFocus)
            self.ctrl_tc_c.Bind(wx.EVT_LEFT_DCLICK, ctrl_tc_c_OnDoubleclick)

            def ctrl_tc_c_b_onClick(e):
                self.application.YamledWindowWrapper(self, title="Content", content=self.report._content)
                pass

            def ctrl_tc_c_onResize(e):
                size = self.ctrl_tc_c.GetSize()
                self.ctrl_tc_c_b.SetPosition((size[0] - 36 - 1, -1))

            self.ctrl_tc_c_b = wx.Button(self.ctrl_tc_c, index.next(), "E", size=(16, 16))
            self.ctrl_tc_c_b.Bind(wx.EVT_BUTTON, ctrl_tc_c_b_onClick)
            self.ctrl_tc_c.Bind(wx.EVT_SIZE, ctrl_tc_c_onResize)
            self.ctrl_tc_c_b.Hide()

            def ctrl_tc_c_b_OnMouseOver(e):
                self.status("Send Content to Yaml Editor", hint=True)
                e.Skip()

            # def ctrl_tc_c_b_OnMouseLeave(e):
            #    self.status('')
            #    e.Skip()
            self.ctrl_tc_c_b.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_c_b_OnMouseOver)
            # self.ctrl_tc_c_b.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_c_b_OnMouseLeave)
            def ctrl_tc_c_OnMouseOver(e):
                if self.ctrl_st_c.IsEnabled():  # Yamled
                    self.ctrl_tc_c_b.Show()
                self.status("You might use drag & drop", hint=True)
                e.Skip()

            # def ctrl_tc_c_OnMouseLeave(e):
            #    self.status('')
            #    e.Skip()
            self.ctrl_tc_c.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_c_OnMouseOver)
            # self.ctrl_tc_c.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_c_OnMouseLeave)
            def ctrl_tc_c_OnDropFiles(filenames):
                if len(filenames) != 1:
                    wx.MessageBox("Single file is expected!", "Error", wx.OK | wx.ICON_ERROR)
                    return
                self._open_content(filenames[0])
                if self.ctrl_st_c.IsEnabled():  # Yamled
                    self.ctrl_tc_c_b.Show()

            ctrl_tc_c_dt = FileDropTarget(self.ctrl_tc_c, ctrl_tc_c_OnDropFiles)
            self.ctrl_tc_c.SetDropTarget(ctrl_tc_c_dt)
            fgs.AddMany([(self.ctrl_st_c, 1, wx.EXPAND), (self.ctrl_tc_c, 1, wx.EXPAND)])

            # Scan + Edit button
            self.ctrl_st_s = wx.StaticText(panel, label="Scan:")
            self.ctrl_st_s.Enable(False)
            self.ctrl_tc_s = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(200, 3 * 17))

            def ctrl_tc_s_OnFocus(e):
                self.ctrl_tc_s.ShowNativeCaret(False)
                e.Skip()

            def ctrl_tc_s_OnDoubleclick(e):
                if self.ctrl_st_s.IsEnabled():
                    self.application.TextWindow(self, title="Scan Preview", content=self.ctrl_tc_s.GetValue())
                e.Skip()

            self.ctrl_tc_s.Bind(wx.EVT_SET_FOCUS, ctrl_tc_s_OnFocus)
            self.ctrl_tc_s.Bind(wx.EVT_LEFT_DCLICK, ctrl_tc_s_OnDoubleclick)

            def ctrl_tc_s_b_onClick(e):
                self.application.YamledWindowWrapper(self, title="Scan", content=self.scan._scan)
                pass

            def ctrl_tc_s_onResize(e):
                size = self.ctrl_tc_s.GetSize()
                self.ctrl_tc_s_b.SetPosition((size[0] - 36 - 1, -1))

            self.ctrl_tc_s_b = wx.Button(self.ctrl_tc_s, index.next(), "E", size=(16, 16))
            self.ctrl_tc_s_b.Bind(wx.EVT_BUTTON, ctrl_tc_s_b_onClick)
            self.ctrl_tc_s.Bind(wx.EVT_SIZE, ctrl_tc_s_onResize)
            self.ctrl_tc_s_b.Hide()

            def ctrl_tc_s_b_OnMouseOver(e):
                self.status("Send Scan to Yaml Editor", hint=True)
                e.Skip()

            # def ctrl_tc_s_b_OnMouseLeave(e):
            #    self.status('')
            #    e.Skip()
            self.ctrl_tc_s_b.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_s_b_OnMouseOver)
            # self.ctrl_tc_s_b.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_s_b_OnMouseLeave)
            def ctrl_tc_s_OnMouseOver(e):
                if self.ctrl_st_s.IsEnabled():  # Yamled
                    self.ctrl_tc_s_b.Show()
                self.status("You might use drag & drop", hint=True)
                e.Skip()

            # def ctrl_tc_s_OnMouseLeave(e):
            #    #self.ctrl_tc_s_b.Hide()
            #    self.status('')
            #    e.Skip()
            self.ctrl_tc_s.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_s_OnMouseOver)
            # self.ctrl_tc_s.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_s_OnMouseLeave)
            def ctrl_tc_s_OnDropFiles(filenames):
                if len(filenames) != 1:
                    wx.MessageBox("Single file is expected!", "Error", wx.OK | wx.ICON_ERROR)
                    return
                self._open_scan(filenames[0])
                if self.ctrl_st_s.IsEnabled():  # Yamled
                    self.ctrl_tc_s_b.Show()

            ctrl_tc_s_dt = FileDropTarget(self.ctrl_tc_s, ctrl_tc_s_OnDropFiles)
            self.ctrl_tc_s.SetDropTarget(ctrl_tc_s_dt)
            fgs.AddMany([(self.ctrl_st_s, 1, wx.EXPAND), (self.ctrl_tc_s, 1, wx.EXPAND)])

            # Knowledge Base
            self.ctrl_st_k = wx.StaticText(panel, label="Knowledge Base:")
            self.ctrl_st_k.Enable(False)
            self.ctrl_tc_k = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(200, 3 * 17))
            self.ctrl_tc_k.Enable(False)
            self.ctrl_tc_k.SetBackgroundColour(self.color_tc_bg_d)

            def ctrl_tc_k_OnFocus(e):
                self.ctrl_tc_k.ShowNativeCaret(False)
                e.Skip()

            def ctrl_tc_k_OnDoubleclick(e):
                if self.ctrl_st_k.IsEnabled():
                    self.application.TextWindow(self, title="KB Preview", content=self.ctrl_tc_k.GetValue())
                e.Skip()

            self.ctrl_tc_k.Bind(wx.EVT_SET_FOCUS, ctrl_tc_k_OnFocus)
            self.ctrl_tc_k.Bind(wx.EVT_LEFT_DCLICK, ctrl_tc_k_OnDoubleclick)

            def ctrl_tc_k_OnMouseOver(e):
                self.status("You might use drag & drop", hint=True)
                e.Skip()

            def ctrl_tc_k_OnMouseLeave(e):
                self.status("")
                e.Skip()

            self.ctrl_tc_k.Bind(wx.EVT_ENTER_WINDOW, ctrl_tc_k_OnMouseOver)
            self.ctrl_tc_k.Bind(wx.EVT_LEAVE_WINDOW, ctrl_tc_k_OnMouseLeave)

            def ctrl_tc_k_OnDropFiles(filenames):
                if len(filenames) != 1:
                    wx.MessageBox("Single file is expected!", "Error", wx.OK | wx.ICON_ERROR)
                    return
                self._open_kb(filenames[0])

            ctrl_tc_k_dt = FileDropTarget(self.ctrl_tc_k, ctrl_tc_k_OnDropFiles)
            self.ctrl_tc_k.SetDropTarget(ctrl_tc_k_dt)
            fgs.AddMany([(self.ctrl_st_k, 1, wx.EXPAND), (self.ctrl_tc_k, 1, wx.EXPAND)])

            def panel_OnMouseOver(e):
                self.status("")
                self.ctrl_tc_c_b.Hide()
                self.ctrl_tc_s_b.Hide()
                e.Skip()

            panel.Bind(wx.EVT_ENTER_WINDOW, panel_OnMouseOver)

            # Report
            # self.ctrl_st_r = wx.StaticText(panel, label='Report:')
            # self.ctrl_st_r.Enable (False)
            # self.ctrl_tc_r = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY, size=(200, 3*17,))
            # self.ctrl_tc_r.Enable(False)
            # self.ctrl_tc_r.SetBackgroundColour (self.color_tc_bg_d)
            # def ctrl_tc_r_OnFocus (e):
            #    self.ctrl_tc_r.ShowNativeCaret (False)
            #    e.Skip()
            # self.ctrl_tc_r.Bind (wx.EVT_SET_FOCUS, ctrl_tc_r_OnFocus)
            # fgs.AddMany ([(self.ctrl_st_r, 1, wx.EXPAND), (self.ctrl_tc_r, 1, wx.EXPAND)])
            fgs.AddGrowableRow(0, 1)
            fgs.AddGrowableRow(1, 1)
            fgs.AddGrowableRow(2, 1)
            fgs.AddGrowableRow(3, 1)
            # fgs.AddGrowableRow (4, 1)
            fgs.AddGrowableCol(1, 1)
            vbox.Add(fgs, proportion=1, flag=wx.ALL | wx.EXPAND, border=10)
            # data = wx.TextCtrl(panel)
            # hbox1 = wx.BoxSizer (wx.HORIZONTAL)
            # hbox1.Add(data, proportion=1, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=10)
            # vbox.Add (hbox1, 0, wx.ALL|wx.EXPAND, 0)
            panel.SetSizer(vbox)
            vbox.Fit(self)
            # self.SetMinSize(self.GetSize())
            self.statusbar = self.CreateStatusBar()
            self._statusbar_h = self.statusbar.GetSize()[1]
            # self.statusbar.Hide()
            self.status("Started")
            self.SetMinSize((self.GetSize()[0], self.GetSize()[1] + self._statusbar_h))
            # panel = wx.Panel (self)
            # vbox = wx.BoxSizer (wx.VERTICAL)
            # hbox1 = wx.BoxSizer (wx.HORIZONTAL)
            ##st1 = wx.StaticText (panel, wx.ID_ANY, label='Not yet ready')
            # st1 = wx.StaticText (panel, wx.ID_ANY, label='Template:', size=(100, -1,))
            # hbox1.Add (st1, 0, wx.ALL, 5)
            # tc1 = wx.TextCtrl (panel, wx.ID_ANY, size=(300, -1,))
            # hbox1.Add (tc1, 1, wx.ALL|wx.EXPAND, 0)
            # vbox.Add (hbox1, 0, wx.ALL|wx.EXPAND, 0)
            # hbox2 = wx.BoxSizer (wx.HORIZONTAL)
            # st2 = wx.StaticText (panel, wx.ID_ANY, label='Scan:', size=(100, -1,))
            # hbox2.Add (st2, 0, wx.ALL, 5)
            # tc2 = wx.TextCtrl (panel, wx.ID_ANY, size=(300, -1,))
            # hbox2.Add (tc2, 1, wx.ALL|wx.EXPAND, 0)
            # vbox.Add (hbox2, 0, wx.ALL|wx.EXPAND, 0)
            ##vbox.Add (hbox1, 0, wx.CENTER, 5)
            # panel.SetSizer (vbox)
            # vbox.Fit (self)
            # self.Center()
            self.alignVMiddleRight()
            self.Show()
            self.Always_on_top(None)
            # print 'loaded'

        def alignVMiddleRight(self):
            dw, dh = wx.DisplaySize()
            w, h = self.GetSize()
            x = dw - w - 40 * 2
            y = dh / 2 - h / 2
            self.SetPosition((x, y))

        def Exit(self, e):
            self.Close()

        def About(self, e):
            dialog = wx.AboutDialogInfo()
            # dialog.SetIcon (wx.Icon('icon.ico', wx.BITMAP_TYPE_PNG))
            dialog.SetIcon(self.icon)
            dialog.SetName(self.application.title + ": " + self.application.long_title)
            dialog.SetVersion(self.application.version)
            dialog.SetCopyright(self.application.c)
            dialog.SetDescription("\n".join(map(lambda x: x[4:], self.application.about.split("\n")[1:][:-1])))

            dialog.SetWebSite(self.application.url)
            dialog.SetLicence(self.application.license)
            wx.AboutBox(dialog)

        def Template_Structure_Preview(self, e):
            self.application.TextWindow(
                self, title="Template Structure Preview", content=self.report.template_dump_struct()
            )

        def HtmlUsageView(self, content):
            page = ""
            for i in content.split("\n\n"):
                if i[:2] == "# ":
                    page += "<h1>" + cgi.escape(i[2:]) + "</h1>"
                elif i[:3] == "## ":
                    page += "<h2>" + cgi.escape(i[3:]) + "</h2>"
                else:
                    page += "<pre>" + cgi.escape(i) + "</pre>"
            return (
                "<html><head><style>"
                "body {margin:0;padding:0}"
                "h1 {font-size:20px}"
                "h2 {font-size:16px}"
                "pre {font-size:13px; font-family:sans-serif}"
                "</style></head><body>" + page + "<p/></body></html>"
            )

        def Usage(self, e):
            # self.application.TextWindow(self, title=self.Usage.__name__, content='\n'.join(
            #    map(lambda x: x[4:], self.application.usage.split('\n')[1:][:-1])))
            self.application.HtmlWindow(
                self,
                title=self.Usage.__name__,
                content=self.HtmlUsageView(
                    "\n".join(map(lambda x: x[4:], self.application.usage.split("\n")[1:][:-1]))
                ),
            )

        def Changelog(self, e):
            self.application.TextWindow(
                self,
                title=self.Changelog.__name__,
                content="\n".join(map(lambda x: x[4:], self.application.changelog.split("\n")[1:][:-1])),
            )

        def Destroy(self):
            map(lambda x: x.Close(), filter(lambda x: isinstance(x, wx.Frame), self.GetChildren()))
            wx.WakeUpIdle()
            # print 'destroying MainWindow'
            super(wx.Frame, self).Destroy()

        def Open_Template(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Open Template",
                "",
                "",
                "XML files (*.xml)|*.xml|All files (*.*)|*.*",
                wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self._open_template(openFileDialog.GetPath())

        def _open_template(self, filename):
            self.status("Loading template...")
            self.ctrl_st_t.Enable(False)
            self.ctrl_tc_t.SetValue("")
            self.ctrl_st_c.Enable(False)
            self.ctrl_tc_c.SetValue("")
            self.menu_file_open_k.Enable(False)
            self.menu_file_save_t.Enable(False)
            self.menu_file_save_r.Enable(False)
            self.menu_tools_template_structure_preview.Enable(False)
            # if self.report:
            #    del self.report
            # self.report = Report()
            # print self.report._skel
            self.report.template_load_xml(filename, clean=self.menu_view_c.IsChecked())
            if self.menu_view_y.IsChecked():
                self.ctrl_tc_t.SetValue(self.report.template_dump_yaml())
            else:
                self.ctrl_tc_t.SetValue(self.report.template_dump_json())
            self.ctrl_st_t.Enable(True)
            self.ctrl_tc_c.Enable(True)
            self.ctrl_tc_c.SetBackgroundColour(self.color_tc_bg_e)
            self.ctrl_tc_k.Enable(True)
            self.ctrl_tc_k.SetBackgroundColour(self.color_tc_bg_e)
            self.menu_file_open_k.Enable(True)
            self.menu_file_open_c.Enable(True)
            self.menu_file_save_t.Enable(True)
            self.menu_tools_template_structure_preview.Enable(True)
            if self.scan:
                self.menu_file_save_r.Enable(True)
            if self.ctrl_st_s.IsEnabled():
                self.menu_tools_merge_scan_into_content.Enable(True)
            self.status("Template loaded")

        def Open_Content(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Open Content",
                "",
                "",
                "Content files (*.yaml; *.json)|*.yaml;*.json|All files (*.*)|*.*",
                wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self._open_content(openFileDialog.GetPath())

        def __show_content(self):
            if self.menu_view_y.IsChecked():
                self.ctrl_tc_c.SetValue(self.report.content_dump_yaml())
            else:
                self.ctrl_tc_c.SetValue(self.report.content_dump_json())

        def _open_content(self, filename):
            self.status("Loading content...")
            self.ctrl_st_c.Enable(False)
            json_ext = ".json"
            if filename[-len(json_ext) :] == json_ext:
                self.report.content_load_json(filename)
            else:
                self.report.content_load_yaml(filename)
            self.save_into_directory = os.path.dirname(filename)
            self.__show_content()
            self.ctrl_st_c.Enable(True)
            self.menu_file_save_r.Enable(True)
            self.menu_file_save_c.Enable(True)
            # if self.scan:
            #    self.menu_tools_merge_scan_into_content.Enable(True)
            self.status("Content loaded")

        def Open_Scan(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Open Scan",
                "",
                "",
                "Scan files (*.xml; *.yaml; *.json)|*.xml;*.yaml;*.json|All files (*.*)|*.*",
                wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self._open_scan(openFileDialog.GetPath())

        def _open_scan(self, filename):
            self.status("Loading scan...")
            self.menu_file_save_s.Enable(False)
            if self.scan is not None:
                del self.scan
            self.scan = Scan(filename, requests_and_responses=self.menu_view_r.IsChecked())
            if self.menu_view_y.IsChecked():
                self.ctrl_tc_s.SetValue(self.scan.dump_yaml(truncate=self.menu_view_i.IsChecked()))
            else:
                self.ctrl_tc_s.SetValue(self.scan.dump_json(truncate=self.menu_view_i.IsChecked()))
            self.ctrl_st_s.Enable(True)
            self.menu_file_save_s.Enable(True)
            self.menu_file_save_r.Enable(True)
            # if self.ctrl_st_c.IsEnabled():
            if self.ctrl_st_t.IsEnabled():
                self.menu_tools_merge_scan_into_content.Enable(True)
            self.status("Scan loaded")

        def Merge_Scan_Into_Content(self, e):
            self.status("Merging Scan into Content...")
            self.report.merge_scan(self.scan.modify(truncate=self.menu_view_i.IsChecked()))
            self.ctrl_st_c.Enable(True)
            self.menu_file_save_c.Enable(True)
            self.menu_file_save_s.Enable(False)
            del self.scan
            self.scan = None
            self.ctrl_tc_s.SetValue("")
            self.ctrl_st_s.Enable(False)
            self.menu_file_save_s.Enable(False)
            self.__show_content()
            self.menu_tools_merge_scan_into_content.Enable(False)
            self.report.content_refresh()
            self.status("Merged")

        def Generate_few_passwords(self, e):
            self.application.TextWindow(
                self, title="Random Password Generator", content="\n".join(pwgen.Few(15)), size=(235, 270)
            )

        # def Open_Knowledge_Base (self, e):
        #    pass
        # def Generate_Content (self, e):
        #    pass
        # def Generate_Knowledge_Base (self, e):
        #    pass
        # def Generate_Report (self, e):
        #    pass
        def Save_Template_As(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Save Template As",
                self.save_into_directory,
                "",
                "Content files (*.yaml; *.json)|*.yaml;*.json|All files (*.*)|*.*",
                wx.FD_SAVE | wx.wx.FD_OVERWRITE_PROMPT,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            json_ext = ".json"
            filename = openFileDialog.GetPath()
            self.status("Saving Template content...")
            h = open(filename, "w")
            if filename[-len(json_ext) :] == json_ext:
                h.write(self.report.template_dump_json().encode("utf-8"))
            else:
                h.write(self.report.template_dump_yaml().encode("utf-8"))
            h.close()
            self.status("Template content saved")

        def Save_Content_As(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Save Content As",
                self.save_into_directory,
                "",
                "Content files (*.yaml; *.json)|*.yaml;*.json|All files (*.*)|*.*",
                wx.FD_SAVE | wx.wx.FD_OVERWRITE_PROMPT,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            json_ext = ".json"
            filename = openFileDialog.GetPath()
            self.status("Saving Content...")
            h = open(filename, "w")
            if filename[-len(json_ext) :] == json_ext:
                h.write(self.report.content_dump_json().encode("utf-8"))
            else:
                h.write(self.report.content_dump_yaml().encode("utf-8"))
            h.close()
            self.status("Content saved")

        def Save_Scan_As(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Save Scan As",
                self.save_into_directory,
                "",
                "Content files (*.yaml; *.json)|*.yaml;*.json|All files (*.*)|*.*",
                wx.FD_SAVE | wx.wx.FD_OVERWRITE_PROMPT,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            json_ext = ".json"
            filename = openFileDialog.GetPath()
            h = open(filename, "w")
            if filename[-len(json_ext) :] == json_ext:
                h.write(self.scan.dump_json(truncate=self.menu_view_i.IsChecked()).encode("utf-8"))
            else:
                h.write(self.scan.dump_yaml(truncate=self.menu_view_i.IsChecked()).encode("utf-8"))
            h.close()
            self.status("Scan saved")

        def _refresh(self):
            self.status("Reloading previews...")
            if self.menu_view_y.IsChecked():
                self._Use_yaml()
            else:
                self._Use_json()
            self.status("Ready")

        def _clean_template(self, force=False):
            if force == True or self.report.template_cleanup_required == True:
                if self.ctrl_st_t.IsEnabled():
                    self.report.template_reload(clean=self.menu_view_c.IsChecked())
                    if self.ctrl_st_c.IsEnabled():
                        self.report.content_reload()
                    if self.ctrl_st_k.IsEnabled():
                        self.report.kb_reload()
                    self._refresh()
            #    print 'cleanup performed.'
            # else:
            #    print 'cleanup omitted.'

        def Clean_template(self, e):
            self._clean_template(force=True)

        # def Save_Knowledge_Base_As (self, e):
        #    pass
        def Save_Report_As(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Save Report As",
                self.save_into_directory,
                "",
                "XML files (*.xml)|*.xml|All files (*.*)|*.*",
                wx.FD_SAVE | wx.wx.FD_OVERWRITE_PROMPT,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            filename = openFileDialog.GetPath()
            if filename == self.report._template_filename:
                wx.MessageBox(
                    "For safety reasons, template overwriting with generated report is not allowed!",
                    "Error",
                    wx.OK | wx.ICON_ERROR,
                )
                return
            self.status("Generating and saving the report...")
            self.report.scan = self.scan
            self._clean_template()
            # self.report.xml_apply_meta()
            self.report.xml_apply_meta(
                vulnparam_highlighting=self.menu_view_v.IsChecked(), truncation=self.menu_view_i.IsChecked()
            )
            self.report.save_report_xml(filename)
            # self._clean_template()
            self.status("Report saved")

        def _Use_yaml(self):
            if self.ctrl_st_t.IsEnabled():
                self.ctrl_tc_t.SetValue(self.report.template_dump_yaml())
            if self.ctrl_st_c.IsEnabled():
                self.ctrl_tc_c.SetValue(self.report.content_dump_yaml())
            if self.ctrl_st_s.IsEnabled():
                self.ctrl_tc_s.SetValue(self.scan.dump_yaml(truncate=self.menu_view_i.IsChecked()))
            if self.ctrl_st_k.IsEnabled():
                self.ctrl_tc_k.SetValue(self.report.kb_dump_yaml())

        def Use_yaml(self, e):
            self._Use_yaml()

        def _Use_json(self):
            if self.ctrl_st_t.IsEnabled():
                self.ctrl_tc_t.SetValue(self.report.template_dump_json())
            if self.ctrl_st_c.IsEnabled():
                self.ctrl_tc_c.SetValue(self.report.content_dump_json())
            if self.ctrl_st_s.IsEnabled():
                self.ctrl_tc_s.SetValue(self.scan.dump_json(truncate=self.menu_view_i.IsChecked()))
            if self.ctrl_st_k.IsEnabled():
                self.ctrl_tc_k.SetValue(self.report.kb_dump_json())

        def Use_json(self, e):
            self._Use_json()

        # def Status_Preview(self, e):
        #    if self.menu_view_s.IsChecked():
        #        self.statusbar.Show()
        #        self.SetSize((-1,self.GetSize()[1]+self._statusbar_h,))
        #    else:
        #        self.statusbar.Hide()
        #        self.SetSize((-1,self.GetSize()[1]-self._statusbar_h,))

        def status(self, text, hint=False):
            # print text
            self.SetStatusText(["", "Hint: "][hint] + text)

        def VulnParam_highlighting(self, e):
            pass

        def Viewstate_truncation(self, e):
            self._refresh()

        def Always_on_top(self, e):
            if self.menu_view_t.IsChecked():
                self.SetWindowStyle(self.GetWindowStyle() | wx.STAY_ON_TOP)
                for i in self.children:
                    i.SetWindowStyle(i.GetWindowStyle() | wx.STAY_ON_TOP)
            else:
                self.SetWindowStyle(self.GetWindowStyle() & ~wx.STAY_ON_TOP)
                for i in self.children:
                    i.SetWindowStyle(i.GetWindowStyle() & ~wx.STAY_ON_TOP)

        def Open_Knowledge_Base(self, e):
            openFileDialog = wx.FileDialog(
                self,
                "Open Knowledge Base",
                "",
                "",
                "Knowledge Base files (*.yaml; *.json; *.csv)|*.yaml;*.json;*.csv|All files (*.*)|*.*",
                wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
            )
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return
            self._open_kb(openFileDialog.GetPath())

        def _open_kb(self, filename):
            self.ctrl_st_k.Enable(False)
            csv_ext = ".csv"
            json_ext = ".json"
            if filename[-len(csv_ext) :].lower() == csv_ext:
                self.report.kb_load_csv(filename)
            elif filename[-len(json_ext) :] == json_ext:
                self.report.kb_load_json(filename)
            else:
                self.report.kb_load_yaml(filename)
            if self.menu_view_y.IsChecked():
                self.ctrl_tc_k.SetValue(self.report.kb_dump_yaml())
            else:
                self.ctrl_tc_k.SetValue(self.report.kb_dump_json())
            self.ctrl_st_k.Enable(True)
            # self.menu_file_save_k.Enable (True)
            self.menu_file_save_r.Enable(True)