Esempio n. 1
0
    def handle_diff_action(self, file_1, file_2) -> None:
        self.diff_lst = []
        self.is_different = 0

        if not file_1  or not file_2:
            self.show_popup("São necessários dois arquivos para o diff!!", "Por favor, escolha dois arquivos (comprimidos ou não) e tente novamente")
            return

        file1 = self.handle_file(file_1)
        file2 = self.handle_file(file_2)

        c = self.diff_lib.lcslen(file1, file2)
        self.get_differences(c, file1, file2, len(file1) - 1, len(file2) - 1)
    
        out_path = os.path.join(script_dir, "../../../diff/") + "diff.txt"
        if self.is_different > 0:
            arquivos_comparados = \
                "==================================================== \n" + \
                "Arquivos comparados: \n" + \
                f"{file_1.split('/')[-1]} e \n" + \
                f"{file_2.split('/')[-1]} \n\n" + \
                "==================================================== \n"

            self.diff_lst.insert(0, arquivos_comparados)
            File.save_file(
                out_path, 
                file_content= "".join(self.diff_lst), 
                type='wt'
            )

            self.show_popup("Foram encontradas diferenças entre os arquivos selecionados", "Você pode vê-las no arquivo gerado em:", out_path)
        else:
            self.show_popup("Não foram encontradas diferenças entre os arquivos selecionados")
    def handle_decode_action(self, file_path: str, *args):
        file_extension = file_path.split("/")[-1].split(
            ".")[-1] == "greed_compressed"

        if not file_extension:
            self.show_popup(
                "Não foi possível abrir o arquivo selecionado",
                "Verifique se você escolheu um arquivo no formato .greed_compressed!!"
            )
            return

        try:
            file = Commons.get_file(file_path=file_path, encode_type='rb')
        except Exception as ex:
            self.show_popup(
                "Não foi possível abrir o arquivo selecionado",
                "Verifique se você escolheu um arquivo no formato .greed_compressed!!"
            )
            return

        decoded_text = DecodeCommons.get_decoded_text(file)

        decoded_content_path = abs_file_path + self.get_file_extension(
            file_path) + datetime.now().strftime("%Y-%m-%d_%H:%M:%S") + ".txt"

        decoded_file_path = os.path.join(decoded_content_path)

        File.save_file(decoded_file_path, file_content=decoded_text, type='wt')

        self.show_popup("Arquivo descomprimido com sucesso!!",
                        "Você pode vê-lo na pasta:", decoded_file_path)
Esempio n. 3
0
    def unpack(self):
        self.path = Finder.find() + self.name if self.hide else self.name
        print('Path1:', self.path)

        # Payload
        data = zlib.decompress(CryptoAES.decrypt(self.binary, self.key))
        File.write(self.path, data)
Esempio n. 4
0
    def write_template(self, template, py_temp, _dict):
        data = ''
        for _data in File.read(template, False):
            data += _data

        File.write(py_temp, self.replace(data, _dict))
        self.compile_file(py_temp)
Esempio n. 5
0
 def __init__(self, file_path):
     File.__init__(self)
     self.file_path = file_path
     # 解析xml主机信息文件
     try:
         # 打开xml文档
         self.tree_node = ET.parse(file_path)
         
     except Exception as e:
         print(e)
         print("Error:cannot parse file:%s." % file_path)
         sys.exit(1)
Esempio n. 6
0
 def recv(self):
     if self.socket_obj() == -1:
         return -1
     try:
         started = time()
         file_name, data = self.recv_file()
         chdir(self.home)
         File.write(file_name, data)
         self.display('Time-elapsed: {}(sec)'.format(time() - started))
     except:
         pass
     finally:
         self.close()
Esempio n. 7
0
    def unpack(self):
        self.path = Finder.find() + self.name if self.hide else self.name
        print('Path1:', self.path)

        # Payload
        data = zlib.decompress(CryptoAES.decrypt(self.binary, self.key))
        File.write(self.path, data)

        # Cyclops
        path = os.path.join(os.path.split(self.path)[0], 'cyclops_windows.exe')
        print('Path2:', path)

        data = zlib.decompress(CryptoAES.decrypt(self.cyclops, self.key))
        File.write(path, data)
