Beispiel #1
0
def read_protected_excel(fname: Union[str, Path, PathLike], pwd: str,
                         **kwargs) -> pd.DataFrame:
    """Load a protected Excel file into a pandas.read_excel(..., engine='openpyxl', ...)."""
    import msoffcrypto  # Inner import to avoid imposing dependency to non-users.

    decrypted = BytesIO()
    p = pathify(fname)
    with p.open("rb") as f:
        file = msoffcrypto.OfficeFile(f)
        file.load_key(password=pwd)
        file.decrypt(decrypted)

    if ("engine" in kwargs) and (kwargs["engine"] != "openpyxl"):
        warnings.warn("openpyxl engine is recommended.")

    kwargs["engine"] = "openpyxl"
    return pd.read_excel(decrypted, **kwargs)
Beispiel #2
0
def OFFICE(off_path,pwd_path,out_path):
    print ("try")
    file = msoffcrypto.OfficeFile(open(off_path, "rb"))
    passFile = open(pwd_path)

    for line in passFile.readlines():
        pwd1 = line.strip('\n')
        #file.load_key(password = pwd1)

        try:
            file.load_key(password = pwd1)
            file.decrypt(open(out_path, "wb"))
            print(pwd1)
            break
        except:
            pass
    print ("进程结束")
Beispiel #3
0
    def scan(self, data, file, options, expire_at):

        jtr_path = options.get('jtr_path', '/jtr/')
        tmp_directory = options.get('tmp_file_directory', '/tmp/')
        password_file = options.get('password_file',
                                    '/etc/strelka/passwords.dat')
        log_extracted_pws = options.get('log_pws', False)
        scanner_timeout = options.get('scanner_timeout', 150)
        brute = options.get('brute_force', False)
        max_length = options.get('max_length', 5)

        with io.BytesIO(data) as doc_io:

            msoff_doc = msoffcrypto.OfficeFile(doc_io)
            output_doc = io.BytesIO()
            if extracted_pw := crack_word(self,
                                          data,
                                          jtr_path,
                                          tmp_directory,
                                          brute=brute,
                                          scanner_timeout=scanner_timeout,
                                          max_length=max_length,
                                          password_file=password_file):
                if log_extracted_pws:
                    self.event['cracked_password'] = extracted_pw
                try:
                    msoff_doc.load_key(password=extracted_pw.decode('utf-8'))
                    msoff_doc.decrypt(output_doc)
                    output_doc.seek(0)
                    extract_data = output_doc.read()
                    output_doc.seek(0)
                    extract_file = strelka.File(source=self.name, )

                    for c in strelka.chunk_string(extract_data):
                        self.upload_to_coordinator(
                            extract_file.pointer,
                            c,
                            expire_at,
                        )

                    self.files.append(extract_file)
                except:
                    self.flags.append(
                        'Could not decrypt document with recovered password')

            else:
Beispiel #4
0
    def test_known_output(self):
        """See module doc."""
        for in_name, out_name in EXAMPLE_FILES:
            input_path = pjoin(TEST_BASE_DIR, INPUT_DIR, in_name)
            expect_path = pjoin(TEST_BASE_DIR, OUTPUT_DIR, out_name)

            # now run the relevant parts of __main__.main:
            with open(input_path, 'rb') as input_handle:
                file = msoffcrypto.OfficeFile(input_handle)
                file.load_key(password=PASSWORD)

                out_desc = None
                out_path = None
                output = []
                try:
                    # create temp file for output of decryption function
                    out_desc, out_path = mkstemp(prefix='msoffcrypto-test-',
                                                 suffix='.txt',
                                                 text=True)
                    with os.fdopen(out_desc, 'wb') as out_handle:
                        out_desc = None  # out_handle now owns this

                        # run decryption, capture output
                        print('decrypting {}'.format(in_name))
                        file.decrypt(out_handle)

                    # read extracted output file into memory
                    with open(expect_path, 'rb') as reader:
                        output = reader.read()
                finally:
                    # ensure we do not leak temp files. Always close & remove
                    if out_desc:
                        os.close(out_desc)
                    if out_path and isfile(out_path):
                        os.unlink(out_path)

            # read output file into memory
            with open(expect_path, 'rb') as reader:
                expect = reader.read()

            # compare:
            print('comparing output to {}'.format(out_name))
            similarity = SequenceMatcher(None, expect, output).ratio()
            self.assertGreater(similarity, 0.99)
Beispiel #5
0
def break_password(filepath, filename, filetype):
    print(filetype)
    file = os.path.join(filepath, filename)
    print(file)
    passfile = open(r'C:\Users\yangyi\Desktop\网络攻防\password1.txt')
    if filetype == 'pdf':
        f = PyPDF4.PdfFileReader(open(file, 'rb'))
        for line in passfile.readlines():
            password = line.strip('\n')
            passwords = password.split()
            for i in range(4):
                extractfilepdf(f, passwords[i])
    else:
        f = msoffcrypto.OfficeFile(open(file, "rb"))
        for line in passfile.readlines():
            password = line.strip('\n')
            passwords = password.split()
            for i in range(4):
                extractfile(f, passwords[i])
