Exemplo n.º 1
0
def bruteforce(self, args, n):
    in_zip = args.input
    if self.args.m:
        wl = sys.path[0] + ("/data/%d.txt" % n)
    elif n == 0:
        wl = self.args.wordlist
    print(pyzipper.AESZipFile(in_zip))
    found = False
    global password
    with pyzipper.AESZipFile(in_zip) as zf:
        with open(wl) as wordlist:
            for line in wordlist:
                password = line.strip('\n')
                if not found:
                    try:
                        zf.pwd = str.encode(password)
                        zf.extractall('./')
                        print("password found: %s" % password)
                        p = Process(args)
                        p.quit(found)
                        return
                    except Exception:
                        if args.q:
                            pass
                        else:
                            print(password)
Exemplo n.º 2
0
def zip_it(p, f, k):
    clear()
    if not k:
        try:
            if not os.path.exists(p + "\\_1"):
                os.mkdir(p + "\\_1")

            pwd = b'mvti1234mvti1234'

            for i in range(len(f)):
                print("Falta encriptar " + str(len(f) - i) + " ficheiros")
                foo = p + "\\_1\\" + f[i]
                with pyzipper.AESZipFile(foo,
                                         'w',
                                         compression=pyzipper.ZIP_LZMA) as zf:
                    zf.pwd = pwd
                    zf.setencryption(pyzipper.WZ_AES, nbits=128)
                    zf.write(p + "\\" + f[i],
                             os.path.basename(p + "\\_1\\" + f[i]))
            for i in range(len(f)):
                os.remove(p + "\\" + f[i])

            print("Todos os ficheiros foram encriptados")
        except Exception as ex:
            print(ex)
            pass
    else:
        count = 0
        while 1:
            try:
                if not os.path.exists(p + "\\_1"):
                    os.mkdir(p + "\\_1")

                pwd = b'mvti1234mvti1234'

                for i in range(len(f)):
                    count += 1
                    print("Foram encriptados " + str(count) + " ficheiros")
                    foo = p + "\\_1\\" + f[i]
                    with pyzipper.AESZipFile(
                            foo, 'w', compression=pyzipper.ZIP_LZMA) as zf:
                        zf.pwd = pwd
                        zf.setencryption(pyzipper.WZ_AES, nbits=128)
                        zf.write(p + "\\" + f[i],
                                 os.path.basename(p + "\\_1\\" + f[i]))
                for i in range(len(f)):
                    os.remove(p + "\\" + f[i])

                f = []

                for ff in listdir(p):
                    if isfile(join(p, ff)):
                        if ".zip" in ff or ".rar" in ff:
                            f.append(ff)

                time.sleep(15)
            except Exception as ex:
                print(ex)
                pass
Exemplo n.º 3
0
    def encrypt(self, inputtext):
        self.set_message("[color=E6FF00]Encrypting ...[/color]")
        password = inputtext.text
        base = os.path.basename(self.file_path)

        source = "%s" % (self.file_path)
        os.chdir(os.path.dirname(source))

        destination_file = "%s.zip" % (base)
        i = 1
        while os.path.exists(destination_file):
            destination_file = "%s_%s.zip" % (base, i)
            i += 1

        print("Source:%s" % (base))

        with pyzipper.AESZipFile(destination_file,
                                 'a',
                                 compression=pyzipper.ZIP_LZMA) as zf:

            zf.setpassword(str.encode(password))

            zf.setencryption(pyzipper.WZ_AES, nbits=128)

            if os.path.isdir(base):
                self.zipdir(base, zf)
            else:
                zf.write(base)

            zf.close()

        self.hide_all()