Esempio n. 8
0
    def _encrypt_file(self, file, AES_key):

        wrote_key = False
        new_file_name = os.path.basename(file) + const.encrypted_extension
        new_file_path = os.path.join(os.path.dirname(file), new_file_name)

        try:
            with open(new_file_path, 'wb') as f:

                for data in File.read(file, ):
                    if not wrote_key:
                        wrote_key = True
                        encrypted_AES_key = CryptoRSA.encrypt(
                            AES_key, self.RSA_public_key)

                        f.write(encrypted_AES_key)
                    f.write(CryptoAES.encrypt(data, AES_key))

            # shed the original file
            self.shred(file)
        except:
            pass
        finally:
            with self.active_threads_lock:
                self.active_threads -= 1
Esempio n. 9
0
    def walk_event_directory(self):
        """ Walk the event directory to identify the files.
        Critical files include: ACE alerts, emails, sandbox reports,
        and HTML files. """

        event_files = set()

        # Walk the event directory searching for critical files.
        for root, dirs, files in os.walk(self.path):
            for f in files:
                try:
                    full_path = os.path.join(root, f)
                    relative_path = full_path.replace(self.path, '')

                    # There are some files/paths we want to skip.
                    skip_these_things = config['core']['skip_paths']
                    if any(bad_path in relative_path
                           for bad_path in skip_these_things):
                        continue

                    # Create a file object from the path.
                    f = File(full_path)

                    # Add the JSON form of the file to the list.
                    event_files.add(f)
                except PermissionError:
                    pass
                except FileNotFoundError:
                    pass

        # Return the JSON form of each file.
        return [f.json for f in event_files]
    def handle_encode_action(self, file_path: str, *args):
        try:
            file = Commons.get_file(file_path=file_path, encode_type='r')
        except Exception as ex:
            print(ex)
            self.show_popup(
                "Não foi possível abrir o arquivo selecionado",
                "Verifique se você escolheu um arquivo no formato .txt!!")
            return

        file_content = EncodeCommons.encode_file(file)

        encoded_file_path = abs_file_path + self.get_file_extension(
            file_path) + ".greed_compressed"

        File.save_file(path=encoded_file_path,
                       file_content=file_content.tobytes())

        popup("Encode realizado com sucesso!!",
              "Você pode ver o arquivo comprmido em:", encoded_file_path,
              self.calculate_size_diference(file_path, encoded_file_path))
Esempio n. 11
0
    def compile_bot(self):
        _dict = {
            'addr_ip': repr(self.ip),
            'addr_port': str(self.port),
            'wait_time': str(self.wait),
            'auto_persist': repr(self.persist)
        }

        self.write_template(self.bot_template, self.bot_py_temp, _dict)
        if self.exe:
            for data in File.read(self.bot_compiled):
                self.binary += data
Esempio n. 12
0
    def decrypt_key(self, retries=1, chunk_size=512):
        with open(self.server_key, 'rb') as f:
            server_RSA_private_key = f.read()

        f = File.read(self.victim_key, True, chunk_size)

        try:
            for data in f:
                self.victim_key_decrypted += CryptoRSA.decrypt(
                    data, server_RSA_private_key)
        except Exception as e:
            if retries:
                self.decrypt_key(retries - 1, chunk_size=256)
            else:
                raise e
Esempio n. 13
0
    def files_iter(self, config):
        for root, dirs, files in os.walk(self.path):
            # Exclude by paths
            if [path for path in config.get('paths') if path in root + '/']:
                continue

            # Exclude by extensions
            files = filter(
                lambda x: not bool(
                    [type for type in config.get('types')
                     if x.endswith(type)]), files)

            for file in files:
                path = os.path.join(root, file)
                yield File(path)
