Skip to content

Commit

Permalink
Lint almost all with black
Browse files Browse the repository at this point in the history
  • Loading branch information
nolze committed Jan 4, 2021
1 parent a6e454d commit 4094cbb
Show file tree
Hide file tree
Showing 16 changed files with 1,104 additions and 811 deletions.
21 changes: 13 additions & 8 deletions msoffcrypto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import zipfile
import pkg_resources

__version__ = pkg_resources.get_distribution('msoffcrypto-tool').version
__version__ = pkg_resources.get_distribution("msoffcrypto-tool").version


def OfficeFile(file):
'''Return an office file object based on the format of given file.
"""Return an office file object based on the format of given file.
Args:
file (:obj:`_io.BufferedReader`): Input file.
Expand All @@ -22,35 +22,40 @@ def OfficeFile(file):
Given file handle will not be closed, the file position will most certainly
change.
'''
file.seek(0) # required by isOleFile
"""
file.seek(0) # required by isOleFile
if olefile.isOleFile(file):
ole = olefile.OleFileIO(file)
elif zipfile.is_zipfile(file): # Heuristic
from .format.ooxml import OOXMLFile

return OOXMLFile(file)
else:
raise Exception("Unsupported file format")

# TODO: Make format specifiable by option in case of obstruction
# Try this first; see https://github.com/nolze/msoffcrypto-tool/issues/17
if ole.exists('EncryptionInfo'):
if ole.exists("EncryptionInfo"):
from .format.ooxml import OOXMLFile

return OOXMLFile(file)
# MS-DOC: The WordDocument stream MUST be present in the file.
# https://msdn.microsoft.com/en-us/library/dd926131(v=office.12).aspx
elif ole.exists('wordDocument'):
elif ole.exists("wordDocument"):
from .format.doc97 import Doc97File

return Doc97File(file)
# MS-XLS: A file MUST contain exactly one Workbook Stream, ...
# https://msdn.microsoft.com/en-us/library/dd911009(v=office.12).aspx
elif ole.exists('Workbook'):
elif ole.exists("Workbook"):
from .format.xls97 import Xls97File

return Xls97File(file)
# MS-PPT: A required stream whose name MUST be "PowerPoint Document".
# https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ppt/1fc22d56-28f9-4818-bd45-67c2bf721ccf
elif ole.exists('PowerPoint Document'):
elif ole.exists("PowerPoint Document"):
from .format.ppt97 import Ppt97File

return Ppt97File(file)
else:
raise Exception("Unrecognized file format")
21 changes: 11 additions & 10 deletions msoffcrypto/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,21 @@


def ifWIN32SetBinary(io):
if sys.platform == 'win32':
if sys.platform == "win32":
import msvcrt, os

msvcrt.setmode(io.fileno(), os.O_BINARY)


def is_encrypted(file):
r'''
r"""
Test if the file is encrypted.
>>> f = open("tests/inputs/plain.doc", "rb")
>>> file = OfficeFile(f)
>>> is_encrypted(file)
False
'''
"""
# TODO: Validate file
if not olefile.isOleFile(file):
return False
Expand All @@ -38,11 +39,11 @@ def is_encrypted(file):

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-p', '--password', nargs='?', const='', dest='password', help='Password text.')
group.add_argument('-t', '--test', dest='test_encrypted', action='store_true', help='Test if the file is encrypted.')
parser.add_argument('-v', dest='verbose', action='store_true', help='Print verbose information.')
parser.add_argument('infile', nargs='?', type=argparse.FileType('rb'), help='Input file.')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), help='Output file. If blank, stdout is used.')
group.add_argument("-p", "--password", nargs="?", const="", dest="password", help="Password text.")
group.add_argument("-t", "--test", dest="test_encrypted", action="store_true", help="Test if the file is encrypted.")
parser.add_argument("-v", dest="verbose", action="store_true", help="Print verbose information.")
parser.add_argument("infile", nargs="?", type=argparse.FileType("rb"), help="Input file.")
parser.add_argument("outfile", nargs="?", type=argparse.FileType("wb"), help="Output file. If blank, stdout is used.")


def main():
Expand Down Expand Up @@ -74,13 +75,13 @@ def main():

if args.outfile is None:
ifWIN32SetBinary(sys.stdout)
if hasattr(sys.stdout, 'buffer'): # For Python 2
if hasattr(sys.stdout, "buffer"): # For Python 2
args.outfile = sys.stdout.buffer
else:
args.outfile = sys.stdout

file.decrypt(args.outfile)


if __name__ == '__main__':
if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion msoffcrypto/format/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# For 2 and 3 compatibility
# https://stackoverflow.com/questions/35673474/
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()})


class BaseOfficeFile(ABC):
Expand Down
54 changes: 27 additions & 27 deletions msoffcrypto/format/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,45 @@

# https://msdn.microsoft.com/en-us/library/dd926359(v=office.12).aspx
def _parse_encryptionheader(blob):
flags, = unpack('<I', blob.read(4))
(flags,) = unpack("<I", blob.read(4))
# if mode == 'strict': compare values with spec.
sizeExtra, = unpack('<I', blob.read(4))
algId, = unpack('<I', blob.read(4))
algIdHash, = unpack('<I', blob.read(4))
keySize, = unpack('<I', blob.read(4))
providerType, = unpack('<I', blob.read(4))
reserved1, = unpack('<I', blob.read(4))
reserved2, = unpack('<I', blob.read(4))
cspName = blob.read().decode('utf-16le')
(sizeExtra,) = unpack("<I", blob.read(4))
(algId,) = unpack("<I", blob.read(4))
(algIdHash,) = unpack("<I", blob.read(4))
(keySize,) = unpack("<I", blob.read(4))
(providerType,) = unpack("<I", blob.read(4))
(reserved1,) = unpack("<I", blob.read(4))
(reserved2,) = unpack("<I", blob.read(4))
cspName = blob.read().decode("utf-16le")
header = {
'flags': flags,
'sizeExtra': sizeExtra,
'algId': algId,
'algIdHash': algIdHash,
'keySize': keySize,
'providerType': providerType,
'reserved1': reserved1,
'reserved2': reserved2,
'cspName': cspName,
"flags": flags,
"sizeExtra": sizeExtra,
"algId": algId,
"algIdHash": algIdHash,
"keySize": keySize,
"providerType": providerType,
"reserved1": reserved1,
"reserved2": reserved2,
"cspName": cspName,
}
return header


# https://msdn.microsoft.com/en-us/library/dd910568(v=office.12).aspx
def _parse_encryptionverifier(blob, algorithm):
saltSize, = unpack('<I', blob.read(4))
(saltSize,) = unpack("<I", blob.read(4))
salt = blob.read(16)
encryptedVerifier = blob.read(16)
verifierHashSize, = unpack('<I', blob.read(4))
if algorithm == 'RC4':
(verifierHashSize,) = unpack("<I", blob.read(4))
if algorithm == "RC4":
encryptedVerifierHash = blob.read(20)
elif algorithm == 'AES':
elif algorithm == "AES":
encryptedVerifierHash = blob.read(32)
verifier = {
'saltSize': saltSize,
'salt': salt,
'encryptedVerifier': encryptedVerifier,
'verifierHashSize': verifierHashSize,
'encryptedVerifierHash': encryptedVerifierHash,
"saltSize": saltSize,
"salt": salt,
"encryptedVerifier": encryptedVerifier,
"verifierHashSize": verifierHashSize,
"encryptedVerifierHash": encryptedVerifierHash,
}
return verifier
Loading

0 comments on commit 4094cbb

Please sign in to comment.