Exemplo n.º 4
0
def zip_extractor(password, start, count, ex_path):
    '''Function to extract zip file encrypted with AES'''

    flag = False
    try:
        with pyzipper.AESZipFile(path, 'r') as zf:
            try:
                zf.extractall(path=ex_path, pwd=bytes(password.encode('utf8')))
                print("\n\nFile decrypted successfully\nPassword found = {}".
                      format(password),
                      end='')
                flag = True
                return flag
            except:
                t = time.monotonic() - start
                t = convertf(t)
                print(
                    "\rElapsed time = {}:{}:{} Attempt = {} Password failed = {}                    "
                    .format(t[0], t[1], t[2], count, password),
                    end='',
                    flush=True)

    except (FileNotFoundError):
        print("\nNo such file or directory found")
        return True
    except Exception as e:
        print("\n{}".format(e))
        return True
Exemplo n.º 5
0
 def zip_directory(
         path,
         zip_name,
         password: str = "i_luv_sagiri") -> Optional[Tuple[str, bytes]]:
     if not os.path.exists(f"{path}/{zip_name}_密码{password}.zip"):
         if not os.path.exists(f"{path}/{zip_name}.zip"):
             with zipfile.ZipFile(Path(path) / f"{zip_name}.zip",
                                  mode='w') as zipf:
                 len_dir_path = len(path)
                 for root, _, files in os.walk(path):
                     for file in files:
                         if file[-3:] == "zip":
                             continue
                         file_path = os.path.join(root, file)
                         zipf.write(file_path, file_path[len_dir_path:])
         with pyzipper.AESZipFile(f"{path}/{zip_name}_密码{password}.zip",
                                  'w',
                                  compression=pyzipper.ZIP_LZMA,
                                  encryption=pyzipper.WZ_AES) as zf:
             zf.setpassword(password.encode())
             zf.setencryption(pyzipper.WZ_AES, nbits=128)
             zf.write(
                 Path(path) / f"{zip_name}.zip",
                 f"{zip_name}_密码{password}.zip")
     with open(f"{path}/{zip_name}_密码{password}.zip", "rb") as r:
         return f"{zip_name}_密码{password}", r.read()
Exemplo n.º 6
0
    def zip_email_data(self):
        """
        архивируем файлы из каталога store_dir
        и удалем каталог
        """
        try:
            zip_password = self.conf['zip']['password']
            archine_name = self.conf['zip']['archine_name']
            store_dir = self.conf['other']['tmp_folder']

            self.logger.info(f'Compressed  files to {archine_name}')
            with pyzipper.AESZipFile(archine_name,
                                     'w',
                                     compression=pyzipper.ZIP_LZMA) as z:
                z.setpassword(zip_password.encode())
                z.setencryption(pyzipper.WZ_AES, nbits=128)
                for root, dirs, files in os.walk(store_dir):
                    for file in files:
                        z.write(os.path.join(root, file))
                        #z.write(file)
            # удаляем папку с сохраненными файлами
            shutil.rmtree(os.path.join(os.getcwd(), store_dir))

        except:
            self.logger.exception('zip_email_data')