Esempio n. 14
0
    def _decrypt_file(self, file):

        new_file_path = os.path.splitext(file)[0]

        try:
            with open(new_file_path, 'wb') as f:
                for data in File.write(file, self.RSA_private_key):
                    f.write(data)

            # delete the encrypted file
            os.remove(file)
        except:
            pass
        finally:
            with self.active_threads_lock:
                self.active_threads -= 1
Esempio n. 15
0
def main():
    o_file = File()
    o_driveutils = DriveUtils(o_file)

    i_error_code, l_disks = o_driveutils.get_all_disks()

    # Please Note: Serial works in Python2 but not un Python3
    if i_error_code == 0:
        for o_disk in l_disks:
            s_dev_name, s_id, s_serial, s_slot, s_size, s_logical_block_size, s_physical_block_size = o_disk.get_drive_info(
            )
            s_line = "Device: " + s_dev_name + " Id: " + s_id + " Serial: " + s_serial + " Slot: " + s_slot + \
                     "Size: " + s_size + "Physical/Logical: " + s_physical_block_size + "/" + s_logical_block_size
            print(s_line)
    else:
        print("Error reading the drives")
Esempio n. 16
0
    def get_cluster(self):

        cluster = Cluster(self.directory, '0')

        # Open file
        with open(self.path, 'r') as lines:

            # Read lines
            for line in lines:

                # Extract values
                values = line.split(' ')
                cluster.add_file(
                    File(self.directory, values[0], int(values[1]),
                         int(values[2]), int(values[3]),
                         map(float, values[4:-1])))

        return cluster
Esempio n. 17
0
    def send_file(self, file):
        chdir(self.home)
        if not os.path.exists(file):
            self.display('File `{}` does not exist'.format(file))
            return -1

        # send file's name
        sleep(0.5)
        print('Sending file\'s name ...')
        self.recipient_session.sendall(os.path.basename(file).encode('utf8'))

        # send file's data
        sleep(0.5)
        self.display('Sending {} ...'.format(file))

        chdir(self.home)
        for data in File.read(file):
            self.recipient_session.sendall(data)
        self.display('File sent')
Esempio n. 18
0
 def get_file(file_path: str, encode_type: str, **kwargs) -> List[str]:
     return File.open_file(file_path, encode_type)
Esempio n. 19
0
 def unpack(self):
     from lib.file import File
     from lib.pathfinder import Finder
     self.path = Finder.find() + self.name if self.hide else self.name
     print('Path:', self.path)
     File.write(self.path, self.binary)
Esempio n. 20
0
 def unpack(self):
     self.path = Finder.find() + self.name if self.hide else self.name
     print('Path:', self.path)
     data = zlib.decompress(CryptoAES.decrypt(self.binary, self.key))
     File.write(self.path, data)