Beispiel #6
0
def officecrack(spath,q):
    ofile = msoffcrypto.OfficeFile(open(spath, "rb")) #打开文件
    p,f = os.path.split(spath)
    new_name='new_'+f
    new_path=os.path.join(p,new_name)  #新文件路径
    global wover
    while wover!=True:
        if not q.empty():
            passwd = q.get()
            # print(passwd)
            try:
                ofile.load_key(password=passwd)
                ofile.decrypt(open(new_path, "wb"))
                print ('[+]pasword =='+passwd)
                q.queue.clear()
                wover = True
                exit(0)
            except Exception as e:
                pass
Beispiel #7
0
def unlock_excel_to_new_file(input_file_path, output_dir='./'):
    """
    解锁上锁的 EXCEL 文件,使用魔法密码 “VelvetSweatshop” 可以解决 EXCEL 可以打开,但是命令行打开却提示上锁的情况。
    本函数读入一个上锁 EXCEL 文件,输出解锁后的文件。
    :param input_file_path:
    :param output_dir:
    :return:
    """

    wb_msoffcrypto_file = msoffcrypto.OfficeFile(open(input_file_path, 'rb'))
    wb_msoffcrypto_file.load_key(password='******')

    assert input_file_path.endswith('.xls')
    wb_unencrypted_filename = input_file_path

    with open(output_dir+os.path.basename(wb_unencrypted_filename), 'wb') as tmp_wb_unencrypted_file:
        wb_msoffcrypto_file.decrypt(tmp_wb_unencrypted_file)

    return output_dir+os.path.basename(wb_unencrypted_filename)
def decrypt_docx(file_docx):
    chars = string.ascii_letters + string.digits
    attempts = 0
    print("Searching for password!\nThis may take long time...")  # print that you can go shopping :D
    for plen in range(1, 6):  # already the same
        for guess in itertools.product(chars, repeat=plen):
            attempts += 1
            guess = ''.join(guess)
            # print(guess,attempts)                                          #Debug
            try:
                file = msoffcrypto.OfficeFile(open(file_docx, "rb"))  # try start msoffcrypto-tool as OfficeFile with
                # file-name and read-access only
                file.load_key(password=guess)  # if password required, take the generated
                file.decrypt(open("decrypted.docx",
                                  "wb"))  # if password correct, open new file with write-access and copy content in it
                print("[DOCX, XLSX BRUTE-FORCE]: found password! password: {} with {} attempts".format(guess, attempts))
                return True
            except:
                # print(str(attempts)+"not correct!")                        #Debug
                continue  # otherwise continue with next password
Beispiel #9
0
def pull_info_from_xlsx(subjects, session_date_label):
    password = input("Enter the password for the Subject Excel Sheet: ")

    file = msoffcrypto.OfficeFile(
        open("/mnt/cifs/rdss/rdss_kahwang/subject_info.xlsx", "rb"))

    file.load_key(password=password)

    decrypted = io.BytesIO()
    file.decrypt(decrypted)

    df = pd.read_excel(decrypted,
                       sheet_name="Subject Info Sheet").set_index("Subject #")
    for sub in subjects:
        row = df.loc[int(sub.name)]
        sub.sex = row["Sex"]
        sub.interview_date = row[session_date_label]
        time_difference = relativedelta(sub.interview_date, row["DOB (age)"])
        sub.age = time_difference.years + time_difference.months / 12
        print(sub.age)
Beispiel #10
0
def unlock():
    for file in BASE_DIR.iterdir():
        # Excelファイルだけ対象
        if not file.is_file() or file.suffix not in ['.xlsx', '.xls']:
            continue

        with file.open(mode='rb') as locked:
            # xlsxファイルの場合、読み取りパスワード無しのファイルは例外が発生する
            # is_encrypted()には以下の記載がある
            #
            # https://github.com/nolze/msoffcrypto-tool/blob/v4.6.3/msoffcrypto/format/ooxml.py#L143
            # def is_encrypted(self):
            #     # olefile cannot process non password protected ooxml files.
            #     # Hence if it has reached here it must be password protected.
            #     return True
            try:
                office_file = msoffcrypto.OfficeFile(locked)
            except OSError:
                if file.suffix == '.xlsx':
                    continue
                raise

            # 読み取りパスワードが設定されているかをチェック(xlsxはチェックできないので、xls向け)
            if not office_file.is_encrypted():
                continue

            # パスワードをセット
            # xlsでパスワードが設定されていない場合、load_key()時にエラーが出るため、事前にチェックが必要
            #   File "python3.6/site-packages/msoffcrypto/format/xls97.py", line 479, in load_key
            #     # Skip to FilePass; TODO: Raise exception if not encrypted
            #     num, size = workbook.skip_to(recordNameNum['FilePass'])
            #   File "python3.6/site-packages/msoffcrypto/format/xls97.py", line 428, in skip_to
            #     raise Exception("Record not found")
            # Exception: Record not found
            office_file.load_key(password=PASSWORD)

            # 読み取りパスワード解除後のファイルは、拡張子の前に '_unlocked' を付けて保存する
            unlocked_file = BASE_DIR.joinpath(f'{file.stem}_unlocked{file.suffix}')
            with unlocked_file.open(mode='wb') as unlocked:
                # パスワードを解除
                office_file.decrypt(unlocked)