Exemplo n.º 7
0
async def _(req):
    global score
    check_flag()

    try:
        data = bytes.fromhex(req.query['x'])
        assert 16 < len(data) <= MAX_SIZE
        assert len(data) % 16 == 0
    except Exception:
        raise web.HTTPBadRequest()

    aes = AES.new(key, AES.MODE_CBC, data[:16])
    ptxt = aes.decrypt(data[16:]).strip(b'\0')

    score += 1
    if len(history) < MAX_HIST:
        history.append([0, data.hex()])

    out = io.BytesIO()
    with pyzipper.AESZipFile(out,
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(key)
        zf.writestr('flag', ptxt)

    return web.Response(
        headers={'Content-Disposition': 'Attachment; filename=flag.zip'},
        body=out.getvalue())
Exemplo n.º 8
0
def encrypt_and_compress_zip_file(filename, secret_password, encrypted_filenames):
    with pyzipper.AESZipFile(
            filename, 'w', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES
    ) as zf:
        zf.setpassword(secret_password)
        for encrypted_filename in encrypted_filenames:
            with open(encrypted_filename, 'rb') as f:
                zf.writestr(os.path.basename(encrypted_filename), f.read())
Exemplo n.º 9
0
def run():
    logger = Util.configure_log(__name__)
    total = 0
    for sample in Util.get_sample_list():
        if total % 100 == 0:
            time.sleep(5)
        try:
            with pyzipper.AESZipFile(sample) as zf:
                zf.pwd = 'infected'
        except pyzipper.zipfile.BadZipFile:
            if os.path.getsize(sample) == 15:  # 'Invalid Hash...' File
                logger.debug(
                    '{} file marked as "Invalid Hash...", deleted.'.format(
                        sample))
                os.remove(sample)
            elif os.path.getsize(sample) == 409:  # Proxy error file.
                logger.debug(
                    '{} file marked as "Proxy error", deleted.'.format(sample))
                os.remove(sample)
            elif os.path.getsize(sample) == 0:  # General error
                logger.debug(
                    '{} file marked as Zero size, deleted.'.format(sample))
                os.remove(sample)
            else:
                file = open(sample, 'r', encoding="latin1")
                header = file.read(128)  # Read 16 bytes
                header = str(header).lower()
                if '!doctype' in header or '<html' in header or '<!--':
                    logger.debug(
                        '{} file marked as "HTML file", deleted.'.format(
                            sample))
                    os.remove(sample)
                elif 'this program cannot be run in dos mode' in header:
                    # uncompressed exe
                    logger.debug('Compresing {} file.'.format(sample))
                    new_name = sample.split('.')[0]
                    new_name = '{}.exe'.format(new_name)
                    os.rename(sample, new_name)
                    with pyzipper.AESZipFile(sample,
                                             'w',
                                             encryption=pyzipper.WZ_AES) as zf:
                        zf.setpassword(b'infected')
                        zf.write(sample, new_name)
                    os.remove(new_name)
            total += 1
    logger.info("Processed {} files. Stopping.".format(total))
Exemplo n.º 10
0
def Unpack_zipfile(filename):
    try:
        #Unpack_zipfile
        file_path = os.path.join(FOL_PATH, filename)
        with pyzipper.AESZipFile(file_path) as zf:
            my_secrets = zf.extractall(UNZIP_PATH)
    except Exception as e:
        pass
def zip_encrypt(filenames, outzip, passwd):
    with pyzipper.AESZipFile('new_test.zip',
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(passwd)
        for filename in filenames:
            zf.write(filename)
Exemplo n.º 12
0
def zipFiles(filePathList=None,
             outputZipFilePath="",
             keepRelativeFolderStructure=True,
             password="",
             progressHandler=None):
    """
    If a progressHandler is specified, the progress will be updated with 
    progressHandler(progress, currentFileIndex, totalNumberOfFiles) where progress is a float in [0,1].
    """
    if filePathList == None:
        filePathList = []

    # Support single files:
    if not isinstance(filePathList, list):
        filePathList = [filePathList]

    if progressHandler:
        numberOfFiles = len(filePathList)
        progressHandler(0.0, 0, numberOfFiles)
        fileNumber = 0

    relFolder = Path(os.path.commonpath(filePathList)).parent

    if password == "" or not pwEncryptionSupported:
        with ZipFile(outputZipFilePath, 'w') as zipFile:
            for filePath in filePathList:
                if keepRelativeFolderStructure:
                    zipFile.write(filePath,
                                  os.path.relpath(filePath, relFolder))
                else:
                    zipFile.write(filePath, os.path.basename(filePath))

                if progressHandler:
                    fileNumber += 1
                    progressHandler(
                        float(fileNumber) / numberOfFiles, fileNumber,
                        numberOfFiles)
    else:
        with pyzipper.AESZipFile(outputZipFilePath,
                                 'w',
                                 compression=pyzipper.ZIP_LZMA,
                                 encryption=pyzipper.WZ_AES) as zipFile:
            zipFile.pwd = password
            for filePath in filePathList:
                if keepRelativeFolderStructure:
                    zipFile.write(filePath,
                                  os.path.relpath(filePath, relFolder))
                else:
                    zipFile.write(filePath, os.path.basename(filePath))

                if progressHandler:
                    fileNumber += 1
                    progressHandler(
                        float(fileNumber) / numberOfFiles, fileNumber,
                        numberOfFiles)

    return outputZipFilePath
Exemplo n.º 13
0
 def unzip_file(self, file_path):
     dir = os.path.dirname(os.path.abspath(file_path))
     zf = pyzipper.AESZipFile(file_path)
     try:
         zf.extractall(path=dir)
     except RuntimeError as e:
         if "is encrypted" in str(e):
             self.set_file(file_path)
             self.show_password_to_unzip()
Exemplo n.º 14
0
def save_key_to_file(main_haslo):
    klucz = create_key()
    haslo_to_file = main_haslo
    with pyzipper.AESZipFile('secret.zip',
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(haslo_to_file)
        zf.writestr('klucz.txt', klucz)
Exemplo n.º 15
0
def encrypted_zip(files, out_path, password):
    with pyz.AESZipFile(out_path,
                        'w',
                        compression=pyz.ZIP_LZMA,
                        encryption=pyz.WZ_AES) as z:
        z.setpassword(password)
        for f in files:
            z.write(f, f.name)
    return out_path
def decrypt():
    passnum = decryptarchivename.strip(".zip")
    passarr = passnum.split('/')
    passarr = passarr[-1]
    with open(decryptpasswfilname, "r") as f:
        password_dict = json.load(f)
    zippassword = password_dict[passarr].encode()
    with pyzipper.AESZipFile(decryptarchivename) as f:
        f.pwd = zippassword
        f.extractall(".")
Exemplo n.º 17
0
 def encrypt(self, filehash, filename, filepath):
     filename_encrypted = "{}_{}".format(filehash, filename)
     with pyzipper.AESZipFile("{}.zip".format(filename_encrypted),
                              'w',
                              compression=pyzipper.ZIP_LZMA,
                              encryption=pyzipper.WZ_AES) as zf:
         zf.pwd = self.zip_password
         # zf.writestr(filepath, "What ever you do, don't tell anyone!")
         zf.write(filepath)
     return filename_encrypted
Exemplo n.º 18
0
def get_sample(hash):
    headers = { 'API-KEY': KEY } 
    data = { 'query': 'get_file', 'sha256_hash': hash }
    response = requests.post('https://mb-api.abuse.ch/api/v1/', data=data, timeout=15, headers=headers, allow_redirects=True)
    with open(SAMPLES_PATH+hash+'.zip', 'wb') as f:
        f.write(response.content)
        print("[+] Sample downloaded successfully")
    with pyzipper.AESZipFile(SAMPLES_PATH+hash+'.zip') as zf:
        zf.extractall(path=SAMPLES_PATH, pwd=ZIP_PASSWORD)
        print("[+] Sample unpacked successfully")
def encrypt():
    passnum = random.randint(0,99)
    with open(passfilname, "r") as f:
        password_dict = json.load(f)
    zipname = str(passnum) + ".zip"
    zippassword = password_dict[str(passnum)].encode()
    filename_nodirs = sendfilname.split("/")[-1]
    with pyzipper.AESZipFile(zipname, 'w', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(zippassword)
        zf.write(sendfilname, filename_nodirs)
    return passnum
Exemplo n.º 20
0
def unzip_file(zip_path,dir_path):
    try:
        with ZipFile(zip_path,'r') as zf:
            zf.extractall(path=dir_path)
    except RuntimeError:
        print('AES Encrypted zip file. Need pyzipper to continue.\n')
        shutil.rmtree(dir_path, ignore_errors=True) #delete old dir
        import pyzipper
        with pyzipper.AESZipFile(zip_path,'r',encryption=pyzipper.WZ_AES) as zf:
            pwd=getpass.getpass(prompt='Archive is password protected. Please enter the password to continue \n')
            zf.extractall(path=dir_path,pwd=pwd.encode())
Exemplo n.º 21
0
def init(input, prefix, alphabet, minlength, maxlength):
    fzipAES = pyzipper.AESZipFile(input)
    print('[x] CRACKING')
    start = time.time()
    result = crackit(fzipAES, prefix, alphabet, minlength, maxlength)
    end = time.time()
    done = end - start
    print('[x] Done in ' + str(done) + ' seconds')
    if (result == None):
        print("[-] No password found :(")
    else:
        print("[+] Password found: " + result)
Exemplo n.º 22
0
def download():

    dirname = os.getcwd()
    with pyzipper.AESZipFile('arquivo.zip', 'w',
                             compression=pyzipper.ZIP_LZMA) as zf:
        zf.pwd = b'5DBE7D079067809BB06F7C80DE78ECB9D914F5735265148CD704F85353FC0B5114EBBFC960539CD3F430E7B12EB3FDC261726BB756BAB9658C6DB6A302913DF1'
        zf.setencryption(pyzipper.WZ_AES, nbits=128)
        for folderName, subfolders, filenames in os.walk(
                os.path.join(dirname, "lib")):
            for filename in filenames:
                zf.write(os.path.join("lib", filename))

    return send_file(dirname + "/arquivo.zip", as_attachment=True)
def download_seguro():
    file = requests.get('http://localhost:5000')
    arquivo_nome = 'libs/arquivo-seguro.zip'
    with open(arquivo_nome, 'wb') as f:
        f.write(file.content)

    try:
        with pyzipper.AESZipFile(arquivo_nome) as zf:
            zf.pwd = b'5DBE7D079067809BB06F7C80DE78ECB9D914F5735265148CD704F85353FC0B5114EBBFC960539CD3F430E7B12EB3FDC261726BB756BAB9658C6DB6A302913DF1'
            zf.extractall()
            return 'Feito o download do arquivo de forma segura'
    except:
        return 'Cuidado não foi possível descompactar o arquivo de forma segura'
def extract( password ):
  """
  Extract the dataset files from ZIP file.
  """
  bytePwd = password.encode('utf-8')
  print("Extracting...")

  with pyzipper.AESZipFile(datasetPath) as f:
      f.extractall(pwd=bytePwd)

  print("Complete!")

  return
Exemplo n.º 25
0
def backup(ctx, password, open_file=True):
    """
    \b
    Create backup for the following files:
    1. list of saplogon systems (SAPUILandscape.xml)
    2. database
    3. encryption keys (private and public)
    4. sap_config.ini
    """

    #  Paths to SAPUILandscape.xml: https://launchpad.support.sap.com/#/notes/2075150

    pwd = str.encode(password)

    config_ini_path = ctx.obj.config.config_file_path
    saplogon_ini_path = os.path.join(
        os.path.expandvars(r'%APPDATA%\SAP\Common'), 'SAPUILandscape.xml')

    back_file_name = f'backup_{datetime.now().strftime("%Y.%m.%d-%I.%M.%S")}.zip'
    back_path = os.path.join(utilities.path(), back_file_name)
    with pyzipper.AESZipFile(back_path,
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        zf.setpassword(pwd)
        zf.write(ctx.obj.config.db_path,
                 os.path.basename(ctx.obj.config.db_path))
        zf.write(ctx.obj.config.public_key_path,
                 os.path.basename(ctx.obj.config.public_key_path))
        zf.write(ctx.obj.config.private_key_path,
                 os.path.basename(ctx.obj.config.private_key_path))
        zf.write(config_ini_path, os.path.basename(config_ini_path))
        zf.write(saplogon_ini_path, os.path.basename(saplogon_ini_path))

        comment = r""" 
            1. Place 'SAPUILandscape.xml' to '%APPDATA%\SAP\Common' folder 
            2. Place 'sap_config.ini' to 'c:\Users\<USERNAME>\AppData\Local\SAP' folder
            3. Other files - according to sap_config.ini paths
            Or you can place whener you want, just enter new paths to sap_config.ini
            !!! And remember that files 'database.db' and 'private_key.txt' must be stored in secure place"""

        zf.comment = comment.encode()

    if os.path.exists(back_path):
        click.echo(
            click.style('Backup succesfully created',
                        **utilities.color_success))
        if open_file:
            click.launch(url=back_path, locate=True)
    else:
        click.echo('Backup creation failed')
Exemplo n.º 26
0
    def bazaar_download(self,
                        hash: str,
                        unzip: bool = True,
                        info: bool = False):
        """Downloads malware hash's information

        Args:
            hash (str): Hash value to download
            unzip (bool, optional): Whether to unzip the file returned
            info (bool, optional): Whether to get information as JSON

        Returns:
            dict OR str OR list: Request response, name of zip file written to, or list of names of files unpacked from zip
        """
        if (unzip == True and info == True):
            raise ValueError(
                "Sorry, please select unzip or information display.")
        self.check_sha256(hash)

        ZIP_PASSWORD = "******"

        if (info == False):
            data = {
                'query': 'get_file',
                'sha256_hash': hash,
            }

            response = self.session.post(self.url,
                                         data=data,
                                         timeout=15,
                                         allow_redirects=True)
            open(hash + '.zip', 'wb').write(response.content)

            if (unzip == True):
                with pyzipper.AESZipFile(hash + ".zip") as zf:
                    zf.pwd = ZIP_PASSWORD
                    _ = zf.extractall(".")
                    print("Sample \"" + hash + "\" downloaded and unpacked.")
                    return zf.namelist()
            else:
                print("Sample \"" + hash + "\" downloaded.")
                return hash + '.zip'
        else:
            data = {
                'query': 'get_info',
                'hash': hash,
            }
            print(data)
            response = self.session.post(self.url, data=data, timeout=15)
            return response.json()
Exemplo n.º 27
0
    def download(self, sha256):
        response = self.session.post(self.base_url,
                                     data={
                                         'query': 'get_file',
                                         'sha256_hash': sha256,
                                     })
        response.raise_for_status()

        data = io.BytesIO()
        data.write(response.content)
        zip_file = pyzipper.AESZipFile(data)
        zip_file.setpassword(b'infected')
        for name in zip_file.namelist():
            return zip_file.read(name)
Exemplo n.º 28
0
    def download_unzip(self, sha256):
        """
        Download and unzip a sample from MalwareBazaar.

        sha256: a str representing the sample's sha256.
        returns: a bytes object containing the contents of the file
        """
        data = {"query": "get_file", "sha256_hash": sha256}
        resp = requests.post(self.api_url, data=data)
        zip_contents = resp.content
        zip_obj = io.BytesIO(zip_contents)
        zip_file = pyzipper.AESZipFile(zip_obj)
        zip_file.setpassword(b"infected")
        file_name = zip_file.namelist()[0]
        return zip_file.read(file_name)
Exemplo n.º 29
0
def zipfile(filetuple):
    filename = filetuple[0]
    zipname = filetuple[1]
    with open(filename, 'rb') as f:
        filedata = f.read()
    print('\033[1;33mZipping', filename, '->', zipname + '\033[0m')
    with pyzipper.AESZipFile(zipname,
                             'w',
                             compression=pyzipper.ZIP_LZMA,
                             encryption=pyzipper.WZ_AES) as zf:
        password = bytes(makepassword(), 'utf-8')
        zf.setpassword(password)
        zf.setencryption(pyzipper.WZ_AES, nbits=256)
        zf.writestr(filename, filedata)
    return zipname, password.decode('utf-8')
Exemplo n.º 30
0
    def __create_zip_object(zip_filepath: str, mode: str, password: bytes = None,
                            is_aes_encrypted: bool = False) -> pyzipper.ZipFile:
        if password is None or len(password) == 0:
            return pyzipper.ZipFile(zip_filepath, mode)
        else:
            if is_aes_encrypted:
                zip_object = pyzipper.AESZipFile(zip_filepath, mode=mode)

                zip_object.setpassword(password)
                zip_object.setencryption(pyzipper.WZ_AES)
                return zip_object
            else:
                zip_object = pyzipper.ZipFile(zip_filepath, mode=mode)
                zip_object.setpassword(password)
                return zip_object