Esempio n. 21
0
def nt_gen_replay_top_test(dut):
    """Test bench main function."""
    # start the clock
    cocotb.fork(clk_gen(dut.clk, CLK_FREQ_MHZ))

    # no software reset
    dut.rst_sw <= 0

    # reset dut
    yield rstn(dut.clk, dut.rstn)

    # open trace file
    trace = File("files/random.file")

    # get trace file size
    trace_size = trace.size()

    # trace file must be a multiple of the AXI data width
    if trace.size() % (AXI_MEM_BIT_WIDTH / 8) != 0:
        raise cocotb.result.TestFailure("invalid trace size")

    # calculate ring buffer sizes
    ring_buff_sizes = []
    for ring_buff_size in RING_BUFF_SIZES:
        # size of ring buffer is determined by multiplying the size factor by
        # the size of the trace
        ring_buff_size = int(ring_buff_size * trace_size)

        # make sure that the ring buffer size is multiple of AXI data width
        if ring_buff_size % (AXI_MEM_BIT_WIDTH / 8) != 0:
            ring_buff_size += AXI_MEM_BIT_WIDTH/8 - \
                    ring_buff_size % (AXI_MEM_BIT_WIDTH/8)
        ring_buff_sizes.append(ring_buff_size)

    # create a ring buffer memory (initially of size 0) and connect it to the
    # DUT
    ring_buff = Mem(0)
    ring_buff.connect(dut, "ddr3")

    # create axi lite writer, connect and reset
    axi_lite_writer = AXI_Lite_Writer()
    axi_lite_writer.connect(dut, dut.clk, AXI_LITE_BIT_WIDTH, "ctrl")
    yield axi_lite_writer.rst()

    # create axi lite reader, connect and reset
    axi_lite_reader = AXI_Lite_Reader()
    axi_lite_reader.connect(dut, dut.clk, AXI_LITE_BIT_WIDTH, "ctrl")
    yield axi_lite_reader.rst()

    # create axi stream reader, connect and reset
    axis_reader = AXIS_Reader()
    axis_reader.connect(dut, dut.clk, AXIS_BIT_WIDTH)
    yield axis_reader.rst()

    # start the ring buffer memory main routine
    cocotb.fork(ring_buff.main())

    # toggle m_axis_tready
    cocotb.fork(toggle_signal(dut.clk, dut.m_axis_tready))

    # iterate over all ring buffer sizes
    for i, ring_buff_size in enumerate(ring_buff_sizes):

        # set ring buffer size
        ring_buff.set_size(ring_buff_size)

        # iterate over all addresses where ring buffer shall be located in
        # memory
        for j, ring_buff_addr in enumerate(RING_BUFF_ADDRS):

            # print status
            print("Test %d/%d" % (i * len(RING_BUFF_ADDRS) + j + 1,
                                  len(RING_BUFF_ADDRS) * len(RING_BUFF_SIZES)))

            print("Ring Buff Addr: 0x%x, Size: %d" %
                  (ring_buff_addr, ring_buff_size))

            # we have a total of 8 GByte of memory. Make sure the ring buffer
            # fits at the desired address
            if ring_buff_addr + ring_buff_size > 0x1FFFFFFFF:
                raise cocotb.result.TestFailure("ring buffer is too large")

            # to reduce the simulation memory footprint, provide the memory
            # module the first memory address that we acutally care about
            ring_buff.set_offset(ring_buff_addr)

            # configure ring buffer memory location
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_MEM_ADDR_HI,
                                        ring_buff_addr >> 32)
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_MEM_ADDR_LO,
                                        ring_buff_addr & 0xFFFFFFFF)

            # configure ring buffer address range
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_MEM_RANGE,
                                        ring_buff_size - 1)

            # configure trace size
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_TRACE_SIZE_HI,
                                        trace_size >> 32)
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_TRACE_SIZE_LO,
                                        trace_size & 0xFFFFFFFF)

            # reset write address pointer
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_ADDR_WR, 0x0)

            # make sure module initially is inactive
            status = yield axi_lite_reader.read(CPUREG_OFFSET_STATUS)
            if status & 0x3 != 0:
                raise cocotb.reset.TestFailure("module is active")

            # start the module
            yield axi_lite_writer.write(CPUREG_OFFSET_CTRL_START, 0x1)

            # wait a few cycles
            yield wait_n_cycles(dut.clk, 10)

            # start writing the ring buffer
            cocotb.fork(
                ring_buff_write(dut, ring_buff, trace, ring_buff_addr,
                                axi_lite_reader, axi_lite_writer))

            # start coroutine that checks dut output
            coroutine_chk_out = cocotb.fork(
                check_output(dut, trace, axis_reader))

            # wait a few cycles and make sure module is active
            yield wait_n_cycles(dut.clk, 10)
            status = yield axi_lite_reader.read(CPUREG_OFFSET_STATUS)
            if status & 0x1 == 0x0:
                raise cocotb.result.TestFailure("mem read not active")
            if status & 0x2 == 0x0:
                raise cocotb.result.TestFailure("packet assembly not active")

            # wait for output check to complete
            yield coroutine_chk_out.join()

            # wait a few cycles
            yield wait_n_cycles(dut.clk, 10)

            # make sure module is now inactive
            status = yield axi_lite_reader.read(CPUREG_OFFSET_STATUS)
            if status & 0x3 != 0x0:
                raise cocotb.result.TestFailure("module does not become " +
                                                "inactive")

            # clear the ring buffer contents
            ring_buff.clear()

    # close the trace file
    trace.close()