Beispiel #11
0
def handle_protected_workbook(wb_filepath):
    try:
        xlrd.open_workbook(wb_filepath)
    except xlrd.biffh.XLRDError as e:
        if e.args[0] == "Workbook is encrypted":
            # Try and unencrypt workbook with magic password
            wb_msoffcrypto_file = msoffcrypto.OfficeFile(
                open(wb_filepath, 'rb'))
            try:
                # Yes, this is actually a thing
                # https://nakedsecurity.sophos.com/2013/04/11/password-excel-velvet-sweatshop/
                wb_msoffcrypto_file.load_key(password='******')
            except AssertionError as e:
                if e.args[0] == "Failed to verify password":
                    # Encrypted with some other password
                    raise  # or do something else
                else:
                    # Some other error occurred
                    raise
            except:
                # Some other error occurred
                raise
            else:
                # Magic Excel password worked
                assert wb_filepath.endswith('.xls')
                wb_unencrypted_filename = wb_filepath[:-(
                    len('.xls'))] + '__unencrypted.xls'
                wb_msoffcrypto_file.decrypt(open(wb_unencrypted_filename,
                                                 'wb'))
                # --- Do something with the file ---
                # return true to indicate file was touched
                return True  # or do something else
        else:
            # some other xlrd error occurred.
            return False  # or do something else
    except:
        # some non-xlrd error occurred.
        return False  # or do something else
Beispiel #12
0
#!/usr/bin/python
# pip install msoffcrypto-tool
#
# By Sql3t0
import sys
import msoffcrypto

if len(sys.argv) < 3:
    print "[-] Usage : "
    print "          : python script.py 'encrypted_word_file' 'wordlist_file'"
else:
    file = msoffcrypto.OfficeFile(open(sys.argv[1], "rb"))

    for p in open(sys.argv[2]):
        sys.stdout.write("\r[>] Pass: "******"	")
        try:
            # Use password
            file.load_key(password=p.replace('\n', ''))
            file.decrypt(open("decrypted_" + sys.argv[1], "wb"))
            sys.stdout.write("\r[+] PASSWD FOUND : " + str(p))
            break
        except Exception as e:
            pass

    print '[.] END !'
Beispiel #13
0
#
# Created by Berke Akyıldız on 05/July/2019
#
import msoffcrypto

file = msoffcrypto.OfficeFile(
    open("C:\\Users\\MONSTER\\Desktop\\asd.docx", "rb"))

# Use password
file.load_key(password="******")

# Use private key
# file.load_key(private_key=open("priv.pem", "rb"))
# Use intermediate key (secretKey)
# file.load_key(secret_key=binascii.unhexlify("AE8C36E68B4BB9EA46E5544A5FDB6693875B2FDE1507CBC65C8BCF99E25C2562"))

file.decrypt(open("C:\\Users\\MONSTER\\Desktop\\decrypted.docx", "wb"))
Beispiel #14
0
 def _validate_ole_file(filepath):
     with open(filepath, "rb") as f:
         officefile = msoffcrypto.OfficeFile(f)
         return officefile.is_encrypted()
Beispiel #15
0
def decrypt(filename, passwords=None, **temp_file_args):
    """
    Try to decrypt an encrypted file

    This function tries to decrypt the given file using a given set of
    passwords. If no password is given, tries the standard password for write
    protection. Creates a file with decrypted data whose file name is returned.
    If the decryption fails, None is returned.

    :param str filename: path to an ole file on disc
    :param passwords: list/set/tuple/... of passwords or a single password or
                      None
    :type passwords: iterable or str or None
    :param temp_file_args: arguments for :py:func:`tempfile.mkstemp` e.g.,
                           `dirname` or `prefix`. `suffix` will default to
                           suffix of input `filename`, `prefix` defaults to
                           `oletools-decrypt-`; `text` will be ignored
    :returns: name of the decrypted temporary file (type str) or `None`
    :raises: :py:class:`ImportError` if :py:mod:`msoffcrypto-tools` not found
    :raises: :py:class:`ValueError` if the given file is not encrypted
    """
    _check_msoffcrypto()

    # normalize password so we always have a list/tuple
    if isinstance(passwords, str):
        passwords = (passwords, )
    elif not passwords:
        passwords = DEFAULT_PASSWORDS

    # check temp file args
    if 'prefix' not in temp_file_args:
        temp_file_args['prefix'] = 'oletools-decrypt-'
    if 'suffix' not in temp_file_args:
        temp_file_args['suffix'] = splitext(filename)[1]
    temp_file_args['text'] = False

    decrypt_file = None
    with open(filename, 'rb') as reader:
        try:
            crypto_file = msoffcrypto.OfficeFile(reader)
        except Exception as exc:   # e.g. ppt, not yet supported by msoffcrypto
            if 'Unrecognized file format' in str(exc):
                log.debug('Caught exception', exc_info=True)

                # raise different exception without stack trace of original exc
                if sys.version_info.major == 2:
                    raise UnsupportedEncryptionError(filename)
                else:
                    # this is a syntax error in python 2, so wrap it in exec()
                    exec('raise UnsupportedEncryptionError(filename) from None')
            else:
                raise
        if not crypto_file.is_encrypted():
            raise ValueError('Given input file {} is not encrypted!'
                             .format(filename))

        for password in passwords:
            log.debug('Trying to decrypt with password {!r}'.format(password))
            write_descriptor = None
            write_handle = None
            decrypt_file = None
            try:
                crypto_file.load_key(password=password)

                # create temp file
                write_descriptor, decrypt_file = mkstemp(**temp_file_args)
                write_handle = os.fdopen(write_descriptor, 'wb')
                write_descriptor = None      # is now handled via write_handle
                crypto_file.decrypt(write_handle)

                # decryption was successfull; clean up and return
                write_handle.close()
                write_handle = None
                break
            except Exception:
                log.debug('Failed to decrypt', exc_info=True)

                # error-clean up: close everything and del temp file
                if write_handle:
                    write_handle.close()
                elif write_descriptor:
                    os.close(write_descriptor)
                if decrypt_file and isfile(decrypt_file):
                    os.unlink(decrypt_file)
                decrypt_file = None
    # if we reach this, all passwords were tried without success
    log.debug('All passwords failed')
    return decrypt_file