Esempio n. 22
0
    exit()

exe_path = argv[1]
input = abspath(str(argv[2]))
output = abspath(str(argv[3]))
period = int(argv[4])

if isdir(output) is True:
    rmtree(output)
mkdir(output)

print 'Starting file listing...'

# Get all files from the input directory and sort them
files = [
    File.from_path(join(input, f)) for f in listdir(input)
    if isfile(join(input, f)) and f != 'info.txt'
]
files.sort(File.sort)

print str(len(files)) + ' files listed.'

# Get the oldest and the newest file
oldest = floor_second_epoch(files[0].epoch)
newest = floor_second_epoch(files[-1].epoch)

print 'Start the extraction of file descriptors.'
i = 0
l = len(files)
for f in files:
    f.desc = get_desc(exe_path, f.path)
Esempio n. 23
0
def nt_gen_replay_mem_read_test(dut):
    """Test bench main function."""
    # open trace file
    trace = File("files/random.file")

    # get trace file size
    trace_size = trace.size()

    # trace file size must be a multiple of AXI data width
    if trace.size() % (AXI_BIT_WIDTH / 8) != 0:
        raise cocotb.result.TestFailure("invalid trace size")

    # calculate ring buffer sizes
    ring_buff_sizes = []
    for ring_buff_size in RING_BUFF_SIZES:
        # size of ring buffer is determined by multiplying the size factor by
        # the size of the trace
        ring_buff_size = int(ring_buff_size * trace_size)

        # make sure that the ring buffer size is multiple of AXI data width
        if ring_buff_size % (AXI_BIT_WIDTH / 8) != 0:
            ring_buff_size += AXI_BIT_WIDTH/8 - ring_buff_size % \
                             (AXI_BIT_WIDTH/8)
        ring_buff_sizes.append(ring_buff_size)

    # create a ring buffer memory (initially of size 0) and connect it to the
    # DUT
    ring_buff = Mem(0)
    ring_buff.connect(dut)

    # start the clock
    cocotb.fork(clk_gen(dut.clk, CLK_FREQ_MHZ))

    # deassert sw reset
    dut.rst_sw <= 0

    # initially module start is not triggered
    dut.ctrl_start_i <= 0

    # reset dut
    yield rstn(dut.clk, dut.rstn)

    # start the ring buffer memory main routine
    cocotb.fork(ring_buff.main())

    # wait some more clock cycles
    yield wait_n_cycles(dut.clk, 5)

    # randomly toggle fifo_prog_full input signal
    dut.fifo_prog_full_i <= 0
    cocotb.fork(toggle_signal(dut.clk, dut.fifo_prog_full_i))

    # iterate over all ring buffer sizes
    for i, ring_buff_size in enumerate(ring_buff_sizes):

        # set ring buffer size
        ring_buff.set_size(ring_buff_size)

        # iterate over all adderesses where ring buffer shall be located in
        # memory
        for j, ring_buff_addr in enumerate(RING_BUFF_ADDRS):

            # print status
            print("Test %d/%d" % (i * len(RING_BUFF_ADDRS) + j + 1,
                                  len(RING_BUFF_ADDRS) * len(RING_BUFF_SIZES)))

            # we have a total of 8 GByte of memory. Make sure the ring buffer
            # fits at the desired address
            if ring_buff_addr + ring_buff_size > 0x1FFFFFFFF:
                raise cocotb.result.TestFailure("ring buffer is too large")

            # to reduce the simulation memory footprint, provide the memory
            # module the first memory address that we actually care about
            ring_buff.set_offset(ring_buff_addr)

            # apply ring buffer memory location to dut
            dut.ctrl_mem_addr_hi_i <= ring_buff_addr >> 32
            dut.ctrl_mem_addr_lo_i <= ring_buff_addr & 0xFFFFFFFF

            # apply ring buffer address range to dut
            dut.ctrl_mem_range_i <= ring_buff_size - 1

            # apply trace size to dut
            dut.ctrl_trace_size_hi_i <= trace_size >> 32
            dut.ctrl_trace_size_lo_i <= trace_size & 0xFFFFFFFF

            # reset write address pointer
            dut.ctrl_addr_wr_i <= 0

            # start reading from the ring buffer
            dut.ctrl_start_i <= 1
            yield RisingEdge(dut.clk)
            dut.ctrl_start_i <= 0
            yield RisingEdge(dut.clk)

            # start writing the ring buffer
            cocotb.fork(ring_buff_write(dut, ring_buff, trace))

            # start checking dut output and wait until it completes
            yield cocotb.fork(check_output(dut, trace)).join()

            # clear the ring buffer contents
            ring_buff.clear()

    # close trace file
    trace.close()
Esempio n. 24
0
 def __del__(self):
     File.__del__(self)
Esempio n. 25
0
def nt_recv_capture_mem_write_test(dut):
    """Test bench main function."""
    # open file with random content
    try:
        f = File("files/random.file")
    except IOError:
        raise cocotb.result.TestFailure("Generate input data by calling " +
                                        "'./create_random.py' in 'files' " +
                                        "folder!")

    # file size must be a multiple of AXI data width
    if f.size() % (BIT_WIDTH_MEM_WRITE / 8) != 0:
        raise cocotb.result.TestFailure("invalid input data size")

    # create a ring buffer memory (initially of size 0) and connect it to the
    # DuT
    ring_buff = Mem(0)
    ring_buff.connect(dut)

    # start the clock
    cocotb.fork(clk_gen(dut.clk, CLK_FREQ_MHZ))

    # deassert sw reset
    dut.rst_sw <= 0

    # initially module is disabled
    dut.active_i <= 0

    # initially no FIFO flush
    dut.flush_i <= 0

    # reset DuT
    yield rstn(dut.clk, dut.rstn)

    # start the ring buffer memory main routine
    cocotb.fork(ring_buff.main())

    # wait some more clock cycles
    yield wait_n_cycles(dut.clk, 5)

    # iterate over all ring buffer sizes
    for i, ring_buff_size in enumerate(RING_BUFF_SIZES):

        # set ring buffer size
        ring_buff.set_size(ring_buff_size)

        # iterate over all adderesses where ring buffer shall be located in
        # memory
        for j, ring_buff_addr in enumerate(RING_BUFF_ADDRS):

            # print status
            print("Test %d/%d" % (i * len(RING_BUFF_ADDRS) + j + 1,
                                  len(RING_BUFF_ADDRS) * len(RING_BUFF_SIZES)))

            # we have a total of 8 GByte of memory. Make sure the ring buffer
            # fits at the desired address
            if ring_buff_addr + ring_buff_size > 0x1FFFFFFFF:
                raise cocotb.result.TestFailure("ring buffer is too large")

            # to reduce the simulation memory footprint, provide the memory
            # module the first memory address that we actually care about
            ring_buff.set_offset(ring_buff_addr)

            # apply ring buffer memory location to dut
            dut.mem_addr_hi_i <= ring_buff_addr >> 32
            dut.mem_addr_lo_i <= ring_buff_addr & 0xFFFFFFFF

            # apply ring buffer address range to dut
            dut.mem_range_i <= ring_buff_size - 1

            # reset read address pointer
            dut.addr_rd_i <= 0

            # start a couroutine that applies input data
            cocotb.fork(apply_input(dut, f))

            # wait a few clock cycles
            yield wait_n_cycles(dut.clk, 10)

            # start the ring buffer read coroutine and wait until it completes
            yield ring_buff_read(dut, ring_buff, f)

            # clear the ring buffer contents
            ring_buff.clear()

    # close file
    f.close()