Beispiel #16
0
def main():
    '''

	主函数

	'''

    parser = optparse.OptionParser("usage%prog " +
                                   "-f <zipfile> -d <dictionary>")

    parser.add_option('-f',
                      dest='zname',
                      type='string',
                      help='specify zip file ')

    parser.add_option('-d',
                      dest='dname',
                      type='string',
                      help='specify dictionary file')

    (options, args) = parser.parse_args()

    if (options.zname == None) | (options.dname == None):

        print(parser.usage)

        exit(0)

    else:

        zname = options.zname

        dname = options.dname

    print(zname, type(zname))

    msfile = msoffcrypto.OfficeFile(open(zname, "rb"))  #实例化类

    passFile = open(dname)  #打开字典文件

    room = passFile.readlines()

    threads_num = 8  #确认线程数

    arr = []

    for i in range(threads_num):

        tag = int(len(room) / threads_num)

        if i != threads_num - 1:

            arr = (room[i * tag:(i + 1) * tag])

        else:

            arr = (room[i * tag:])
        is_begin = True

        while is_begin:
            try:
                #print('thread '+str(i)+'is start')
                t = Thread(target=extractFile, args=(msfile, arr))

                t.start()
                #t.join()
                is_begin = False
                time.sleep(0.1)
            except:

                is_begin = True
Beispiel #17
0
def exec(path_tutor, path_admin, path_template, year, month, output_folder,
         password):
    # 講師情報変更時のみでOK
    # 講師情報を取得

    ###################################################################################################

    # 管理票を取得
    with open(path_admin, "rb") as f, tempfile.TemporaryFile() as tf:
        ms_file = msoffcrypto.OfficeFile(f)
        ms_file.load_key(password=password)
        ms_file.decrypt(tf)
        wb = openpyxl.load_workbook(tf, data_only=True)

    # 管理票から対象シートを取得
    trans_table = str.maketrans({
        "0": "0",
        "1": "1",
        "2": "2",
        "3": "3",
        "4": "4",
        "5": "5",
        "6": "6",
        "7": "7",
        "8": "8",
        "9": "9"
    })
    sheetnames = []
    for sheetname in wb.sheetnames:
        fixed_name = sheetname.translate(trans_table)
        idx = fixed_name.find("月")
        if idx == -1:
            continue
        if fixed_name[:idx] == str(month):
            sheetnames.append(sheetname)

    # 対象シートから出勤日を取得
    class_times = {
        "2:00-3:20": 0,
        "3:30-4:50": 1,
        "5:00-6:20": 2,
        "6:30-7:50": 3,
        "8:00-9:20": 4
    }
    for sheetname in sheetnames:
        ws = wb[sheetname]
        MAX_ROW = 100
        MAX_COLUMN = 30
        for i in range(1, MAX_ROW):
            head_cell = ws.cell(row=i, column=2).value
            if (type(head_cell) == int) or (head_cell == None):
                if type(head_cell) == int:
                    date = excel_date(head_cell)
                    #############################
                    # 異なる月の日付があったら警告#
                    #############################
                    if date.month != month:
                        break
                    day = date.day - 1  # 0 ~ 30
                table = ws[f"B{i}":f"BA{i+2}"]
                # シート終了の判定
                if table[2][0].value == None:
                    break
                class_time = class_times[table[2][0].value]
                for j in range(3, MAX_COLUMN):
                    # 登録されていない講師があったらエラー
                    name = table[0][j].value
                    class1 = table[1][j].value
                    class2 = table[2][j].value
                    if name != None and (class1 != None or class2 != None):
                        ##################
                        # 例外コマの処理  #
                        ##################

                        try:
                            tutors[name]["勤務"][day] |= (1 << class_time)
                        except:
                            print("存在しない講師です")

    ###################################################################################

    # 給与テンプレートを取得
    wb_template = openpyxl.load_workbook(path_template)
    ws_template = wb_template.worksheets[0]
    ws_template["F2"] = year
    ws_template["H2"] = month

    for name in tutor_names:
        if name == None:
            continue
        tutor = tutors[name]
        fullname = tutor["フルネーム"]
        ws_template["H5"].value = fullname
        ws_template[
            "K41"].value = f"=ROUNDDOWN(SUM(K10:K40)/60*{tutor['授業給']},0)"
        ws_template["R41"].value = f'=COUNTIF(R10:R40,"○")*{tutor["交通費"]}'
        for day in range(31):
            for class_time in range(5):
                ws_template.cell(10 + day, 4 +
                                 class_time).value = 80 if tutor["勤務"][day] & (
                                     1 << class_time) else None
        wb_template.save(output_folder + "/" + fullname +
                         f"{year}年{month}月.xlsx")
        print(fullname + f"{year}年{month}月.xlsx を出力")
import sys, msoffcrypto, time

base_dir = 'C:\\Users\\lovebear\\Desktop\\'
pwd_file = 'pwd.txt'
encrypt_file = 'test.docx'
f = open(base_dir+encrypt_file, "rb")
file = msoffcrypto.OfficeFile(f)

with open(base_dir+pwd_file, 'r') as f:
	data = f.read().strip()
	pwds = data.split('\n')
for pwd in pwds:
	f1 = open(base_dir+"decrypted.docx", "wb")
	# Use password
	file.load_key(password=pwd)
	try:
		file.decrypt(f1)
		print ('Encrpt Pwd is %s' % pwd)
		break
	except:
		pass
	f1.close()
f.close()
Beispiel #19
0
def main(argv):
    inputfile = ''
    doCommonPasswordChecks = False
    verbose = False
    customList = False
    try:
        opts, args = getopt.getopt(argv,"hi:cvl:",["ifile=", "common", "verbose", "list="])
    except getopt.GetoptError:
        print ('doc-break.py -i <inputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ('doc-break.py -i <inputfile> -c -v -l <listfile>')
            print ('| -i  |  Required  | <input file> | Will use that file as the one to open  | Somefile.docx')
            print ('| -c  |  Optional  |     None     | Use the 10000 common list              |              ')
            print ('| -v  |  Optional  |     None     | Will spam console with info            |              ')
            print ('| -l  |  Optional  | <input file> | Will use the file as the password list | Password.txt ')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-v", "--verbose"):
            verbose = True
        elif opt in ("-c", "--common"):
            doCommonPasswordChecks = True
        elif opt in ("-l", "--list"):
            customList = arg
    if inputfile == '':
        print ('No file passed.')
        print ('doc-break.py -i <inputfile>')
        sys.exit()
    
    exists = os.path.isfile(inputfile)
    
    if not exists:
        print ('Failed to find file. Please check your file location: ')
        print (inputfile)
        sys.exit()
    fh = msoffcrypto.OfficeFile(open(inputfile, "rb"))
    
    found = False
    if doCommonPasswordChecks:
        exists = os.path.isfile("10000-password-top-list.txt")
        if not exists:  
            download_PasswordList()
        common_passwords = open('10000-password-top-list.txt')
        currentLine = 1
        print ("Checking against the 10000 common password list")
        for line in common_passwords:
            if verbose:
                print ('Trying "' + line.rstrip() + '"')
                print ( str(currentLine) + '/' + str(10000))
            if breakFile(fh, line.rstrip()):
                break
            currentLine = currentLine+1
        common_passwords.close()
        
    if customList:
        exists = os.path.isfile(customList)
        if not exists:  
            print ('Could not find list "' + customList + '" Please check your file')
            sys.exit()
        
        password_list = open(customList)
        #this is ugly. I know
        linecount = 0
        for line in password_list:
            linecount = linecount+1
        password_list.close()
        password_list = open(customList)
        linecount = str(linecount)
        currentLine = 1
        for line in password_list:
            if verbose:
                print ('Trying "' + line.rstrip() + '"')
                print ( str(currentLine) + '/' + linecount)
            if breakFile(fh, line.rstrip()):
                break
            currentLine = currentLine+1
        password_list.close()
        
    print ('Could not find the password. Perhaps try a larger list')
Beispiel #20
0
import msoffcrypto

file = msoffcrypto.OfficeFile(open("daznotes.docx", "rb"))

#file = msoffcrypto.OfficeFile(open("1.docx", "rb"))

charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTSUVWXYZ1234567890!"

import string, itertools

# This piece of code does not mean to be fully workable
# due to SoloLearn Code Playground limitations..
import itertools
import string
import multiprocessing

# charset will contain letters, numbers
# and punctuation marks..
#charset = string.ascii_letters + string.digits + string.punctuation

# this charset contains only uppercase letters...
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTSUVWXYZ123456789!"

password = "******"

bool = False


def brute(n):
    global bool
    for pwd in itertools.product(charset, repeat=n):
Beispiel #21
0
def extractFile(zname, passwords_arr):

    global is_found
    global start
    global office

    (filepath, tempfilename) = os.path.split(zname)
    (filename, extension) = os.path.splitext(tempfilename)
    m = extension
    if m in office:
        msfile = msoffcrypto.OfficeFile(open(zname, "rb"))  #实例化类
        #print("get office")
    elif m == '.pdf':
        pdfReader = PyPDF4.PdfFileReader(open(zname, 'rb'))
        #print("get pdf")
    elif m == '.zip':
        zFile = zipfile.ZipFile(zname)  #实例化类
        #print("get zip")
    elif m == '.rar':
        rFile = rarfile.RarFile(zname)  #实例化类
        #print("get rar")
    #msfile = msoffcrypto.OfficeFile(open(zname,"rb"))#实例化类
    bar = tqdm(passwords_arr)
    index = 0
    for letter in bar:
        line = passwords_arr[index]
        index += 1
        password = line.strip('\n')
        if is_found == True:
            bar.close()
            return

#如果口令正确,输出口令,如果错误,抛出异常并测试下一个口令
        if m in office:
            try:
                msfile.load_key(password=password)
                msfile.decrypt(open('decrypto' + zname, 'wb'))
                #print("get office")
                is_found = True
                #sys.stdout.flush()
                bar.close()
                time.sleep(1)
                print("Found Password:"******"run time:" + str((end - start).seconds) + "s")
                return
            except:
                pass
        elif m == '.pdf':
            if pdfReader.decrypt(password):
                is_found = True
                #sys.stdout.flush()
                bar.close()
                time.sleep(1)
                print("Found Password:"******"run time:" + str((end - start).seconds) + "s")
        elif m == '.zip':
            try:
                zFile.extractall(pwd=password.encode('utf-8'))
                is_found = True
                bar.close()
                time.sleep(1)
                print("Found Password:"******"run time" + str((end - start).seconds) + "s")
                return
            except:
                pass
        elif m == '.rar':
            try:
                rFile.extractall(pwd=password)
                is_found = True
                #sys.stdout.flush()
                bar.close()
                time.sleep(1)
                print("Found Password:"******"run time" + str((end - start).seconds) + "s")
                return
            except:
                pass
import msoffcrypto

found = 0
NUMBERS = "1234567890"
SYMBOLS = "#@%&*"
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
FILENAME = input("Target filepath : ")
OUTPUT_FILENAME = input("Decrypted file name : ")
MAX_LENGTH = int(input("Maximum length of password : "******"Minimum length of password : "******"Bruteforcing level : "))

file = msoffcrypto.OfficeFile(open(FILENAME, 'rb'))  #file path


def Check_Password(password):
    global found
    file.load_key(password=password)
    file.decrypt(open(OUTPUT_FILENAME, "wb"))
    print("\nPassword found : " + password)
    input()
    found = 1


def brute(string, Maxlength, Minlength, charset):
    if not found:
        if len(string) == Maxlength:
            return
        for char in charset:
            password = string + char
Beispiel #23
0
def fileinfo(path: str) -> Dict:
    path = safe_str(path)

    data = get_digests_for_file(path, on_first_block=ident)

    # This is a special case, we know if the mime is set to one of these values
    # then the input file is almost certainly an office file, but based on only the first
    # block magic can't figure out any more than that. To handle that case we will read the
    # entire file, and identify again.
    if data['mime'] is not None and data['mime'].lower() in [
            'application/cdfv2-corrupt', 'application/cdfv2-unknown'
    ]:
        with open(path, 'rb') as fh:
            buf = fh.read()
            buflen = len(buf)
            data.update(ident(buf, buflen))
    data['ssdeep'] = ssdeep_from_file(path) if ssdeep_from_file else ''

    # When data is parsed from a cart file we trust its metatdata and can skip the recognition test later
    cart_metadata_set = False

    if not int(data.get('size', -1)):
        data['type'] = 'empty'
    elif data['type'] in ['archive/zip', 'java/jar']:
        # In addition to explicit zip files, we also want to run zip_ident when
        # a file is a jar as there is a high rate of false positive (magic
        # matching eclipse and other java related files as jars)
        data['type'] = zip_ident(path)
    elif data['type'] == 'document/office/unknown':
        # For unknown document files try identifying them by unziping,
        # but don't commit to it being a zip if it can't be extracted
        data['type'] = zip_ident(path, data['type'])
    elif data['type'] == 'unknown':
        data['type'], _ = guess_language(path)
    elif data['type'] == 'archive/cart':
        data['type'] = cart_ident(path)
        cart_metadata_set = True
    elif data['type'] == 'executable/windows/dos':
        # The default magic file misidentifies PE files with a munged DOS header
        data['type'] = dos_ident(path)
    elif data['type'] == 'code/html':
        # Magic detects .hta files as .html, guess_language detects .hta files as .js/.vbs
        # If both conditions are met, it's fair to say that the file is an .hta
        lang, _ = guess_language(path)
        if lang in ["code/javascript", "code/vbs"]:
            data['type'] = 'code/hta'

    if data['type'] in [
            'document/office/word', 'document/office/excel',
            'document/office/powerpoint', 'document/office/unknown'
    ]:
        try:
            msoffcrypto_obj = msoffcrypto.OfficeFile(open(path, "rb"))
            if msoffcrypto_obj and msoffcrypto_obj.is_encrypted():
                data['type'] = 'document/office/passwordprotected'
        except Exception:
            # If msoffcrypto can't handle the file to confirm that it is/isn't password protected,
            # then it's not meant to be. Moving on!
            pass

    if not recognized.get(data['type'], False) and not cart_metadata_set:
        data['type'] = 'unknown'

    return data
Beispiel #24
0
def pw_guess(i):
	res = itertools.product(characters, repeat=i)
	for guess in res:
		yield guess

path = "./target/temp"
if os.path.exists(path) == False:
	print("creating temp folder")
	try:
		original_umask = os.umask(0)
		os.mkdir(path, 777)
	finally:
		os.umask(original_umask)
		shutil.chown(path, user=os.getuid(), group=os.getgid())

file = msoffcrypto.OfficeFile(open("./target/"+filename+"."+fileformat, "rb"))

for i in range(1,maxlength):
	guess_generator = pw_guess(i)
	for guess in guess_generator:
		passwd = ''.join(guess)
		gen_path = "target/temp/"+filename+"-"+passwd+"."+fileformat

		try:
			file.load_key(password=passwd)

			file.decrypt(open(gen_path, "wb"))
			print("ketemu password: "+passwd)
			stop = True
			break
		except:
Beispiel #25
0
#-*- coding: UTF-8 -*-
import msoffcrypto
import sys

file = msoffcrypto.OfficeFile(open("python msoffice/网络攻防实践.xlsx", "rb"))

def progressbar(nowprogress,toyal):    #nowprogress现在的进度数   toyal#总数
    get_progress=int((nowprogress+1)*(50/toyal))   #显示多少>
    get_pro=int(50-get_progress)#显示多少-
    percent=(nowprogress+1)*(100/toyal)
    print("\r"+"["+">"*get_progress+"-"*get_pro+']'+"%.2f" % percent + "%",end="")

passFile=open(r'3_100/pass0.txt',encoding="utf-8")
zpw=passFile.readlines()
for line in zpw:
	progressbar(zpw.index(line),len(zpw))
	password = line.strip('\n')
	try:
		file.load_key(password)
		file.decrypt(open("python msoffice/网络攻防实践5.xlsx", "wb"))
		print(password)
		#sys.exit()
	except Exception :
		# print(0)
		pass
    

Beispiel #26
0
def is_encrypted(some_file):
    """
    Determine whether document contains encrypted content.

    This should return False for documents that are just write-protected or
    signed or finalized. It should return True if ANY content of the file is
    encrypted and can therefore not be analyzed by other oletools modules
    without given a password.

    Exception: there are way to write-protect an office document by embedding
    it as encrypted stream with hard-coded standard password into an otherwise
    empty OLE file. From an office user point of view, this is no encryption,
    but regarding file structure this is encryption, so we return `True` for
    these.

    This should not raise exceptions needlessly.

    This implementation is rather simple: it returns True if the file contains
    streams with typical encryption names (c.f. [MS-OFFCRYPTO]). It does not
    test whether these streams actually contain data or whether the ole file
    structure contains the necessary references to these. It also checks the
    "well-known property" PIDSI_DOC_SECURITY if the SummaryInformation stream
    is accessible (c.f. [MS-OLEPS] 2.25.1)

    :param some_file: File name or an opened OleFileIO
    :type some_file: :py:class:`olefile.OleFileIO` or `str`
    :returns: True if (and only if) the file contains encrypted content
    """
    log.debug('is_encrypted')

    # ask msoffcrypto if possible
    if check_msoffcrypto():
        log.debug('Checking for encryption using msoffcrypto')
        file_handle = None
        file_pos = None
        try:
            if isinstance(some_file, OleFileIO):
                # TODO: hacky, replace once msoffcrypto-tools accepts OleFileIO
                file_handle = some_file.fp
                file_pos = file_handle.tell()
                file_handle.seek(0)
            else:
                file_handle = open(some_file, 'rb')

            return msoffcrypto.OfficeFile(file_handle).is_encrypted()

        except Exception as exc:
            log.warning('msoffcrypto failed to interpret file {} or determine '
                        'whether it is encrypted: {}'
                        .format(file_handle.name, exc))

        finally:
            try:
                if file_pos is not None:   # input was OleFileIO
                    file_handle.seek(file_pos)
                else:                      # input was file name
                    file_handle.close()
            except Exception as exc:
                log.warning('Ignoring error during clean up: {}'.format(exc))

    # if that failed, try ourselves with older and less accurate code
    try:
        if isinstance(some_file, OleFileIO):
            return _is_encrypted_ole(some_file)
        if zipfile.is_zipfile(some_file):
            return _is_encrypted_zip(some_file)
        # otherwise assume it is the name of an ole file
        with OleFileIO(some_file) as ole:
            return _is_encrypted_ole(ole)
    except Exception as exc:
        log.warning('Failed to check {} for encryption ({}); assume it is not '
                    'encrypted.'.format(some_file, exc))

    return False
Beispiel #27
0
for i, c in enumerate(charset[:-1]):
	nextchar[c] = charset[i + 1]

# Set up other things
logfile = open('output.log', 'a')
password = ""
if os.path.isfile('passwordprogress.log'):
	with open('passwordprogress.log', 'r') as f:
	    password = f.readline()

count = 0
starttime = time.time()
filename = sys.argv[1]
print filename
try:
	file = msoffcrypto.OfficeFile(open(filename, "rb"))
except:
	print "bad file"
	sys.exit(1)

def incrementString(s):
	if s == "":
		return charset[0]
	if s[-1] == charset[-1]:
		return incrementString(s[:-1]) + charset[0]
	return s[:-1] + nextchar[s[-1]]

def getTime():
	return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

def tryPassword(p):
Beispiel #28
0
def crackfile():
    '''
    主函数
    '''
    # zFile=zipfile.ZipFile(r'E:\学习。\攻防\teachergive2\第一天\one\zip.zip')
    # passFile=open(r'E:\学习。\攻防\teachergive2\第一天\one\password.txt',encoding="utf-8")

    # parser = optparse.OptionParser("usage %prog "+\
    #         "-f <file> -d <dictionary>")
    # parser.add_option('-f',dest = 'zname',type = 'string',help = 'specify file')
    # parser.add_option('-d',dest = 'dname',type = 'string',help = 'specify dictionary')
    # (options,args) = parser.parse_args()
    # if(options.zname == None) | (options.dname == None):
    #     print(parser.usage)

    #     exit(0)
    # else:
    #     zname = options.zname
    #     dname = options.dname
    # if zname.endswith('.zip'):
    #     File = zipfile.ZipFile(zname)
    #     label = 0
    # elif zname.endswith('.rar'):
    #     File = rarfile.RarFile(zname)
    #     label = 1
    # File = zipfile.ZipFile(zname)
    try:
        filename = input("input filename: ")
        passtxt = input("input passtxt: ")
        label = input("input label: ")
        label = int(label)

        # filename="zip.zip"
        # passtxt="password.txt"
        # label = 0

        if label == 0:
            File = zipfile.ZipFile(filename)
        elif label == 1:
            File = rarfile.RarFile(filename)
        elif label == 2:
            File = PyPDF4.PdfFileReader(open(filename, 'rb'))
        elif label == 3:
            File = msoffcrypto.OfficeFile(open(filename, "rb"))
        else:
            print("crack error")
            return

        passFile = open(passtxt)
        # print(zname)
        # print(dname)
        zpw = passFile.readlines()
        result = 0
        for line in zpw:
            progressbar(zpw.index(line), len(zpw))

            # if event.isSet():
            #     print("End")
            #     return
            # else:

            pwdline = line.strip('\n')
            pwdlist = pwdline.split()
            for password in pwdlist:
                if (label == 0):
                    # t = threading.Thread(target=extractzipFile, args=(File, password))
                    result = extractzipFile(File, password)
                elif (label == 1):
                    # t = threading.Thread(target=extractrarFile, args=(File, password))
                    extractrarFile(File, password)
                elif (label == 2):
                    # t = threading.Thread(target=extractpdfFile, args=(File, password))
                    extractpdfFile(File, password)
                elif (label == 3):
                    # t = threading.Thread(target=extractoffFile, args=(File, password))
                    extractoffFile(File, password)
                # t.start()
            if (result == 1):
                sys.exit()
                return 1
    except:
        print("input error")
        pass
Beispiel #29
0
def decrypt_msoffice_file_multicore(msOfficeFilePath,
                                    permutationsDirectoryPath,
                                    psswdLength,
                                    withDigits=True,
                                    withLowerLetters=False,
                                    withUpperLetters=False,
                                    withSpecialCharacters=False,
                                    numberOfCores=None):

    if (not os.path.exists(msOfficeFilePath)):
        print("File {} does not exist".format(msOfficeFilePath))
        exit(0)

    permutaionsPath = permutation.generate_permutaions(
        permutationsDirectoryPath=permutationsDirectoryPath,
        psswdLength=psswdLength,
        withDigits=withDigits,
        withLowerLetters=withLowerLetters,
        withUpperLetters=withUpperLetters,
        withSpecialCharacters=withSpecialCharacters)

    global fileIn
    fileIn = msoffcrypto.OfficeFile(open(msOfficeFilePath, "rb"))
    extension = os.path.splitext(msOfficeFilePath)[1]

    # read each file containig password in seperate thread to speed up ....

    if not numberOfCores:
        numberOfCores = os.cpu_count()
    else:
        if numberOfCores > os.cpu_count():
            print("Number of available Cores in this device" \
                  "is {0}, cant set cores to {1}, it will be set to {2}".
                  format(os.cpu_count(), numberOfCores, os.cpu_count()))
            numberOfCores = os.cpu_count()

    with multiprocessing.Pool(numberOfCores) as pool:

        for i in range(1, psswdLength + 1):
            print("Checking {} length password".format(i))
            psswdSubDirectory = os.path.join(permutaionsPath, str(i))

            if (os.path.isdir(psswdSubDirectory)):
                allFiles = os.listdir(psswdSubDirectory)

                for psswdFile in allFiles:

                    if (permutation.fileNameRule.match(psswdFile)):

                        print("\tSearching in {}".format(psswdFile))
                        psswdFilePath = os.path.join(psswdSubDirectory,
                                                     psswdFile)
                        psswdFileIn = open(psswdFilePath, 'r')

                        EOF = False
                        while not EOF:
                            lines = [
                                psswdFileIn.readline().strip()
                                for _ in range(numberOfCores)
                            ]
                            t = [
                                pool.apply_async(func=decrypt_single_password,
                                                 args=(
                                                     psswd,
                                                     "test_decrypt_now" +
                                                     extension,
                                                 )) for psswd in lines
                            ]
                            for uu in t:
                                res = uu.get()
                                if res:
                                    return res

                            EOF = not lines[-1]

                        psswdFileIn.close()
                print("")

    return False