diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..06c790b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a bug report to help us fix issues + +--- + +**Affected tool:** +olevba, mraptor, rtfobj, oleid, etc + +**Describe the bug** +A clear and concise description of what the bug is. + +**File/Malware sample to reproduce the bug** +Please attach the file in a password protected zip archive, or provide a link where it can be downloaded (e.g. Hybrid Analysis, preferably not VirusTotal which requires paid access). If not possible, please provide a hash. + +**How To Reproduce the bug** +Steps to reproduce the behavior, including the full command line or the options you used. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Console output / Screenshots** +If applicable, add screenshots to help explain your problem. +Use the option "-l debug" to add debugging information, if possible. + +**Version information:** + - OS: Windows/Linux/Mac/Other + - OS version: x.xx - 32/64 bits + - Python version: 2.7/3.6 - 32/64 bits + - oletools version: + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..066b2d9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.travis.yml b/.travis.yml index 2c621c8..de2b1f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,21 @@ language: python - -python: - - "2.7" - - "3.6" - - "nightly" cache: pip +sudo: false + +matrix: + include: + - python: 2.7 + - python: 3.4 + - python: 3.5 + - python: 3.6 + - python: 3.7 + dist: xenial + sudo: yes + - python: nightly + dist: xenial + sudo: yes + - python: pypy + - python: pypy3 + script: - python setup.py test diff --git a/README.md b/README.md index 9614b4d..69b7b81 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ python-oletools =============== -[![PyPI](https://img.shields.io/pypi/v/oletools.svg)](https://pypi.python.org/pypi/oletools) +[![PyPI](https://img.shields.io/pypi/v/oletools.svg)](https://pypi.org/project/oletools/) [![Build Status](https://travis-ci.org/decalage2/oletools.svg?branch=master)](https://travis-ci.org/decalage2/oletools) +[![Say Thanks!](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/decalage2) [oletools](http://www.decalage.info/python/oletools) is a package of python tools to analyze [Microsoft OLE2 files](http://en.wikipedia.org/wiki/Compound_File_Binary_Format) @@ -87,7 +88,15 @@ including [Viper](http://viper.li/), [REMnux](https://remnux.org/), [dridex.malwareconfig.com](https://dridex.malwareconfig.com), [Snake](https://github.com/countercept/snake), [DARKSURGEON](https://github.com/cryps1s/DARKSURGEON), -and probably [VirusTotal](https://www.virustotal.com). +[CAPE](https://github.com/ctxis/CAPE), +[AssemblyLine](https://www.cse-cst.gc.ca/en/assemblyline), +[malshare.io](https://malshare.io), +[Malware Repository Framework (MRF)](https://www.adlice.com/download/mrf/), +[malware-repo](https://github.com/Tigzy/malware-repo), +[Vba2Graph](https://github.com/MalwareCantFly/Vba2Graph), +[Strelka](https://github.com/target/strelka), +and probably [VirusTotal](https://www.virustotal.com). +And quite a few [other projects on GitHub](https://github.com/search?q=oletools&type=Repositories). (Please [contact me]((http://decalage.info/contact)) if you have or know a project using oletools) diff --git a/oletools/README.html b/oletools/README.html index 8f157e6..4da6e8a 100644 --- a/oletools/README.html +++ b/oletools/README.html @@ -17,7 +17,7 @@

python-oletools

-

PyPI Build Status

+

PyPI Build Status

oletools is a package of python tools to analyze Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft Office documents or Outlook messages, mainly for malware analysis, forensics and debugging. It is based on the olefile parser. See http://www.decalage.info/python/oletools for more info.

Quick links: Home page - Download/Install - Documentation - Report Issues/Suggestions/Questions - Contact the Author - Repository - Updates on Twitter Cheatsheet

Note: python-oletools is not related to OLETools published by BeCubed Software.

diff --git a/oletools/README.rst b/oletools/README.rst index bbf818d..323a954 100644 --- a/oletools/README.rst +++ b/oletools/README.rst @@ -240,6 +240,6 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. .. |PyPI| image:: https://img.shields.io/pypi/v/oletools.svg - :target: https://pypi.python.org/pypi/oletools + :target: https://pypi.org/project/oletools/ .. |Build Status| image:: https://travis-ci.org/decalage2/oletools.svg?branch=master :target: https://travis-ci.org/decalage2/oletools diff --git a/oletools/common/clsid.py b/oletools/common/clsid.py index df74ab3..156aaed 100644 --- a/oletools/common/clsid.py +++ b/oletools/common/clsid.py @@ -43,7 +43,7 @@ http://www.decalage.info/python/oletools # 2018-04-18 PL: - added known-bad CLSIDs from Cuckoo sandbox (issue #290) # 2018-05-08 PL: - added more CLSIDs (issues #299, #304), merged and sorted -__version__ = '0.53' +__version__ = '0.54dev3' # REFERENCES: @@ -80,12 +80,14 @@ KNOWN_CLSIDS = { '00020900-0000-0000-C000-000000000046': 'Microsoft Word 6.0-7.0 Document (Word.Document.6)', '00020906-0000-0000-C000-000000000046': 'Microsoft Word 97-2003 Document (Word.Document.8)', '00020C01-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', + '00021401-0000-0000-C000-000000000046': 'Windows LNK Shortcut file', # ref: https://github.com/libyal/liblnk/blob/master/documentation/Windows%20Shortcut%20File%20(LNK)%20format.asciidoc '00021700-0000-0000-C000-000000000046': 'Microsoft Equation 2.0 (Known Related to CVE-2017-11882 or CVE-2018-0802)', '00022601-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', '00022602-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', '00022603-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', '0002CE02-0000-0000-C000-000000000046': 'Microsoft Equation 3.0 (Known Related to CVE-2017-11882 or CVE-2018-0802)', '0002CE03-0000-0000-C000-000000000046': 'MathType Equation Object', + '0003000B-0000-0000-C000-000000000046': 'Microsoft Equation (Known Related to CVE-2017-11882 or CVE-2018-0802)', '0003000C-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', '0003000D-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', '0003000E-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)', diff --git a/oletools/common/errors.py b/oletools/common/errors.py new file mode 100644 index 0000000..4ee4cb1 --- /dev/null +++ b/oletools/common/errors.py @@ -0,0 +1,13 @@ +""" +Errors used in several tools to avoid duplication + +.. codeauthor:: Intra2net AG +""" + +class FileIsEncryptedError(ValueError): + """Exception thrown if file is encrypted and cannot deal with it.""" + # see also: same class in olevba[3] and record_base + def __init__(self, filename=None): + super(FileIsEncryptedError, self).__init__( + 'Office file {}is encrypted, not yet supported' + .format('' if filename is None else filename + ' ')) diff --git a/oletools/common/log_helper/__init__.py b/oletools/common/log_helper/__init__.py new file mode 100644 index 0000000..7a027c2 --- /dev/null +++ b/oletools/common/log_helper/__init__.py @@ -0,0 +1,5 @@ +from . import log_helper as log_helper_ + +log_helper = log_helper_.LogHelper() + +__all__ = ['log_helper'] diff --git a/oletools/common/log_helper/_json_formatter.py b/oletools/common/log_helper/_json_formatter.py new file mode 100644 index 0000000..4c5e337 --- /dev/null +++ b/oletools/common/log_helper/_json_formatter.py @@ -0,0 +1,24 @@ +import logging +import json + + +class JsonFormatter(logging.Formatter): + """ + Format every message to be logged as a JSON object + """ + _is_first_line = True + + def format(self, record): + """ + Since we don't buffer messages, we always prepend messages with a comma to make + the output JSON-compatible. The only exception is when printing the first line, + so we need to keep track of it. + """ + json_dict = dict(msg=record.msg, level=record.levelname) + formatted_message = ' ' + json.dumps(json_dict) + + if self._is_first_line: + self._is_first_line = False + return formatted_message + + return ', ' + formatted_message diff --git a/oletools/common/log_helper/_logger_adapter.py b/oletools/common/log_helper/_logger_adapter.py new file mode 100644 index 0000000..75e331a --- /dev/null +++ b/oletools/common/log_helper/_logger_adapter.py @@ -0,0 +1,30 @@ +import logging +from . import _root_logger_wrapper + + +class OletoolsLoggerAdapter(logging.LoggerAdapter): + """ + Adapter class for all loggers returned by the logging module. + """ + _json_enabled = None + + def print_str(self, message): + """ + This function replaces normal print() calls so we can format them as JSON + when needed or just print them right away otherwise. + """ + if self._json_enabled and self._json_enabled(): + # Messages from this function should always be printed, + # so when using JSON we log using the same level that set + self.log(_root_logger_wrapper.level(), message) + else: + print(message) + + def set_json_enabled_function(self, json_enabled): + """ + Set a function to be called to check whether JSON output is enabled. + """ + self._json_enabled = json_enabled + + def level(self): + return self.logger.level diff --git a/oletools/common/log_helper/_root_logger_wrapper.py b/oletools/common/log_helper/_root_logger_wrapper.py new file mode 100644 index 0000000..273d5c6 --- /dev/null +++ b/oletools/common/log_helper/_root_logger_wrapper.py @@ -0,0 +1,24 @@ +import logging + + +def is_logging_initialized(): + """ + We use the same strategy as the logging module when checking if + the logging was initialized - look for handlers in the root logger + """ + return len(logging.root.handlers) > 0 + + +def set_formatter(fmt): + """ + Set the formatter to be used by every handler of the root logger. + """ + if not is_logging_initialized(): + return + + for handler in logging.root.handlers: + handler.setFormatter(fmt) + + +def level(): + return logging.root.level diff --git a/oletools/common/log_helper/log_helper.py b/oletools/common/log_helper/log_helper.py new file mode 100644 index 0000000..7a7fb02 --- /dev/null +++ b/oletools/common/log_helper/log_helper.py @@ -0,0 +1,194 @@ +""" +log_helper.py + +General logging helpers + +.. codeauthor:: Intra2net AG +""" + +# === LICENSE ================================================================= +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +# ----------------------------------------------------------------------------- +# CHANGELOG: +# 2017-12-07 v0.01 CH: - first version +# 2018-02-05 v0.02 SA: - fixed log level selection and reformatted code +# 2018-02-06 v0.03 SA: - refactored code to deal with NullHandlers +# 2018-02-07 v0.04 SA: - fixed control of handlers propagation +# 2018-04-23 v0.05 SA: - refactored the whole logger to use an OOP approach + +# ----------------------------------------------------------------------------- +# TODO: + + +from ._json_formatter import JsonFormatter +from ._logger_adapter import OletoolsLoggerAdapter +from . import _root_logger_wrapper +import logging +import sys + + +LOG_LEVELS = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL +} + +DEFAULT_LOGGER_NAME = 'oletools' +DEFAULT_MESSAGE_FORMAT = '%(levelname)-8s %(message)s' + + +class LogHelper: + def __init__(self): + self._all_names = set() # set so we do not have duplicates + self._use_json = False + self._is_enabled = False + + def get_or_create_silent_logger(self, name=DEFAULT_LOGGER_NAME, level=logging.CRITICAL + 1): + """ + Get a logger or create one if it doesn't exist, setting a NullHandler + as the handler (to avoid printing to the console). + By default we also use a higher logging level so every message will + be ignored. + This will prevent oletools from logging unnecessarily when being imported + from external tools. + """ + return self._get_or_create_logger(name, level, logging.NullHandler()) + + def enable_logging(self, use_json, level, log_format=DEFAULT_MESSAGE_FORMAT, stream=None): + """ + This function initializes the root logger and enables logging. + We set the level of the root logger to the one passed by calling logging.basicConfig. + We also set the level of every logger we created to 0 (logging.NOTSET), meaning that + the level of the root logger will be used to tell if messages should be logged. + Additionally, since our loggers use the NullHandler, they won't log anything themselves, + but due to having propagation enabled they will pass messages to the root logger, + which in turn will log to the stream set in this function. + Since the root logger is the one doing the work, when using JSON we set its formatter + so that every message logged is JSON-compatible. + """ + if self._is_enabled: + raise ValueError('re-enabling logging. Not sure whether that is ok...') + + log_level = LOG_LEVELS[level] + logging.basicConfig(level=log_level, format=log_format, stream=stream) + self._is_enabled = True + + self._use_json = use_json + sys.excepthook = self._get_except_hook(sys.excepthook) + + # since there could be loggers already created we go through all of them + # and set their levels to 0 so they will use the root logger's level + for name in self._all_names: + logger = self.get_or_create_silent_logger(name) + self._set_logger_level(logger, logging.NOTSET) + + # add a JSON formatter to the root logger, which will be used by every logger + if self._use_json: + _root_logger_wrapper.set_formatter(JsonFormatter()) + print('[') + + def end_logging(self): + """ + Must be called at the end of the main function if the caller wants + json-compatible output + """ + if not self._is_enabled: + return + self._is_enabled = False + + # end logging + self._all_names = set() + logging.shutdown() + + # end json list + if self._use_json: + print(']') + self._use_json = False + + def _get_except_hook(self, old_hook): + """ + Global hook for exceptions so we can always end logging. + We wrap any hook currently set to avoid overwriting global hooks set by oletools. + Note that this is only called by enable_logging, which in turn is called by + the main() function in oletools' scripts. When scripts are being imported this + code won't execute and won't affect global hooks. + """ + def hook(exctype, value, traceback): + self.end_logging() + old_hook(exctype, value, traceback) + + return hook + + def _get_or_create_logger(self, name, level, handler=None): + """ + Get or create a new logger. This newly created logger will have the + handler and level that was passed, but if it already exists it's not changed. + We also wrap the logger in an adapter so we can easily extend its functionality. + """ + + # logging.getLogger creates a logger if it doesn't exist, + # so we need to check before calling it + if handler and not self._log_exists(name): + logger = logging.getLogger(name) + logger.addHandler(handler) + self._set_logger_level(logger, level) + else: + logger = logging.getLogger(name) + + # Keep track of every logger we created so we can easily change + # their levels whenever needed + self._all_names.add(name) + + adapted_logger = OletoolsLoggerAdapter(logger, None) + adapted_logger.set_json_enabled_function(lambda: self._use_json) + + return adapted_logger + + @staticmethod + def _set_logger_level(logger, level): + """ + If the logging is already initialized, we set the level of our logger + to 0, meaning that it will reuse the level of the root logger. + That means that if the root logger level changes, we will keep using + its level and not logging unnecessarily. + """ + + # if this log was wrapped, unwrap it to set the level + if isinstance(logger, OletoolsLoggerAdapter): + logger = logger.logger + + if _root_logger_wrapper.is_logging_initialized(): + logger.setLevel(logging.NOTSET) + else: + logger.setLevel(level) + + @staticmethod + def _log_exists(name): + """ + We check the log manager instead of our global _all_names variable + since the logger could have been created outside of the helper + """ + return name in logging.Logger.manager.loggerDict diff --git a/oletools/ezhexviewer.py b/oletools/ezhexviewer.py index 701f05e..a43e408 100644 --- a/oletools/ezhexviewer.py +++ b/oletools/ezhexviewer.py @@ -48,8 +48,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # 2016-10-26 PL: - fixed to run on Python 2+3 # 2017-03-23 v0.51 PL: - fixed display of control characters (issue #151) # 2017-04-26 PL: - fixed absolute imports (issue #141) +# 2018-09-15 v0.54 PL: - easygui is now a dependency -__version__ = '0.51' +__version__ = '0.54dev1' #----------------------------------------------------------------------------- # TODO: @@ -71,7 +72,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty.easygui import easygui +import easygui # === PYTHON 2+3 SUPPORT ====================================================== diff --git a/oletools/mraptor_milter.py b/oletools/mraptor_milter.py index 2856a36..6b70309 100644 --- a/oletools/mraptor_milter.py +++ b/oletools/mraptor_milter.py @@ -405,7 +405,7 @@ if __name__ == "__main__": daemon.start() # Using python-daemon - Does not work as-is, need to create the PID file - # See https://pypi.python.org/pypi/python-daemon/ + # See https://pypi.org/project/python-daemon/ # See PEP-3143: https://www.python.org/dev/peps/pep-3143/ # import daemon # import lockfile diff --git a/oletools/msodde.py b/oletools/msodde.py index c405a0b..b59b77e 100644 --- a/oletools/msodde.py +++ b/oletools/msodde.py @@ -11,6 +11,7 @@ Supported formats: - RTF - CSV (exported from / imported into Excel) - XML (exported from Word 2003, Word 2007+, Excel 2003, (Excel 2007+?) +- raises an error if run with files encrypted using MS Crypto API RC4 Author: Philippe Lagadec - http://www.decalage.info License: BSD, see source code or documentation @@ -53,25 +54,17 @@ import argparse import os from os.path import abspath, dirname import sys -import json -import logging import re import csv -# little hack to allow absolute imports even if oletools is not installed -# Copied from olevba.py -try: - from oletools.thirdparty import olefile -except ImportError: - PARENT_DIR = dirname(dirname(abspath(__file__))) - if PARENT_DIR not in sys.path: - sys.path.insert(0, PARENT_DIR) - del PARENT_DIR - from oletools.thirdparty import olefile +import olefile from oletools import ooxml from oletools import xls_parser from oletools import rtfobj +from oletools import oleid +from oletools.common.log_helper import log_helper +from oletools.common.errors import FileIsEncryptedError # ----------------------------------------------------------------------------- # CHANGELOG: @@ -93,8 +86,10 @@ from oletools import rtfobj # 2018-01-11 PL: - fixed issue #242 (apply unquote to fldSimple tags) # 2018-01-10 CH: - add single-xml files (Word 2003/2007+ / Excel 2003) # 2018-03-21 CH: - added detection for various CSV formulas (issue #259) +# 2018-09-11 v0.54 PL: - olefile is now a dependency +# 2018-10-25 CH: - detect encryption and raise error if detected -__version__ = '0.53' +__version__ = '0.54dev4' # ----------------------------------------------------------------------------- # TODO: field codes can be in headers/footers/comments - parse these @@ -220,63 +215,12 @@ THIS IS WORK IN PROGRESS - Check updates regularly! Please report any issue at https://github.com/decalage2/oletools/issues """ % __version__ -BANNER_JSON = dict(type='meta', version=__version__, name='msodde', - link='http://decalage.info/python/oletools', - message='THIS IS WORK IN PROGRESS - Check updates regularly! ' - 'Please report any issue at ' - 'https://github.com/decalage2/oletools/issues') - # === LOGGING ================================================================= DEFAULT_LOG_LEVEL = "warning" # Default log level -LOG_LEVELS = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warning': logging.WARNING, - 'error': logging.ERROR, - 'critical': logging.CRITICAL -} - - -class NullHandler(logging.Handler): - """ - Log Handler without output, to avoid printing messages if logging is not - configured by the main application. - Python 2.7 has logging.NullHandler, but this is necessary for 2.6: - see https://docs.python.org/2.6/library/logging.html#configuring-logging-for-a-library - """ - def emit(self, record): - pass - - -def get_logger(name, level=logging.CRITICAL+1): - """ - Create a suitable logger object for this module. - The goal is not to change settings of the root logger, to avoid getting - other modules' logs on the screen. - If a logger exists with same name, reuse it. (Else it would have duplicate - handlers and messages would be doubled.) - The level is set to CRITICAL+1 by default, to avoid any logging. - """ - # First, test if there is already a logger with the same name, else it - # will generate duplicate messages (due to duplicate handlers): - if name in logging.Logger.manager.loggerDict: - # NOTE: another less intrusive but more "hackish" solution would be to - # use getLogger then test if its effective level is not default. - logger = logging.getLogger(name) - # make sure level is OK: - logger.setLevel(level) - return logger - # get a new logger: - logger = logging.getLogger(name) - # only add a NullHandler for this logger, it is up to the application - # to configure its own logging: - logger.addHandler(NullHandler()) - logger.setLevel(level) - return logger # a global logger object used for debugging: -log = get_logger('msodde') +logger = log_helper.get_or_create_silent_logger('msodde') # === UNICODE IN PY2 ========================================================= @@ -320,7 +264,7 @@ def ensure_stdout_handles_unicode(): encoding = 'utf8' # logging is probably not initialized yet, but just in case - log.debug('wrapping sys.stdout with encoder using {0}'.format(encoding)) + logger.debug('wrapping sys.stdout with encoder using {0}'.format(encoding)) wrapper = codecs.getwriter(encoding) sys.stdout = wrapper(sys.stdout) @@ -404,7 +348,7 @@ def process_doc_field(data): """ check if field instructions start with DDE expects unicode input, returns unicode output (empty if not dde) """ - log.debug('processing field \'{0}\''.format(data)) + logger.debug('processing field \'{0}\''.format(data)) if data.lstrip().lower().startswith(u'dde'): return data @@ -442,7 +386,7 @@ def process_doc_stream(stream): if char == OLE_FIELD_START: if have_start and max_size_exceeded: - log.debug('big field was not a field after all') + logger.debug('big field was not a field after all') have_start = True have_sep = False max_size_exceeded = False @@ -454,7 +398,7 @@ def process_doc_stream(stream): # now we are after start char but not at end yet if char == OLE_FIELD_SEP: if have_sep: - log.debug('unexpected field: has multiple separators!') + logger.debug('unexpected field: has multiple separators!') have_sep = True elif char == OLE_FIELD_END: # have complete field now, process it @@ -472,7 +416,7 @@ def process_doc_stream(stream): if max_size_exceeded: pass elif len(field_contents) > OLE_FIELD_MAX_SIZE: - log.debug('field exceeds max size of {0}. Ignore rest' + logger.debug('field exceeds max size of {0}. Ignore rest' .format(OLE_FIELD_MAX_SIZE)) max_size_exceeded = True @@ -490,25 +434,26 @@ def process_doc_stream(stream): field_contents += u'?' if max_size_exceeded: - log.debug('big field was not a field after all') + logger.debug('big field was not a field after all') - log.debug('Checked {0} characters, found {1} fields' + logger.debug('Checked {0} characters, found {1} fields' .format(idx, len(result_parts))) return result_parts -def process_doc(filepath): +def process_doc(ole): """ find dde links in word ole (.doc/.dot) file + Checks whether files is ppt and returns empty immediately in that case + (ppt files cannot contain DDE-links to my knowledge) + like process_xml, returns a concatenated unicode string of dde links or empty if none were found. dde-links will still begin with the dde[auto] key word (possibly after some whitespace) """ - log.debug('process_doc') - ole = olefile.OleFileIO(filepath, path_encoding=None) - + logger.debug('process_doc') links = [] for sid, direntry in enumerate(ole.direntries): is_orphan = direntry is None @@ -516,7 +461,7 @@ def process_doc(filepath): # this direntry is not part of the tree --> unused or orphan direntry = ole._load_direntry(sid) is_stream = direntry.entry_type == olefile.STGTY_STREAM - log.debug('direntry {:2d} {}: {}' + logger.debug('direntry {:2d} {}: {}' .format(sid, '[orphan]' if is_orphan else direntry.name, 'is stream of size {}'.format(direntry.size) if is_stream else @@ -601,7 +546,7 @@ def process_docx(filepath, field_filter_mode=None): ddetext += unquote(elem.text) # apply field command filter - log.debug('filtering with mode "{0}"'.format(field_filter_mode)) + logger.debug('filtering with mode "{0}"'.format(field_filter_mode)) if field_filter_mode in (FIELD_FILTER_ALL, None): clean_fields = all_fields elif field_filter_mode == FIELD_FILTER_DDE: @@ -660,7 +605,7 @@ def field_is_blacklisted(contents): index = FIELD_BLACKLIST_CMDS.index(words[0].lower()) except ValueError: # first word is no blacklisted command return False - log.debug('trying to match "{0}" to blacklist command {1}' + logger.debug('trying to match "{0}" to blacklist command {1}' .format(contents, FIELD_BLACKLIST[index])) _, nargs_required, nargs_optional, sw_with_arg, sw_solo, sw_format \ = FIELD_BLACKLIST[index] @@ -672,11 +617,11 @@ def field_is_blacklisted(contents): break nargs += 1 if nargs < nargs_required: - log.debug('too few args: found {0}, but need at least {1} in "{2}"' + logger.debug('too few args: found {0}, but need at least {1} in "{2}"' .format(nargs, nargs_required, contents)) return False elif nargs > nargs_required + nargs_optional: - log.debug('too many args: found {0}, but need at most {1}+{2} in "{3}"' + logger.debug('too many args: found {0}, but need at most {1}+{2} in "{3}"' .format(nargs, nargs_required, nargs_optional, contents)) return False @@ -686,14 +631,14 @@ def field_is_blacklisted(contents): for word in words[1+nargs:]: if expect_arg: # this is an argument for the last switch if arg_choices and (word not in arg_choices): - log.debug('Found invalid switch argument "{0}" in "{1}"' + logger.debug('Found invalid switch argument "{0}" in "{1}"' .format(word, contents)) return False expect_arg = False arg_choices = [] # in general, do not enforce choices continue # "no further questions, your honor" elif not FIELD_SWITCH_REGEX.match(word): - log.debug('expected switch, found "{0}" in "{1}"' + logger.debug('expected switch, found "{0}" in "{1}"' .format(word, contents)) return False # we want a switch and we got a valid one @@ -715,7 +660,7 @@ def field_is_blacklisted(contents): if 'numeric' in sw_format: arg_choices = [] # too many choices to list them here else: - log.debug('unexpected switch {0} in "{1}"' + logger.debug('unexpected switch {0} in "{1}"' .format(switch, contents)) return False @@ -741,11 +686,11 @@ def process_xlsx(filepath): # binary parts, e.g. contained in .xlsb for subfile, content_type, handle in parser.iter_non_xml(): try: - logging.info('Parsing non-xml subfile {0} with content type {1}' + logger.info('Parsing non-xml subfile {0} with content type {1}' .format(subfile, content_type)) for record in xls_parser.parse_xlsb_part(handle, content_type, subfile): - logging.debug('{0}: {1}'.format(subfile, record)) + logger.debug('{0}: {1}'.format(subfile, record)) if isinstance(record, xls_parser.XlsbBeginSupBook) and \ record.link_type == \ xls_parser.XlsbBeginSupBook.LINK_TYPE_DDE: @@ -755,16 +700,16 @@ def process_xlsx(filepath): if content_type.startswith('application/vnd.ms-excel.') or \ content_type.startswith('application/vnd.ms-office.'): # pylint: disable=bad-indentation # should really be able to parse these either as xml or records - log_func = logging.warning + log_func = logger.warning elif content_type.startswith('image/') or content_type == \ 'application/vnd.openxmlformats-officedocument.' + \ 'spreadsheetml.printerSettings': # understandable that these are not record-base - log_func = logging.debug + log_func = logger.debug else: # default - log_func = logging.info - log_func('Failed to parse {0} of content type {1}' - .format(subfile, content_type)) + log_func = logger.info + log_func('Failed to parse {0} of content type {1} ("{2}")' + .format(subfile, content_type, str(exc))) # in any case: continue with next return u'\n'.join(dde_links) @@ -782,15 +727,15 @@ class RtfFieldParser(rtfobj.RtfParser): def open_destination(self, destination): if destination.cword == b'fldinst': - log.debug('*** Start field data at index %Xh' % destination.start) + logger.debug('*** Start field data at index %Xh' % destination.start) def close_destination(self, destination): if destination.cword == b'fldinst': - log.debug('*** Close field data at index %Xh' % self.index) - log.debug('Field text: %r' % destination.data) + logger.debug('*** Close field data at index %Xh' % self.index) + logger.debug('Field text: %r' % destination.data) # remove extra spaces and newline chars: field_clean = destination.data.translate(None, b'\r\n').strip() - log.debug('Cleaned Field text: %r' % field_clean) + logger.debug('Cleaned Field text: %r' % field_clean) self.fields.append(field_clean) def control_symbol(self, matchobject): @@ -812,7 +757,7 @@ def process_rtf(file_handle, field_filter_mode=None): rtfparser.parse() all_fields = [field.decode('ascii') for field in rtfparser.fields] # apply field command filter - log.debug('found {1} fields, filtering with mode "{0}"' + logger.debug('found {1} fields, filtering with mode "{0}"' .format(field_filter_mode, len(all_fields))) if field_filter_mode in (FIELD_FILTER_ALL, None): clean_fields = all_fields @@ -861,7 +806,7 @@ def process_csv(filepath): if is_small and not results: # easy to mis-sniff small files. Try different delimiters - log.debug('small file, no results; try all delimiters') + logger.debug('small file, no results; try all delimiters') file_handle.seek(0) other_delim = CSV_DELIMITERS.replace(dialect.delimiter, '') for delim in other_delim: @@ -869,12 +814,12 @@ def process_csv(filepath): file_handle.seek(0) results, _ = process_csv_dialect(file_handle, delim) except csv.Error: # e.g. sniffing fails - log.debug('failed to csv-parse with delimiter {0!r}' + logger.debug('failed to csv-parse with delimiter {0!r}' .format(delim)) if is_small and not results: # try whole file as single cell, since sniffing fails in this case - log.debug('last attempt: take whole file as single unquoted cell') + logger.debug('last attempt: take whole file as single unquoted cell') file_handle.seek(0) match = CSV_DDE_FORMAT.match(file_handle.read(CSV_SMALL_THRESH)) if match: @@ -890,7 +835,7 @@ def process_csv_dialect(file_handle, delimiters): dialect = csv.Sniffer().sniff(file_handle.read(CSV_SMALL_THRESH), delimiters=delimiters) dialect.strict = False # microsoft is never strict - log.debug('sniffed csv dialect with delimiter {0!r} ' + logger.debug('sniffed csv dialect with delimiter {0!r} ' 'and quote char {1!r}' .format(dialect.delimiter, dialect.quotechar)) @@ -932,7 +877,7 @@ def process_excel_xml(filepath): break if formula is None: continue - log.debug('found cell with formula {0}'.format(formula)) + logger.debug('found cell with formula {0}'.format(formula)) match = re.match(XML_DDE_FORMAT, formula) if match: dde_links.append(u' '.join(match.groups()[:2])) @@ -942,40 +887,51 @@ def process_excel_xml(filepath): def process_file(filepath, field_filter_mode=None): """ decides which of the process_* functions to call """ if olefile.isOleFile(filepath): - log.debug('Is OLE. Checking streams to see whether this is xls') + logger.debug('Is OLE. Checking streams to see whether this is xls') if xls_parser.is_xls(filepath): - log.debug('Process file as excel 2003 (xls)') + logger.debug('Process file as excel 2003 (xls)') return process_xls(filepath) + + # encrypted files also look like ole, even if office 2007+ (xml-based) + # so check for encryption, first + ole = olefile.OleFileIO(filepath, path_encoding=None) + oid = oleid.OleID(ole) + if oid.check_encrypted().value: + log.debug('is encrypted - raise error') + raise FileIsEncryptedError(filepath) + elif oid.check_powerpoint().value: + log.debug('is ppt - cannot have DDE') + return u'' else: - log.debug('Process file as word 2003 (doc)') - return process_doc(filepath) + logger.debug('Process file as word 2003 (doc)') + return process_doc(ole) with open(filepath, 'rb') as file_handle: if file_handle.read(4) == RTF_START: - log.debug('Process file as rtf') + logger.debug('Process file as rtf') return process_rtf(file_handle, field_filter_mode) try: doctype = ooxml.get_type(filepath) - log.debug('Detected file type: {0}'.format(doctype)) + logger.debug('Detected file type: {0}'.format(doctype)) except Exception as exc: - log.debug('Exception trying to xml-parse file: {0}'.format(exc)) + logger.debug('Exception trying to xml-parse file: {0}'.format(exc)) doctype = None if doctype == ooxml.DOCTYPE_EXCEL: - log.debug('Process file as excel 2007+ (xlsx)') + logger.debug('Process file as excel 2007+ (xlsx)') return process_xlsx(filepath) elif doctype in (ooxml.DOCTYPE_EXCEL_XML, ooxml.DOCTYPE_EXCEL_XML2003): - log.debug('Process file as xml from excel 2003/2007+') + logger.debug('Process file as xml from excel 2003/2007+') return process_excel_xml(filepath) elif doctype in (ooxml.DOCTYPE_WORD_XML, ooxml.DOCTYPE_WORD_XML2003): - log.debug('Process file as xml from word 2003/2007+') + logger.debug('Process file as xml from word 2003/2007+') return process_docx(filepath) elif doctype is None: - log.debug('Process file as csv') + logger.debug('Process file as csv') return process_csv(filepath) else: # could be docx; if not: this is the old default code path - log.debug('Process file as word 2007+ (docx)') + logger.debug('Process file as word 2007+ (docx)') return process_docx(filepath, field_filter_mode) @@ -993,27 +949,14 @@ def main(cmd_line_args=None): # Setup logging to the console: # here we use stdout instead of stderr by default, so that the output # can be redirected properly. - logging.basicConfig(level=LOG_LEVELS[args.loglevel], stream=sys.stdout, - format='%(levelname)-8s %(message)s') - # enable logging in the modules: - log.setLevel(logging.NOTSET) - - if args.json and args.loglevel.lower() == 'debug': - log.warning('Debug log output will not be json-compatible!') + log_helper.enable_logging(args.json, args.loglevel, stream=sys.stdout) if args.nounquote: global NO_QUOTES NO_QUOTES = True - if args.json: - jout = [] - jout.append(BANNER_JSON) - else: - # print banner with version - print(BANNER) - - if not args.json: - print('Opening file: %s' % args.filepath) + logger.print_str(BANNER) + logger.print_str('Opening file: %s' % args.filepath) text = '' return_code = 1 @@ -1021,22 +964,12 @@ def main(cmd_line_args=None): text = process_file(args.filepath, args.field_filter_mode) return_code = 0 except Exception as exc: - if args.json: - jout.append(dict(type='error', error=type(exc).__name__, - message=str(exc))) - else: - raise # re-raise last known exception, keeping trace intact - - if args.json: - for line in text.splitlines(): - if line.strip(): - jout.append(dict(type='dde-link', link=line.strip())) - json.dump(jout, sys.stdout, check_circular=False, indent=4) - print() # add a newline after closing "]" - return return_code # required if we catch an exception in json-mode - else: - print ('DDE Links:') - print(text) + logger.exception(exc.message) + + logger.print_str('DDE Links:') + logger.print_str(text) + + log_helper.end_logging() return return_code diff --git a/oletools/olebrowse.py b/oletools/olebrowse.py index ccfb0a9..cb77033 100644 --- a/oletools/olebrowse.py +++ b/oletools/olebrowse.py @@ -41,8 +41,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # 2012-09-17 v0.01 PL: - first version # 2014-11-29 v0.02 PL: - use olefile instead of OleFileIO_PL # 2017-04-26 v0.51 PL: - fixed absolute imports (issue #141) +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.51' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -68,8 +69,8 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty.easygui import easygui -from oletools.thirdparty import olefile +import easygui +import olefile from oletools import ezhexviewer ABOUT = '~ About olebrowse' diff --git a/oletools/oledir.py b/oletools/oledir.py index c04c836..6b6d530 100644 --- a/oletools/oledir.py +++ b/oletools/oledir.py @@ -50,8 +50,10 @@ from __future__ import print_function # - added support for zip files and wildcards # 2018-04-11 v0.53 PL: - added table displaying storage tree and CLSIDs # 2018-04-13 PL: - moved KNOWN_CLSIDS to common.clsid +# 2018-08-28 v0.54 PL: - olefile is now a dependency +# 2018-10-06 - colorclass is now a dependency -__version__ = '0.53' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -62,6 +64,13 @@ __version__ = '0.53' import sys, os, optparse +import olefile +import colorclass + +# On Windows, colorclass needs to be enabled: +if os.name == 'nt': + colorclass.Windows.enable(auto_colors=True) + # IMPORTANT: it should be possible to run oletools directly as scripts # in any directory without installing them with pip or setup.py. # In that case, relative imports are NOT usable. @@ -74,20 +83,6 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -# we also need the thirdparty dir for colorclass -# TODO: remove colorclass from thirdparty, make it a dependency -_thirdparty_dir = os.path.normpath(os.path.join(_thismodule_dir, 'thirdparty')) -# print('_thirdparty_dir = %r' % _thirdparty_dir) -if not _thirdparty_dir in sys.path: - sys.path.insert(0, _thirdparty_dir) - -import colorclass - -# On Windows, colorclass needs to be enabled: -if os.name == 'nt': - colorclass.Windows.enable(auto_colors=True) - -from oletools.thirdparty import olefile from oletools.thirdparty.tablestream import tablestream from oletools.thirdparty.xglob import xglob from oletools.common.clsid import KNOWN_CLSIDS @@ -236,6 +231,35 @@ def main(): # t.add_row((id, status, entry_type, name, left, right, child, hex(d.isectStart), d.size)) table.write_row((id, status, entry_type, name, left, right, child, '%X' % d.isectStart, d.size), colors=(None, status_color, etype_color, None, None, None, None, None, None)) + + table = tablestream.TableStream(column_width=[4, 28, 6, 38], + header_row=('id', 'Name', 'Size', 'CLSID'), + style=tablestream.TableStyleSlim) + rootname = ole.get_rootentry_name() + entry_id = 0 + clsid = ole.root.clsid + clsid_text, clsid_color = clsid_display(clsid) + table.write_row((entry_id, rootname, '-', clsid_text), + colors=(None, 'cyan', None, clsid_color)) + for entry in sorted(ole.listdir(storages=True)): + name = entry[-1] + # handle non-printable chars using repr(), remove quotes: + name = repr(name)[1:-1] + name_color = None + if ole.get_type(entry) in (olefile.STGTY_STORAGE, olefile.STGTY_ROOT): + name_color = 'cyan' + indented_name = ' '*(len(entry)-1) + name + entry_id = ole._find(entry) + try: + size = ole.get_size(entry) + except: + size = '-' + clsid = ole.getclsid(entry) + clsid_text, clsid_color = clsid_display(clsid) + table.write_row((entry_id, indented_name, size, clsid_text), + colors=(None, name_color, None, clsid_color)) + + ole.close() # print t diff --git a/oletools/oleform.py b/oletools/oleform.py index 8665e51..c5b3afb 100644 --- a/oletools/oleform.py +++ b/oletools/oleform.py @@ -114,8 +114,6 @@ class ExtendedStream(object): @classmethod def open(cls, ole_file, path): - # import oletools.thirdparty.olefile as olefile - # olefile.enable_logging() stream = ole_file.openstream(path) # print('Opening OLE stream %r - size: %d' % (path, stream.size)) # print('declared size: %d' % ole_file.get_size(path)) diff --git a/oletools/oleid.py b/oletools/oleid.py index f7547ef..5370503 100644 --- a/oletools/oleid.py +++ b/oletools/oleid.py @@ -6,9 +6,8 @@ oleid is a script to analyze OLE files such as MS Office documents (e.g. Word, Excel), to detect specific characteristics that could potentially indicate that the file is suspicious or malicious, in terms of security (e.g. malware). For example it can detect VBA macros, embedded Flash objects, fragmentation. -The results can be displayed or returned as XML for further processing. - -Usage: oleid.py +The results is displayed as ascii table (but could be returned or printed in +other formats like CSV, XML or JSON in future). oleid project website: http://www.decalage.info/python/oleid @@ -21,8 +20,8 @@ http://www.decalage.info/python/oletools # oleid is copyright (c) 2012-2018, Philippe Lagadec (http://www.decalage.info) # All rights reserved. # -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. @@ -30,16 +29,17 @@ http://www.decalage.info/python/oletools # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. # To improve Python 2+3 compatibility: from __future__ import print_function @@ -55,8 +55,11 @@ from __future__ import print_function # 2016-12-12 v0.51 PL: - fixed relative imports for Python 3 (issue #115) # 2017-04-26 PL: - fixed absolute imports (issue #141) # 2017-09-01 SA: - detect OpenXML encryption +# 2018-09-11 v0.54 PL: - olefile is now a dependency +# 2018-10-19 CH: - accept olefile as well as filename, return Indicators, +# improve encryption detection for ppt -__version__ = '0.53' +__version__ = '0.54dev4' #------------------------------------------------------------------------------ @@ -77,28 +80,27 @@ __version__ = '0.53' #=== IMPORTS ================================================================= -import optparse, sys, os, re, zlib, struct +import argparse, sys, re, zlib, struct +from os.path import dirname, abspath -# IMPORTANT: it should be possible to run oletools directly as scripts -# in any directory without installing them with pip or setup.py. -# In that case, relative imports are NOT usable. -# And to enable Python 2+3 compatibility, we need to use absolute imports, -# so we add the oletools parent folder to sys.path (absolute+normalized path): -_thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) -# print('_thismodule_dir = %r' % _thismodule_dir) -_parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) -# print('_parent_dir = %r' % _thirdparty_dir) -if not _parent_dir in sys.path: - sys.path.insert(0, _parent_dir) +# little hack to allow absolute imports even if oletools is not installed +# (required to run oletools directly as scripts in any directory). +try: + from oletools.thirdparty import prettytable +except ImportError: + PARENT_DIR = dirname(dirname(abspath(__file__))) + if PARENT_DIR not in sys.path: + sys.path.insert(0, PARENT_DIR) + del PARENT_DIR + from oletools.thirdparty import prettytable -from oletools.thirdparty import olefile -from oletools.thirdparty.prettytable import prettytable +import olefile #=== FUNCTIONS =============================================================== -def detect_flash (data): +def detect_flash(data): """ Detect Flash objects (SWF files) within a binary string of data return a list of (start_index, length, compressed) tuples, or [] if nothing @@ -140,7 +142,7 @@ def detect_flash (data): compressed_data = swf[8:] try: zlib.decompress(compressed_data) - except: + except Exception: continue # else we don't check anything at this stage, we only assume it is a # valid SWF. So there might be false positives for uncompressed SWF. @@ -151,9 +153,15 @@ def detect_flash (data): #=== CLASSES ================================================================= -class Indicator (object): +class Indicator(object): + """ + Piece of information of an :py:class:`OleID` object. + + Contains an ID, value, type, name and description. No other functionality. + """ - def __init__(self, _id, value=None, _type=bool, name=None, description=None): + def __init__(self, _id, value=None, _type=bool, name=None, + description=None): self.id = _id self.value = value self.type = _type @@ -163,21 +171,55 @@ class Indicator (object): self.description = description -class OleID: +class OleID(object): + """ + Summary of information about an OLE file - def __init__(self, filename): - self.filename = filename + Call :py:meth:`OleID.check` to gather all info on a given file or run one + of the `check_` functions to just get a specific piece of info. + """ + + def __init__(self, input_file): + """ + Create an OleID object + + This does not run any checks yet nor open the file. + + Can either give just a filename (as str), so OleID will check whether + that is a valid OLE file and create a :py:class:`olefile.OleFileIO` + object for it. Or you can give an already opened + :py:class:`olefile.OleFileIO` as argument to avoid re-opening (e.g. if + called from other oletools). + + If filename is given, only :py:meth:`OleID.check` opens the file. Other + functions will return None + """ + if isinstance(input_file, olefile.OleFileIO): + self.ole = input_file + self.filename = None + else: + self.filename = input_file + self.ole = None self.indicators = [] + self.suminfo_data = None def check(self): + """ + Open file and run all checks on it. + + :returns: list of all :py:class:`Indicator`s created + """ # check if it is actually an OLE file: oleformat = Indicator('ole_format', True, name='OLE format') self.indicators.append(oleformat) - if not olefile.isOleFile(self.filename): + if self.ole: + oleformat.value = True + elif not olefile.isOleFile(self.filename): oleformat.value = False return self.indicators - # parse file: - self.ole = olefile.OleFileIO(self.filename) + else: + # parse file: + self.ole = olefile.OleFileIO(self.filename) # checks: self.check_properties() self.check_encrypted() @@ -185,143 +227,274 @@ class OleID: self.check_excel() self.check_powerpoint() self.check_visio() - self.check_ObjectPool() + self.check_object_pool() self.check_flash() self.ole.close() return self.indicators - def check_properties (self): - suminfo = Indicator('has_suminfo', False, name='Has SummaryInformation stream') + def check_properties(self): + """ + Read summary information required for other check_* functions + + :returns: 2 :py:class:`Indicator`s (for presence of summary info and + application name) or None if file was not opened + """ + suminfo = Indicator('has_suminfo', False, + name='Has SummaryInformation stream') self.indicators.append(suminfo) - appname = Indicator('appname', 'unknown', _type=str, name='Application name') + appname = Indicator('appname', 'unknown', _type=str, + name='Application name') self.indicators.append(appname) - self.suminfo = {} - # check stream SummaryInformation + if not self.ole: + return None, None + self.suminfo_data = {} + # check stream SummaryInformation (not present e.g. in encrypted ppt) if self.ole.exists("\x05SummaryInformation"): suminfo.value = True - self.suminfo = self.ole.getproperties("\x05SummaryInformation") + self.suminfo_data = self.ole.getproperties("\x05SummaryInformation") # check application name: - appname.value = self.suminfo.get(0x12, 'unknown') - - def check_encrypted (self): + appname.value = self.suminfo_data.get(0x12, 'unknown') + return suminfo, appname + + def get_indicator(self, indicator_id): + """Helper function: returns an indicator if present (or None)""" + result = [indicator for indicator in self.indicators + if indicator.id == indicator_id] + if result: + return result[0] + else: + return None + + def check_encrypted(self): + """ + Check whether this file is encrypted. + + Might call check_properties. + + :returns: :py:class:`Indicator` for encryption or None if file was not + opened + """ # we keep the pointer to the indicator, can be modified by other checks: - self.encrypted = Indicator('encrypted', False, name='Encrypted') - self.indicators.append(self.encrypted) + encrypted = Indicator('encrypted', False, name='Encrypted') + self.indicators.append(encrypted) + if not self.ole: + return None # check if bit 1 of security field = 1: # (this field may be missing for Powerpoint2000, for example) - if 0x13 in self.suminfo: - if self.suminfo[0x13] & 1: - self.encrypted.value = True + if self.suminfo_data is None: + self.check_properties() + if 0x13 in self.suminfo_data: + if self.suminfo_data[0x13] & 1: + encrypted.value = True # check if this is an OpenXML encrypted file elif self.ole.exists('EncryptionInfo'): - self.encrypted.value = True - - def check_word (self): - word = Indicator('word', False, name='Word Document', - description='Contains a WordDocument stream, very likely to be a Microsoft Word Document.') + encrypted.value = True + # or an encrypted ppt file + if self.ole.exists('EncryptedSummary') and \ + not self.ole.exists('SummaryInformation'): + encrypted.value = True + return encrypted + + def check_word(self): + """ + Check whether this file is a word document + + If this finds evidence of encryption, will correct/add encryption + indicator. + + :returns: 2 :py:class:`Indicator`s (for word and vba_macro) or None if + file was not opened + """ + word = Indicator( + 'word', False, name='Word Document', + description='Contains a WordDocument stream, very likely to be a ' + 'Microsoft Word Document.') self.indicators.append(word) - self.macros = Indicator('vba_macros', False, name='VBA Macros') - self.indicators.append(self.macros) + macros = Indicator('vba_macros', False, name='VBA Macros') + self.indicators.append(macros) + if not self.ole: + return None, None if self.ole.exists('WordDocument'): word.value = True # check for Word-specific encryption flag: - s = self.ole.openstream(["WordDocument"]) - # pass header 10 bytes - s.read(10) - # read flag structure: - temp16 = struct.unpack("H", s.read(2))[0] - fEncrypted = (temp16 & 0x0100) >> 8 - if fEncrypted: - self.encrypted.value = True - s.close() + stream = None + try: + stream = self.ole.openstream(["WordDocument"]) + # pass header 10 bytes + stream.read(10) + # read flag structure: + temp16 = struct.unpack("H", stream.read(2))[0] + f_encrypted = (temp16 & 0x0100) >> 8 + if f_encrypted: + # correct encrypted indicator if present or add one + encrypt_ind = self.get_indicator('encrypted') + if encrypt_ind: + encrypt_ind.value = True + else: + self.indicators.append('encrypted', True, name='Encrypted') + except Exception: + raise + finally: + if stream is not None: + stream.close() # check for VBA macros: if self.ole.exists('Macros'): - self.macros.value = True + macros.value = True + return word, macros + + def check_excel(self): + """ + Check whether this file is an excel workbook. + + If this finds macros, will add/correct macro indicator. - def check_excel (self): - excel = Indicator('excel', False, name='Excel Workbook', - description='Contains a Workbook or Book stream, very likely to be a Microsoft Excel Workbook.') + see also: :py:func:`xls_parser.is_xls` + + :returns: :py:class:`Indicator` for excel or (None, None) if file was + not opened + """ + excel = Indicator( + 'excel', False, name='Excel Workbook', + description='Contains a Workbook or Book stream, very likely to be ' + 'a Microsoft Excel Workbook.') self.indicators.append(excel) + if not self.ole: + return None #self.macros = Indicator('vba_macros', False, name='VBA Macros') #self.indicators.append(self.macros) if self.ole.exists('Workbook') or self.ole.exists('Book'): excel.value = True # check for VBA macros: if self.ole.exists('_VBA_PROJECT_CUR'): - self.macros.value = True - - def check_powerpoint (self): - ppt = Indicator('ppt', False, name='PowerPoint Presentation', - description='Contains a PowerPoint Document stream, very likely to be a Microsoft PowerPoint Presentation.') + # correct macro indicator if present or add one + macro_ind = self.get_indicator('vba_macros') + if macro_ind: + macro_ind.value = True + else: + self.indicators.append('vba_macros', True, + name='VBA Macros') + return excel + + def check_powerpoint(self): + """ + Check whether this file is a powerpoint presentation + + see also: :py:func:`ppt_record_parser.is_ppt` + + :returns: :py:class:`Indicator` for whether this is a powerpoint + presentation or not or None if file was not opened + """ + ppt = Indicator( + 'ppt', False, name='PowerPoint Presentation', + description='Contains a PowerPoint Document stream, very likely to ' + 'be a Microsoft PowerPoint Presentation.') self.indicators.append(ppt) + if not self.ole: + return None if self.ole.exists('PowerPoint Document'): ppt.value = True - - def check_visio (self): - visio = Indicator('visio', False, name='Visio Drawing', - description='Contains a VisioDocument stream, very likely to be a Microsoft Visio Drawing.') + return ppt + + def check_visio(self): + """Check whether this file is a visio drawing""" + visio = Indicator( + 'visio', False, name='Visio Drawing', + description='Contains a VisioDocument stream, very likely to be a ' + 'Microsoft Visio Drawing.') self.indicators.append(visio) + if not self.ole: + return None if self.ole.exists('VisioDocument'): visio.value = True + return visio + + def check_object_pool(self): + """ + Check whether this file contains an ObjectPool stream. + + Such a stream would be a strong indicator for embedded objects or files. - def check_ObjectPool (self): - objpool = Indicator('ObjectPool', False, name='ObjectPool', - description='Contains an ObjectPool stream, very likely to contain embedded OLE objects or files.') + :returns: :py:class:`Indicator` for ObjectPool stream or None if file + was not opened + """ + objpool = Indicator( + 'ObjectPool', False, name='ObjectPool', + description='Contains an ObjectPool stream, very likely to contain ' + 'embedded OLE objects or files.') self.indicators.append(objpool) + if not self.ole: + return None if self.ole.exists('ObjectPool'): objpool.value = True - - - def check_flash (self): - flash = Indicator('flash', 0, _type=int, name='Flash objects', - description='Number of embedded Flash objects (SWF files) detected in OLE streams. Not 100% accurate, there may be false positives.') + return objpool + + def check_flash(self): + """ + Check whether this file contains flash objects + + :returns: :py:class:`Indicator` for count of flash objects or None if + file was not opened + """ + flash = Indicator( + 'flash', 0, _type=int, name='Flash objects', + description='Number of embedded Flash objects (SWF files) detected ' + 'in OLE streams. Not 100% accurate, there may be false ' + 'positives.') self.indicators.append(flash) + if not self.ole: + return None for stream in self.ole.listdir(): data = self.ole.openstream(stream).read() found = detect_flash(data) # just add to the count of Flash objects: flash.value += len(found) #print stream, found + return flash #=== MAIN ================================================================= def main(): + """Called when running this file as script. Shows all info on input file.""" # print banner with version - print ('oleid %s - http://decalage.info/oletools' % __version__) - print ('THIS IS WORK IN PROGRESS - Check updates regularly!') - print ('Please report any issue at https://github.com/decalage2/oletools/issues') - print ('') + print('oleid %s - http://decalage.info/oletools' % __version__) + print('THIS IS WORK IN PROGRESS - Check updates regularly!') + print('Please report any issue at ' + 'https://github.com/decalage2/oletools/issues') + print('') - usage = 'usage: %prog [options] ' - parser = optparse.OptionParser(usage=__doc__ + '\n' + usage) -## parser.add_option('-o', '--ole', action='store_true', dest='ole', help='Parse an OLE file (e.g. Word, Excel) to look for SWF in each stream') + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('input', type=str, nargs='*', metavar='FILE', + help='Name of files to process') + # parser.add_argument('-o', '--ole', action='store_true', dest='ole', + # help='Parse an OLE file (e.g. Word, Excel) to look for ' + # 'SWF in each stream') - (options, args) = parser.parse_args() + args = parser.parse_args() # Print help if no argurments are passed - if len(args) == 0: + if len(args.input) == 0: parser.print_help() return - for filename in args: + for filename in args.input: print('Filename:', filename) oleid = OleID(filename) indicators = oleid.check() #TODO: add description #TODO: highlight suspicious indicators - t = prettytable.PrettyTable(['Indicator', 'Value']) - t.align = 'l' - t.max_width = 39 - #t.border = False + table = prettytable.PrettyTable(['Indicator', 'Value']) + table.align = 'l' + table.max_width = 39 + table.border = False for indicator in indicators: #print '%s: %s' % (indicator.name, indicator.value) - t.add_row((indicator.name, indicator.value)) + table.add_row((indicator.name, indicator.value)) - print(t) - print ('') + print(table) + print('') if __name__ == '__main__': main() diff --git a/oletools/olemap.py b/oletools/olemap.py index 6f8f51f..d7c9fa8 100644 --- a/oletools/olemap.py +++ b/oletools/olemap.py @@ -13,7 +13,7 @@ http://www.decalage.info/python/oletools #=== LICENSE ================================================================== -# olemap is copyright (c) 2015-2017 Philippe Lagadec (http://www.decalage.info) +# olemap is copyright (c) 2015-2018 Philippe Lagadec (http://www.decalage.info) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, @@ -51,9 +51,9 @@ http://www.decalage.info/python/oletools # 2017-03-22 PL: - added extra data detection, completed header display # 2017-03-23 PL: - only display the header by default # - added option --exdata to display extra data in hex +# 2018-08-28 v0.54 PL: - olefile is now a dependency - -__version__ = '0.51' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -74,7 +74,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty.olefile import olefile +import olefile from oletools.thirdparty.tablestream import tablestream from oletools.thirdparty.xglob import xglob from oletools.ezhexviewer import hexdump3 diff --git a/oletools/olemeta.py b/oletools/olemeta.py index 7ae8b3e..194da7b 100644 --- a/oletools/olemeta.py +++ b/oletools/olemeta.py @@ -15,7 +15,7 @@ http://www.decalage.info/python/oletools #=== LICENSE ================================================================= -# olemeta is copyright (c) 2013-2017, Philippe Lagadec (http://www.decalage.info) +# olemeta is copyright (c) 2013-2018, Philippe Lagadec (http://www.decalage.info) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, @@ -49,8 +49,9 @@ http://www.decalage.info/python/oletools # 2016-10-28 PL: - removed the UTF8 codec for console display # 2017-04-26 v0.51 PL: - fixed absolute imports (issue #141) # 2017-05-04 PL: - added optparse and xglob (issue #141) +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.51' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -75,7 +76,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty import olefile +import olefile from oletools.thirdparty import xglob from oletools.thirdparty.tablestream import tablestream diff --git a/oletools/oleobj.py b/oletools/oleobj.py index 47a0bfb..a0f5e49 100644 --- a/oletools/oleobj.py +++ b/oletools/oleobj.py @@ -50,7 +50,9 @@ import os import re import sys import io -from zipfile import is_zipfile, ZipFile +from zipfile import is_zipfile + +import olefile # IMPORTANT: it should be possible to run oletools directly as scripts # in any directory without installing them with pip or setup.py. @@ -58,7 +60,7 @@ from zipfile import is_zipfile, ZipFile # And to enable Python 2+3 compatibility, we need to use absolute imports, # so we add the oletools parent folder to sys.path (absolute+normalized path): try: - from oletools.thirdparty import olefile + from oletools.thirdparty import xglob except ImportError: import os.path PARENT_DIR = os.path.normpath(os.path.dirname(os.path.dirname( @@ -66,11 +68,11 @@ except ImportError: if PARENT_DIR not in sys.path: sys.path.insert(0, PARENT_DIR) del PARENT_DIR - from oletools.thirdparty import olefile -from oletools.thirdparty import xglob + from oletools.thirdparty import xglob + from oletools.ppt_record_parser import (is_ppt, PptFile, PptRecordExOleVbaActiveXAtom) -from oletools.ooxml import ZipSubFile +from oletools.ooxml import XmlParser # ----------------------------------------------------------------------------- # CHANGELOG: @@ -84,8 +86,10 @@ from oletools.ooxml import ZipSubFile # 2018-01-18 v0.52 CH: - added support for zipped-xml-based types (docx, pptx, # xlsx), and ppt # 2018-03-27 PL: - fixed issue #274 in read_length_prefixed_string +# 2018-09-11 v0.54 PL: - olefile is now a dependency +# 2018-10-30 SA: - added detection of external links (PR #317) -__version__ = '0.52.4' +__version__ = '0.54dev4' # ----------------------------------------------------------------------------- # TODO: @@ -178,6 +182,7 @@ else: NULL_CHAR = 0 # pylint: disable=redefined-variable-type xrange = range # pylint: disable=redefined-builtin, invalid-name +OOXML_RELATIONSHIP_TAG = '{http://schemas.openxmlformats.org/package/2006/relationships}Relationship' # === GLOBAL VARIABLES ======================================================== @@ -203,6 +208,24 @@ RETURN_ERR_ARGS = 2 # reserve for OptionParser.parse_args RETURN_ERR_STREAM = 4 # error opening/parsing a stream RETURN_ERR_DUMP = 8 # error dumping data from stream to file +# Not sure if they can all be "External", but just in case +BLACKLISTED_RELATIONSHIP_TYPES = [ + 'attachedTemplate', + 'externalLink', + 'externalLinkPath', + 'externalReference' + 'frame' + 'hyperlink', + 'officeDocument', + 'oleObject', + 'package', + 'slideUpdateUrl', + 'slideMaster', + 'slide', + 'slideUpdateInfo', + 'subDocument', + 'worksheet' +] # === FUNCTIONS =============================================================== @@ -596,7 +619,7 @@ class FakeFile(io.RawIOBase): return self.pos -def find_ole(filename, data): +def find_ole(filename, data, xml_parser=None): """ try to open somehow as zip/ole/rtf/... ; yield None if fail If data is given, filename is (mostly) ignored. @@ -628,34 +651,40 @@ def find_ole(filename, data): log.info('is ole file: ' + filename) ole = olefile.OleFileIO(arg_for_ole) yield ole - elif is_zipfile(arg_for_zip): + elif xml_parser is not None or is_zipfile(arg_for_zip): + # keep compatibility with 3rd-party code that calls this function + # directly without providing an XmlParser instance + if xml_parser is None: + xml_parser = XmlParser(arg_for_zip) + # force iteration so XmlParser.iter_non_xml() returns data + [x for x in xml_parser.iter_xml()] + log.info('is zip file: ' + filename) - zipper = ZipFile(arg_for_zip, 'r') - for subfile in zipper.namelist(): - head = b'' + # we looped through the XML files before, now we can + # iterate the non-XML files looking for ole objects + for subfile, _, file_handle in xml_parser.iter_non_xml(): try: - with zipper.open(subfile) as file_handle: - head = file_handle.read(len(olefile.MAGIC)) + head = file_handle.read(len(olefile.MAGIC)) except RuntimeError: log.error('zip is encrypted: ' + filename) yield None continue if head == olefile.MAGIC: + file_handle.seek(0) log.info(' unzipping ole: ' + subfile) - with ZipSubFile(zipper, subfile) as file_handle: - try: - ole = olefile.OleFileIO(file_handle) - yield ole - except IOError: - log.warning('Error reading data from {0}/{1} or ' - 'interpreting it as OLE object' - .format(filename, subfile)) - log.debug('', exc_info=True) - finally: - if ole is not None: - ole.close() - ole = None + try: + ole = olefile.OleFileIO(file_handle) + yield ole + except IOError: + log.warning('Error reading data from {0}/{1} or ' + 'interpreting it as OLE object' + .format(filename, subfile)) + log.debug('', exc_info=True) + finally: + if ole is not None: + ole.close() + ole = None else: log.debug('unzip skip: ' + subfile) else: @@ -671,6 +700,22 @@ def find_ole(filename, data): ole.close() +def find_external_relationships(xml_parser): + """ iterate XML files looking for relationships to external objects + """ + for _, elem, _ in xml_parser.iter_xml(None, False, OOXML_RELATIONSHIP_TAG): + try: + if elem.attrib['TargetMode'] == 'External': + relationship_type = elem.attrib['Type'].rsplit('/', 1)[1] + + if relationship_type in BLACKLISTED_RELATIONSHIP_TYPES: + yield relationship_type, elem.attrib['Target'] + except (AttributeError, KeyError): + # ignore missing attributes - Word won't detect + # external links anyway + pass + + def process_file(filename, data, output_dir=None): """ find embedded objects in given file @@ -703,10 +748,19 @@ def process_file(filename, data, output_dir=None): err_dumping = False did_dump = False + xml_parser = None + if is_zipfile(filename): + log.info('file is a OOXML file, looking for relationships with external links') + xml_parser = XmlParser(filename) + for relationship, target in find_external_relationships(xml_parser): + did_dump = True + print("Found relationship '%s' with external link %s" % (relationship, target)) + + # look for ole files inside file (e.g. unzip docx) # have to finish work on every ole stream inside iteration, since handles # are closed in find_ole - for ole in find_ole(filename, data): + for ole in find_ole(filename, data, xml_parser): if ole is None: # no ole file found continue diff --git a/oletools/oletimes.py b/oletools/oletimes.py index a00ce3d..fa9f5b5 100644 --- a/oletools/oletimes.py +++ b/oletools/oletimes.py @@ -50,8 +50,9 @@ http://www.decalage.info/python/oletools # 2016-09-05 PL: - added main entry point for setup.py # 2017-05-03 v0.51 PL: - fixed absolute imports (issue #141) # 2017-05-04 PL: - added optparse and xglob (issue #141) +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.51' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -75,7 +76,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty import olefile +import olefile from oletools.thirdparty import xglob from oletools.thirdparty.prettytable import prettytable diff --git a/oletools/olevba.py b/oletools/olevba.py index 32ae0dc..d7cd047 100644 --- a/oletools/olevba.py +++ b/oletools/olevba.py @@ -14,6 +14,7 @@ Supported formats: - Word 2003 XML (.xml) - Word/Excel Single File Web Page / MHTML (.mht) - Publisher (.pub) +- raises an error if run with files encrypted using MS Crypto API RC4 Author: Philippe Lagadec - http://www.decalage.info License: BSD, see source code or documentation @@ -206,8 +207,11 @@ from __future__ import print_function # 2018-03-19 PL: - removed pyparsing from the thirdparty subfolder # 2018-04-15 v0.53 PL: - added support for Word/PowerPoint 2007+ XML (FlatOPC) # (issue #283) +# 2018-09-11 v0.54 PL: - olefile is now a dependency +# 2018-10-08 PL: - replace backspace before printing to console (issue #358) +# 2018-10-25 CH: - detect encryption and raise error if detected -__version__ = '0.53.1' +__version__ = '0.54dev4' #------------------------------------------------------------------------------ # TODO: @@ -245,7 +249,10 @@ import sys import os import logging import struct -import cStringIO +try: + from cStringIO import StringIO +except ImportError: + from io import StringIO import math import zipfile import re @@ -274,6 +281,12 @@ except ImportError: + "see http://codespeak.net/lxml " \ + "or http://effbot.org/zone/element-index.htm") +import colorclass + +# On Windows, colorclass needs to be enabled: +if os.name == 'nt': + colorclass.Windows.enable(auto_colors=True) + # IMPORTANT: it should be possible to run oletools directly as scripts # in any directory without installing them with pip or setup.py. @@ -287,7 +300,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty import olefile +import olefile from oletools.thirdparty.prettytable import prettytable from oletools.thirdparty.xglob import xglob, PathNotFoundException from pyparsing import \ @@ -298,6 +311,8 @@ from pyparsing import \ from oletools import ppt_parser from oletools import oleform from oletools import rtfobj +from oletools import oleid +from oletools.common.errors import FileIsEncryptedError # monkeypatch email to fix issue #32: @@ -461,6 +476,7 @@ RETURN_OPEN_ERROR = 5 RETURN_PARSE_ERROR = 6 RETURN_SEVERAL_ERRS = 7 RETURN_UNEXPECTED = 8 +RETURN_ENCRYPTED = 9 # MAC codepages (from http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python) MAC_CODEPAGES = { @@ -697,6 +713,12 @@ SUSPICIOUS_KEYWORDS = { ('VBProject', 'VBComponents', 'CodeModule', 'AddFromString'), } +# Suspicious Keywords to be searched for directly as strings, without regex +SUSPICIOUS_KEYWORDS_NOREGEX = { + 'May use special characters such as backspace to obfuscate code when printed on the console': + ('\b',), +} + # Regular Expression for a URL: # http://en.wikipedia.org/wiki/Uniform_resource_locator # http://www.w3.org/Addressing/URL/uri-spec.html @@ -1351,7 +1373,7 @@ def _extract_vba(ole, vba_root, project_path, dir_path, relaxed=False): else: raise UnexpectedDataError(dir_path, name, expected, value) - dir_stream = cStringIO.StringIO(decompress_stream(dir_compressed)) + dir_stream = StringIO(decompress_stream(dir_compressed)) # PROJECTSYSKIND Record projectsyskind_id = struct.unpack("=0 and i<=255: return VbaExpressionString(chr(i)) else: - return VbaExpressionString(unichr(i).encode('utf-8', 'backslashreplace')) + return VbaExpressionString(chr(i).encode('utf-8', 'backslashreplace')) except ValueError: log.exception('ERROR: incorrect parameter value for chr(): %r' % i) return VbaExpressionString('Chr(%r)' % i) @@ -2355,6 +2365,12 @@ class VBA_Parser(object): # This looks like an OLE file self.open_ole(_file) + # check whether file is encrypted (need to do this before try ppt) + log.debug('Check encryption of ole file') + crypt_indicator = oleid.OleID(self.ole_file).check_encrypted() + if crypt_indicator.value: + raise FileIsEncryptedError(filename) + # if this worked, try whether it is a ppt file (special ole file) self.open_ppt() if self.type is None and is_zipfile(_file): @@ -2835,7 +2851,7 @@ class VBA_Parser(object): log.debug('%r...[much more data]...%r' % (data[:100], data[-50:])) else: log.debug(repr(data)) - if 'Attribut' in data.decode('utf-8', 'ignore'): + if 'Attribut\x00' in data.decode('utf-8', 'ignore'): log.debug('Found VBA compressed code') self.contains_macros = True except IOError as exc: @@ -3589,6 +3605,18 @@ def main(cmd_line_args=None): % (filename, exc.orig_exc)) return_code = RETURN_PARSE_ERROR if return_code == 0 \ else RETURN_SEVERAL_ERRS + except FileIsEncryptedError as exc: + if options.output_mode in ('triage', 'unspecified'): + print('%-12s %s - File is encrypted' % ('!ERROR', filename)) + elif options.output_mode == 'json': + print_json(file=filename, type='error', + error=type(exc).__name__, message=str(exc)) + else: + log.exception('File %s is encrypted!' % (filename)) + return_code = RETURN_ENCRYPTED if return_code == 0 \ + else RETURN_SEVERAL_ERRS + # Here we do not close the vba_parser, because process_file may need it below. + finally: if vba_parser is not None: vba_parser.close() diff --git a/oletools/ooxml.py b/oletools/ooxml.py index 2ec1ba2..174c46d 100644 --- a/oletools/ooxml.py +++ b/oletools/ooxml.py @@ -9,12 +9,14 @@ See also: Notes on Microsoft's implementation of ECMA-376: [MS-0E376] TODO: may have to tell apart single xml types: office2003 looks much different than 2006+ --> DOCTYPE_*_XML2003 +TODO: check what is duplicate here with oleid, maybe merge some day? +TODO: "xml2003" == "flatopc"? .. codeauthor:: Intra2net AG """ import sys -import logging +from oletools.common.log_helper import log_helper from zipfile import ZipFile, BadZipfile, is_zipfile from os.path import splitext import io @@ -27,6 +29,7 @@ try: except ImportError: import xml.etree.cElementTree as ET +logger = log_helper.get_or_create_silent_logger('ooxml') #: subfiles that have to be part of every ooxml file FILE_CONTENT_TYPES = '[Content_Types].xml' @@ -142,7 +145,7 @@ def get_type(filename): is_xls = False is_ppt = False for _, elem, _ in parser.iter_xml(FILE_CONTENT_TYPES): - logging.debug(u' ' + debug_str(elem)) + logger.debug(u' ' + debug_str(elem)) try: content_type = elem.attrib['ContentType'] except KeyError: # ContentType not an attr @@ -160,7 +163,7 @@ def get_type(filename): if not is_doc and not is_xls and not is_ppt: return DOCTYPE_NONE else: - logging.warning('Encountered contradictory content types') + logger.warning('Encountered contradictory content types') return DOCTYPE_MIXED @@ -220,7 +223,7 @@ class ZipSubFile(object): self.name = filename if size is None: self.size = container.getinfo(filename).file_size - logging.debug('zip stream has size {0}'.format(self.size)) + logger.debug('zip stream has size {0}'.format(self.size)) else: self.size = size if 'w' in mode.lower(): @@ -484,10 +487,10 @@ class XmlParser(object): want_tags = [] elif isstr(tags): want_tags = [tags, ] - logging.debug('looking for tags: {0}'.format(tags)) + logger.debug('looking for tags: {0}'.format(tags)) else: want_tags = tags - logging.debug('looking for tags: {0}'.format(tags)) + logger.debug('looking for tags: {0}'.format(tags)) for subfile, handle in self.iter_files(subfiles): events = ('start', 'end') @@ -499,7 +502,7 @@ class XmlParser(object): continue if event == 'start': if elem.tag in want_tags: - logging.debug('remember start of tag {0} at {1}' + logger.debug('remember start of tag {0} at {1}' .format(elem.tag, depth)) inside_tags.append((elem.tag, depth)) depth += 1 @@ -515,18 +518,18 @@ class XmlParser(object): if inside_tags[-1] == curr_tag: inside_tags.pop() else: - logging.error('found end for wanted tag {0} ' + logger.error('found end for wanted tag {0} ' 'but last start tag {1} does not' ' match'.format(curr_tag, inside_tags[-1])) # try to recover: close all deeper tags while inside_tags and \ inside_tags[-1][1] >= depth: - logging.debug('recover: pop {0}' + logger.debug('recover: pop {0}' .format(inside_tags[-1])) inside_tags.pop() except IndexError: # no inside_tag[-1] - logging.error('found end of {0} at depth {1} but ' + logger.error('found end of {0} at depth {1} but ' 'no start event') # yield element if is_wanted or not want_tags: @@ -543,12 +546,12 @@ class XmlParser(object): if subfile is None: # this is no zip subfile but single xml raise BadOOXML(self.filename, 'is neither zip nor xml') elif subfile.endswith('.xml'): - logger = logging.warning + log = logger.warning else: - logger = logging.debug - logger(' xml-parsing for {0} failed ({1}). ' - .format(subfile, err) + - 'Run iter_non_xml to investigate.') + log = logger.debug + log(' xml-parsing for {0} failed ({1}). ' + .format(subfile, err) + + 'Run iter_non_xml to investigate.') assert(depth == 0) def get_content_types(self): @@ -571,14 +574,14 @@ class XmlParser(object): if extension.startswith('.'): extension = extension[1:] defaults.append((extension, elem.attrib['ContentType'])) - logging.debug('found content type for extension {0[0]}: {0[1]}' + logger.debug('found content type for extension {0[0]}: {0[1]}' .format(defaults[-1])) elif elem.tag.endswith('Override'): subfile = elem.attrib['PartName'] if subfile.startswith('/'): subfile = subfile[1:] files.append((subfile, elem.attrib['ContentType'])) - logging.debug('found content type for subfile {0[0]}: {0[1]}' + logger.debug('found content type for subfile {0[0]}: {0[1]}' .format(files[-1])) return dict(files), dict(defaults) @@ -595,14 +598,14 @@ class XmlParser(object): To handle binary parts of an xlsb file, use xls_parser.parse_xlsb_part """ if not self.did_iter_all: - logging.warning('Did not iterate through complete file. ' + logger.warning('Did not iterate through complete file. ' 'Should run iter_xml() without args, first.') if not self.subfiles_no_xml: - raise StopIteration() + return # case of single xml files (office 2003+) if self.is_single_xml(): - raise StopIteration() # "return" + return content_types, content_defaults = self.get_content_types() @@ -628,7 +631,7 @@ def test(): see module doc for more info """ - logging.basicConfig(level=logging.DEBUG) + log_helper.enable_logging(False, logger.DEBUG) if len(sys.argv) != 2: print(u'To test this code, give me a single file as arg') return 2 @@ -641,12 +644,15 @@ def test(): for subfile, elem, depth in parser.iter_xml(): if depth < 4: print(u'{0} {1}{2}'.format(subfile, ' ' * depth, debug_str(elem))) - for index, (subfile, content_type) in enumerate(parser.iter_non_xml()): + for index, (subfile, content_type, _) in enumerate(parser.iter_non_xml()): print(u'Non-XML subfile: {0} of type {1}' .format(subfile, content_type or u'unknown')) if index > 100: print(u'...') break + + log_helper.end_logging() + return 0 diff --git a/oletools/ppt_parser.py b/oletools/ppt_parser.py index 18b1945..a98b9bc 100644 --- a/oletools/ppt_parser.py +++ b/oletools/ppt_parser.py @@ -41,8 +41,9 @@ file structure and will replace this module some time soon! # 2016-09-13 PL: - fixed olefile import for Python 2+3 # - fixed format strings for Python 2.6 (issue #75) # 2017-04-23 v0.51 PL: - fixed absolute imports and issue #101 +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.51' +__version__ = '0.54dev1' # --- IMPORTS ------------------------------------------------------------------ @@ -66,11 +67,41 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) if not _parent_dir in sys.path: sys.path.insert(0, _parent_dir) -from oletools.thirdparty.olefile import olefile +import olefile + + +# TODO: this is a temporary fix until all logging features are unified in oletools +def get_logger(name, level=logging.CRITICAL+1): + """ + Create a suitable logger object for this module. + The goal is not to change settings of the root logger, to avoid getting + other modules' logs on the screen. + If a logger exists with same name, reuse it. (Else it would have duplicate + handlers and messages would be doubled.) + The level is set to CRITICAL+1 by default, to avoid any logging. + """ + # First, test if there is already a logger with the same name, else it + # will generate duplicate messages (due to duplicate handlers): + if name in logging.Logger.manager.loggerDict: + #NOTE: another less intrusive but more "hackish" solution would be to + # use getLogger then test if its effective level is not default. + logger = logging.getLogger(name) + # make sure level is OK: + logger.setLevel(level) + return logger + # get a new logger: + logger = logging.getLogger(name) + # only add a NullHandler for this logger, it is up to the application + # to configure its own logging: + logger.addHandler(logging.NullHandler()) + logger.setLevel(level) + return logger + + # a global logger object used for debugging: -log = olefile.get_logger('ppt') +log = get_logger('ppt') def enable_logging(): diff --git a/oletools/ppt_record_parser.py b/oletools/ppt_record_parser.py index 487d5a8..acdc0dd 100644 --- a/oletools/ppt_record_parser.py +++ b/oletools/ppt_record_parser.py @@ -63,6 +63,7 @@ except ImportError: sys.path.insert(0, PARENT_DIR) del PARENT_DIR from oletools import record_base +from oletools.common.errors import FileIsEncryptedError # types of relevant records (there are much more than listed here) @@ -147,13 +148,17 @@ def is_ppt(filename): Param filename can be anything that OleFileIO constructor accepts: name of file or file data or data stream. + + see also: oleid.OleID.check_powerpoint """ have_current_user = False have_user_edit = False have_persist_dir = False have_document_container = False + ppt_file = None try: - for stream in PptFile(filename).iter_streams(): + ppt_file = PptFile(filename) + for stream in ppt_file.iter_streams(): if stream.name == 'Current User': for record in stream.iter_records(): if isinstance(record, PptRecordCurrentUser): @@ -176,6 +181,11 @@ def is_ppt(filename): return True else: # ignore other streams/storages since they are optional continue + except FileIsEncryptedError: + assert ppt_file is not None, \ + 'Encryption error should not be raised from just opening OLE file.' + # just rely on stream names, copied from oleid + return ppt_file.exists('PowerPoint Document') except Exception: pass return False diff --git a/oletools/pyxswf.py b/oletools/pyxswf.py index c6b6030..27f1254 100644 --- a/oletools/pyxswf.py +++ b/oletools/pyxswf.py @@ -57,8 +57,9 @@ http://www.decalage.info/python/oletools # 2016-09-06 v0.50 PL: - updated to match the rtfobj API # 2016-10-25 PL: - fixed print for Python 3 # 2016-11-01 PL: - replaced StringIO by BytesIO for Python 3 +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.50' +__version__ = '0.54dev1' #------------------------------------------------------------------------------ # TODO: @@ -78,7 +79,7 @@ import optparse, sys, os from . import rtfobj from io import BytesIO from .thirdparty.xxxswf import xxxswf -from .thirdparty import olefile +import olefile #=== MAIN ================================================================= diff --git a/oletools/record_base.py b/oletools/record_base.py index ad7f388..49b3cb5 100644 --- a/oletools/record_base.py +++ b/oletools/record_base.py @@ -36,11 +36,15 @@ from __future__ import print_function # ----------------------------------------------------------------------------- # CHANGELOG: # 2017-11-30 v0.01 CH: - first version based on xls_parser +# 2018-09-11 v0.54 PL: - olefile is now a dependency + +__version__ = '0.54dev1' # ----------------------------------------------------------------------------- # TODO: # - read DocumentSummaryInformation first to get more info about streams # (maybe content type or so; identify streams that are never record-based) +# Or use oleid to avoid same functionality in several files # - think about integrating this with olefile itself # ----------------------------------------------------------------------------- @@ -57,17 +61,19 @@ import os.path from io import SEEK_CUR import logging +import olefile + try: - from oletools.thirdparty import olefile + from oletools.common.errors import FileIsEncryptedError except ImportError: # little hack to allow absolute imports even if oletools is not installed. - # Copied from olevba.py PARENT_DIR = os.path.normpath(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) if PARENT_DIR not in sys.path: sys.path.insert(0, PARENT_DIR) del PARENT_DIR - from oletools.thirdparty import olefile + from oletools.common.errors import FileIsEncryptedError +from oletools import oleid ############################################################################### @@ -118,6 +124,12 @@ class OleRecordFile(olefile.OleFileIO): Subclass of OleFileIO! """ + def open(self, filename, *args, **kwargs): + """Call OleFileIO.open, raise error if is encrypted.""" + #super(OleRecordFile, self).open(filename, *args, **kwargs) + OleFileIO.open(self, filename, *args, **kwargs) + self.is_encrypted = oleid.OleID(self).check_encrypted().value + @classmethod def stream_class_for_name(cls, stream_name): """ helper for iter_streams, must be overwritten in subclasses @@ -149,7 +161,8 @@ class OleRecordFile(olefile.OleFileIO): stream = clz(self._open(direntry.isectStart, direntry.size), direntry.size, None if is_orphan else direntry.name, - direntry.entry_type) + direntry.entry_type, + self.is_encrypted) yield stream stream.close() @@ -162,13 +175,14 @@ class OleRecordStream(object): abstract base class """ - def __init__(self, stream, size, name, stream_type): + def __init__(self, stream, size, name, stream_type, is_encrypted=False): self.stream = stream self.size = size self.name = name if stream_type not in ENTRY_TYPE2STR: raise ValueError('Unknown stream type: {0}'.format(stream_type)) self.stream_type = stream_type + self.is_encrypted = is_encrypted def read_record_head(self): """ read first few bytes of record to determine size and type @@ -197,6 +211,9 @@ class OleRecordStream(object): Stream must be positioned at start of records (e.g. start of stream). """ + if self.is_encrypted: + raise FileIsEncryptedError() + while True: # unpacking as in olevba._extract_vba pos = self.stream.tell() @@ -241,6 +258,8 @@ class OleSummaryInformationStream(OleRecordStream): Do nothing so far. OleFileIO reads quite some info from this. For more info see [MS-OSHARED] 2.3.3 and [MS-OLEPS] 2.21 and references therein. + + See also: info read in oleid.py. """ def iter_records(self, fill_data=False): """ yields nothing, stops at once """ diff --git a/oletools/rtfobj.py b/oletools/rtfobj.py index c596f9b..7179045 100644 --- a/oletools/rtfobj.py +++ b/oletools/rtfobj.py @@ -85,8 +85,11 @@ http://www.decalage.info/python/oletools # 2018-04-30 PL: - handle "\'" obfuscation trick - issue #281 # 2018-05-10 PL: - fixed issues #303 #307: several destination cwords were incorrect # 2018-05-17 PL: - fixed issue #273: bytes constants instead of str +# 2018-05-31 v0.53.1 PP: - fixed issue #316: whitespace after \bin on Python 3 +# 2018-06-22 v0.53.2 PL: - fixed issue #327: added "\pnaiu" & "\pnaiud" +# 2018-09-11 v0.54 PL: - olefile is now a dependency -__version__ = '0.53' +__version__ = '0.54dev1' # ------------------------------------------------------------------------------ # TODO: @@ -119,7 +122,7 @@ if not _parent_dir in sys.path: from oletools.thirdparty.xglob import xglob from oletools.thirdparty.tablestream import tablestream from oletools import oleobj -from oletools.thirdparty.olefile import olefile +import olefile from oletools.common import clsid # === LOGGING ================================================================= @@ -302,6 +305,8 @@ DESTINATION_CONTROL_WORDS = frozenset(( b"xmlattrname", b"xmlattrvalue", b"xmlclose", b"xmlname", b"xmlnstbl", b"xmlopen", # added for issue #292: https://github.com/decalage2/oletools/issues/292 b"margSz", + # added for issue #327: + b"pnaiu", b"pnaiud", # It seems \private should not be treated as a destination (issue #178) # Same for \pxe (issue #196) @@ -578,7 +583,7 @@ class RtfParser(object): # it should be treated as a null length: binlen=0 # ignore optional space after \bin - if self.data[self.index] == ' ': + if ord(self.data[self.index:self.index + 1]) == ord(' '): log.debug('\\bin: ignoring whitespace before data') self.index += 1 log.debug('\\bin: reading %d bytes of binary data' % binlen) @@ -717,7 +722,7 @@ class RtfObjParser(RtfParser): def control_symbol(self, matchobject): # log.debug('control symbol %r at index %Xh' % (matchobject.group(), self.index)) symbol = matchobject.group()[1:2] - if symbol == "'": + if symbol == b"'": # read the two hex digits following "\'" - which can be any characters, not just hex digits # (because within an objdata destination, they are simply ignored) hexdigits = self.data[self.index+2:self.index+4] diff --git a/oletools/thirdparty/colorclass/LICENSE.txt b/oletools/thirdparty/colorclass/LICENSE.txt deleted file mode 100644 index d42eea7..0000000 --- a/oletools/thirdparty/colorclass/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Robpol86 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/oletools/thirdparty/colorclass/__init__.py b/oletools/thirdparty/colorclass/__init__.py deleted file mode 100644 index cae4016..0000000 --- a/oletools/thirdparty/colorclass/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Colorful worry-free console applications for Linux, Mac OS X, and Windows. - -Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called. - -Gives you expected and sane results from methods like len() and .capitalize(). - -https://github.com/Robpol86/colorclass -https://pypi.python.org/pypi/colorclass -""" - -from colorclass.codes import list_tags # noqa -from colorclass.color import Color # noqa -from colorclass.toggles import disable_all_colors # noqa -from colorclass.toggles import disable_if_no_tty # noqa -from colorclass.toggles import enable_all_colors # noqa -from colorclass.toggles import is_enabled # noqa -from colorclass.toggles import is_light # noqa -from colorclass.toggles import set_dark_background # noqa -from colorclass.toggles import set_light_background # noqa -from colorclass.windows import Windows # noqa - - -__all__ = ( - 'Color', - 'disable_all_colors', - 'enable_all_colors', - 'is_enabled', - 'is_light', - 'list_tags', - 'set_dark_background', - 'set_light_background', - 'Windows', -) - - -__author__ = '@Robpol86' -__license__ = 'MIT' -__version__ = '2.2.0' diff --git a/oletools/thirdparty/colorclass/__main__.py b/oletools/thirdparty/colorclass/__main__.py deleted file mode 100644 index d8f3f00..0000000 --- a/oletools/thirdparty/colorclass/__main__.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Called by "python -m". Allows package to be used as a script. - -Example usage: -echo "{red}Red{/red}" |python -m colorclass -""" - -from __future__ import print_function - -import fileinput -import os - -from colorclass.color import Color -from colorclass.toggles import disable_all_colors -from colorclass.toggles import enable_all_colors -from colorclass.toggles import set_dark_background -from colorclass.toggles import set_light_background -from colorclass.windows import Windows - -TRUTHY = ('true', '1', 'yes', 'on') - - -if __name__ == '__main__': - if os.environ.get('COLOR_ENABLE', '').lower() in TRUTHY: - enable_all_colors() - elif os.environ.get('COLOR_DISABLE', '').lower() in TRUTHY: - disable_all_colors() - if os.environ.get('COLOR_LIGHT', '').lower() in TRUTHY: - set_light_background() - elif os.environ.get('COLOR_DARK', '').lower() in TRUTHY: - set_dark_background() - Windows.enable() - for LINE in fileinput.input(): - print(Color(LINE)) diff --git a/oletools/thirdparty/colorclass/codes.py b/oletools/thirdparty/colorclass/codes.py deleted file mode 100644 index b0ecb03..0000000 --- a/oletools/thirdparty/colorclass/codes.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Handles mapping between color names and ANSI codes and determining auto color codes.""" - -import sys -from collections import Mapping - -BASE_CODES = { - '/all': 0, 'b': 1, 'f': 2, 'i': 3, 'u': 4, 'flash': 5, 'outline': 6, 'negative': 7, 'invis': 8, 'strike': 9, - '/b': 22, '/f': 22, '/i': 23, '/u': 24, '/flash': 25, '/outline': 26, '/negative': 27, '/invis': 28, - '/strike': 29, '/fg': 39, '/bg': 49, - - 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, - - 'bgblack': 40, 'bgred': 41, 'bggreen': 42, 'bgyellow': 43, 'bgblue': 44, 'bgmagenta': 45, 'bgcyan': 46, - 'bgwhite': 47, - - 'hiblack': 90, 'hired': 91, 'higreen': 92, 'hiyellow': 93, 'hiblue': 94, 'himagenta': 95, 'hicyan': 96, - 'hiwhite': 97, - - 'hibgblack': 100, 'hibgred': 101, 'hibggreen': 102, 'hibgyellow': 103, 'hibgblue': 104, 'hibgmagenta': 105, - 'hibgcyan': 106, 'hibgwhite': 107, - - 'autored': None, 'autoblack': None, 'automagenta': None, 'autowhite': None, 'autoblue': None, 'autoyellow': None, - 'autogreen': None, 'autocyan': None, - - 'autobgred': None, 'autobgblack': None, 'autobgmagenta': None, 'autobgwhite': None, 'autobgblue': None, - 'autobgyellow': None, 'autobggreen': None, 'autobgcyan': None, - - '/black': 39, '/red': 39, '/green': 39, '/yellow': 39, '/blue': 39, '/magenta': 39, '/cyan': 39, '/white': 39, - '/hiblack': 39, '/hired': 39, '/higreen': 39, '/hiyellow': 39, '/hiblue': 39, '/himagenta': 39, '/hicyan': 39, - '/hiwhite': 39, - - '/bgblack': 49, '/bgred': 49, '/bggreen': 49, '/bgyellow': 49, '/bgblue': 49, '/bgmagenta': 49, '/bgcyan': 49, - '/bgwhite': 49, '/hibgblack': 49, '/hibgred': 49, '/hibggreen': 49, '/hibgyellow': 49, '/hibgblue': 49, - '/hibgmagenta': 49, '/hibgcyan': 49, '/hibgwhite': 49, - - '/autored': 39, '/autoblack': 39, '/automagenta': 39, '/autowhite': 39, '/autoblue': 39, '/autoyellow': 39, - '/autogreen': 39, '/autocyan': 39, - - '/autobgred': 49, '/autobgblack': 49, '/autobgmagenta': 49, '/autobgwhite': 49, '/autobgblue': 49, - '/autobgyellow': 49, '/autobggreen': 49, '/autobgcyan': 49, -} - - -class ANSICodeMapping(Mapping): - """Read-only dictionary, resolves closing tags and automatic colors. Iterates only used color tags. - - :cvar bool DISABLE_COLORS: Disable colors (strip color codes). - :cvar bool LIGHT_BACKGROUND: Use low intensity color codes. - """ - - DISABLE_COLORS = False - LIGHT_BACKGROUND = False - - def __init__(self, value_markup): - """Constructor. - - :param str value_markup: String with {color} tags. - """ - self.whitelist = [k for k in BASE_CODES if '{' + k + '}' in value_markup] - - def __getitem__(self, item): - """Return value for key or None if colors are disabled. - - :param str item: Key. - - :return: Color code integer. - :rtype: int - """ - if item not in self.whitelist: - raise KeyError(item) - if self.DISABLE_COLORS: - return None - return getattr(self, item, BASE_CODES[item]) - - def __iter__(self): - """Iterate dictionary.""" - return iter(self.whitelist) - - def __len__(self): - """Dictionary length.""" - return len(self.whitelist) - - @classmethod - def disable_all_colors(cls): - """Disable all colors. Strips any color tags or codes.""" - cls.DISABLE_COLORS = True - - @classmethod - def enable_all_colors(cls): - """Enable all colors. Strips any color tags or codes.""" - cls.DISABLE_COLORS = False - - @classmethod - def disable_if_no_tty(cls): - """Disable all colors only if there is no TTY available. - - :return: True if colors are disabled, False if stderr or stdout is a TTY. - :rtype: bool - """ - if sys.stdout.isatty() or sys.stderr.isatty(): - return False - cls.disable_all_colors() - return True - - @classmethod - def set_dark_background(cls): - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" - cls.LIGHT_BACKGROUND = False - - @classmethod - def set_light_background(cls): - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" - cls.LIGHT_BACKGROUND = True - - @property - def autoblack(self): - """Return automatic black foreground color depending on background color.""" - return BASE_CODES['black' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblack'] - - @property - def autored(self): - """Return automatic red foreground color depending on background color.""" - return BASE_CODES['red' if ANSICodeMapping.LIGHT_BACKGROUND else 'hired'] - - @property - def autogreen(self): - """Return automatic green foreground color depending on background color.""" - return BASE_CODES['green' if ANSICodeMapping.LIGHT_BACKGROUND else 'higreen'] - - @property - def autoyellow(self): - """Return automatic yellow foreground color depending on background color.""" - return BASE_CODES['yellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiyellow'] - - @property - def autoblue(self): - """Return automatic blue foreground color depending on background color.""" - return BASE_CODES['blue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblue'] - - @property - def automagenta(self): - """Return automatic magenta foreground color depending on background color.""" - return BASE_CODES['magenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'himagenta'] - - @property - def autocyan(self): - """Return automatic cyan foreground color depending on background color.""" - return BASE_CODES['cyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hicyan'] - - @property - def autowhite(self): - """Return automatic white foreground color depending on background color.""" - return BASE_CODES['white' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiwhite'] - - @property - def autobgblack(self): - """Return automatic black background color depending on background color.""" - return BASE_CODES['bgblack' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblack'] - - @property - def autobgred(self): - """Return automatic red background color depending on background color.""" - return BASE_CODES['bgred' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgred'] - - @property - def autobggreen(self): - """Return automatic green background color depending on background color.""" - return BASE_CODES['bggreen' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibggreen'] - - @property - def autobgyellow(self): - """Return automatic yellow background color depending on background color.""" - return BASE_CODES['bgyellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgyellow'] - - @property - def autobgblue(self): - """Return automatic blue background color depending on background color.""" - return BASE_CODES['bgblue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblue'] - - @property - def autobgmagenta(self): - """Return automatic magenta background color depending on background color.""" - return BASE_CODES['bgmagenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgmagenta'] - - @property - def autobgcyan(self): - """Return automatic cyan background color depending on background color.""" - return BASE_CODES['bgcyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgcyan'] - - @property - def autobgwhite(self): - """Return automatic white background color depending on background color.""" - return BASE_CODES['bgwhite' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgwhite'] - - -def list_tags(): - """List the available tags. - - :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value. - :rtype: list - """ - # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi]. - reverse_dict = dict() - for tag, ansi in sorted(BASE_CODES.items()): - if tag.startswith('/'): - reverse_dict[tag] = [ansi, None, None] - else: - reverse_dict['/' + tag][1:] = [tag, ansi] - - # Collapse - four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()] - - # Sort. - def sorter(four_item): - """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors. - - :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value] - - :return Sorting weight. - :rtype: int - """ - if not four_item[2]: # /all /fg /bg - return four_item[3] - 200 - if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors - return four_item[2] - 100 - return four_item[2] - four_item_tuples.sort(key=sorter) - - return four_item_tuples diff --git a/oletools/thirdparty/colorclass/color.py b/oletools/thirdparty/colorclass/color.py deleted file mode 100644 index 2849d06..0000000 --- a/oletools/thirdparty/colorclass/color.py +++ /dev/null @@ -1,220 +0,0 @@ -"""Color class used by library users.""" - -from colorclass.core import ColorStr - - -class Color(ColorStr): - """Unicode (str in Python3) subclass with ANSI terminal text color support. - - Example syntax: Color('{red}Sample Text{/red}') - - Example without parsing logic: Color('{red}Sample Text{/red}', keep_tags=True) - - For a list of codes, call: colorclass.list_tags() - """ - - @classmethod - def colorize(cls, color, string, auto=False): - """Color-code entire string using specified color. - - :param str color: Color of string. - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - tag = '{0}{1}'.format('auto' if auto else '', color) - return cls('{%s}%s{/%s}' % (tag, string, tag)) - - @classmethod - def black(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('black', string, auto=auto) - - @classmethod - def bgblack(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgblack', string, auto=auto) - - @classmethod - def red(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('red', string, auto=auto) - - @classmethod - def bgred(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgred', string, auto=auto) - - @classmethod - def green(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('green', string, auto=auto) - - @classmethod - def bggreen(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bggreen', string, auto=auto) - - @classmethod - def yellow(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('yellow', string, auto=auto) - - @classmethod - def bgyellow(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgyellow', string, auto=auto) - - @classmethod - def blue(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('blue', string, auto=auto) - - @classmethod - def bgblue(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgblue', string, auto=auto) - - @classmethod - def magenta(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('magenta', string, auto=auto) - - @classmethod - def bgmagenta(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgmagenta', string, auto=auto) - - @classmethod - def cyan(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('cyan', string, auto=auto) - - @classmethod - def bgcyan(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgcyan', string, auto=auto) - - @classmethod - def white(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('white', string, auto=auto) - - @classmethod - def bgwhite(cls, string, auto=False): - """Color-code entire string. - - :param str string: String to colorize. - :param bool auto: Enable auto-color (dark/light terminal). - - :return: Class instance for colorized string. - :rtype: Color - """ - return cls.colorize('bgwhite', string, auto=auto) diff --git a/oletools/thirdparty/colorclass/core.py b/oletools/thirdparty/colorclass/core.py deleted file mode 100644 index 481bb40..0000000 --- a/oletools/thirdparty/colorclass/core.py +++ /dev/null @@ -1,342 +0,0 @@ -"""String subclass that handles ANSI color codes.""" - -from colorclass.codes import ANSICodeMapping -from colorclass.parse import parse_input, RE_SPLIT -from colorclass.search import build_color_index, find_char_color - -PARENT_CLASS = type(u'') - - -def apply_text(incoming, func): - """Call `func` on text portions of incoming color string. - - :param iter incoming: Incoming string/ColorStr/string-like object to iterate. - :param func: Function to call with string portion as first and only parameter. - - :return: Modified string, same class type as incoming string. - """ - split = RE_SPLIT.split(incoming) - for i, item in enumerate(split): - if not item or RE_SPLIT.match(item): - continue - split[i] = func(item) - return incoming.__class__().join(split) - - -class ColorBytes(bytes): - """Str (bytes in Python3) subclass, .decode() overridden to return unicode (str in Python3) subclass instance.""" - - def __new__(cls, *args, **kwargs): - """Save original class so decode() returns an instance of it.""" - original_class = kwargs.pop('original_class') - combined_args = [cls] + list(args) - instance = bytes.__new__(*combined_args, **kwargs) - instance.original_class = original_class - return instance - - def decode(self, encoding='utf-8', errors='strict'): - """Decode using the codec registered for encoding. Default encoding is 'utf-8'. - - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors - raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name - registered with codecs.register_error that is able to handle UnicodeDecodeErrors. - - :param str encoding: Codec. - :param str errors: Error handling scheme. - """ - original_class = getattr(self, 'original_class') - return original_class(super(ColorBytes, self).decode(encoding, errors)) - - -class ColorStr(PARENT_CLASS): - """Core color class.""" - - def __new__(cls, *args, **kwargs): - """Parse color markup and instantiate.""" - keep_tags = kwargs.pop('keep_tags', False) - - # Parse string. - value_markup = args[0] if args else PARENT_CLASS() # e.g. '{red}test{/red}' - value_colors, value_no_colors = parse_input(value_markup, ANSICodeMapping.DISABLE_COLORS, keep_tags) - color_index = build_color_index(value_colors) - - # Instantiate. - color_args = [cls, value_colors] + list(args[1:]) - instance = PARENT_CLASS.__new__(*color_args, **kwargs) - - # Add additional attributes and return. - instance.value_colors = value_colors - instance.value_no_colors = value_no_colors - instance.has_colors = value_colors != value_no_colors - instance.color_index = color_index - return instance - - def __add__(self, other): - """Concatenate.""" - return self.__class__(self.value_colors + other, keep_tags=True) - - def __getitem__(self, item): - """Retrieve character.""" - try: - color_pos = self.color_index[int(item)] - except TypeError: # slice - return super(ColorStr, self).__getitem__(item) - return self.__class__(find_char_color(self.value_colors, color_pos), keep_tags=True) - - def __iter__(self): - """Yield one color-coded character at a time.""" - for color_pos in self.color_index: - yield self.__class__(find_char_color(self.value_colors, color_pos)) - - def __len__(self): - """Length of string without color codes (what users expect).""" - return self.value_no_colors.__len__() - - def __mod__(self, other): - """String substitution (like printf).""" - return self.__class__(self.value_colors % other, keep_tags=True) - - def __mul__(self, other): - """Multiply string.""" - return self.__class__(self.value_colors * other, keep_tags=True) - - def __repr__(self): - """Representation of a class instance (like datetime.datetime.now()).""" - return '{name}({value})'.format(name=self.__class__.__name__, value=repr(self.value_colors)) - - def capitalize(self): - """Return a copy of the string with only its first character capitalized.""" - return apply_text(self, lambda s: s.capitalize()) - - def center(self, width, fillchar=None): - """Return centered in a string of length width. Padding is done using the specified fill character or space. - - :param int width: Length of output string. - :param str fillchar: Use this character instead of spaces. - """ - if fillchar is not None: - result = self.value_no_colors.center(width, fillchar) - else: - result = self.value_no_colors.center(width) - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True) - - def count(self, sub, start=0, end=-1): - """Return the number of non-overlapping occurrences of substring sub in string[start:end]. - - Optional arguments start and end are interpreted as in slice notation. - - :param str sub: Substring to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.count(sub, start, end) - - def endswith(self, suffix, start=0, end=None): - """Return True if ends with the specified suffix, False otherwise. - - With optional start, test beginning at that position. With optional end, stop comparing at that position. - suffix can also be a tuple of strings to try. - - :param str suffix: Suffix to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - args = [suffix, start] + ([] if end is None else [end]) - return self.value_no_colors.endswith(*args) - - def encode(self, encoding=None, errors='strict'): - """Encode using the codec registered for encoding. encoding defaults to the default encoding. - - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors - raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any - other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. - - :param str encoding: Codec. - :param str errors: Error handling scheme. - """ - return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__) - - def decode(self, encoding=None, errors='strict'): - """Decode using the codec registered for encoding. encoding defaults to the default encoding. - - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors - raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name - registered with codecs.register_error that is able to handle UnicodeDecodeErrors. - - :param str encoding: Codec. - :param str errors: Error handling scheme. - """ - return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True) - - def find(self, sub, start=None, end=None): - """Return the lowest index where substring sub is found, such that sub is contained within string[start:end]. - - Optional arguments start and end are interpreted as in slice notation. - - :param str sub: Substring to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.find(sub, start, end) - - def format(self, *args, **kwargs): - """Return a formatted version, using substitutions from args and kwargs. - - The substitutions are identified by braces ('{' and '}'). - """ - return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True) - - def index(self, sub, start=None, end=None): - """Like S.find() but raise ValueError when the substring is not found. - - :param str sub: Substring to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.index(sub, start, end) - - def isalnum(self): - """Return True if all characters in string are alphanumeric and there is at least one character in it.""" - return self.value_no_colors.isalnum() - - def isalpha(self): - """Return True if all characters in string are alphabetic and there is at least one character in it.""" - return self.value_no_colors.isalpha() - - def isdecimal(self): - """Return True if there are only decimal characters in string, False otherwise.""" - return self.value_no_colors.isdecimal() - - def isdigit(self): - """Return True if all characters in string are digits and there is at least one character in it.""" - return self.value_no_colors.isdigit() - - def isnumeric(self): - """Return True if there are only numeric characters in string, False otherwise.""" - return self.value_no_colors.isnumeric() - - def isspace(self): - """Return True if all characters in string are whitespace and there is at least one character in it.""" - return self.value_no_colors.isspace() - - def istitle(self): - """Return True if string is a titlecased string and there is at least one character in it. - - That is uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return - False otherwise. - """ - return self.value_no_colors.istitle() - - def isupper(self): - """Return True if all cased characters are uppercase and there is at least one cased character in it.""" - return self.value_no_colors.isupper() - - def join(self, iterable): - """Return a string which is the concatenation of the strings in the iterable. - - :param iterable: Join items in this iterable. - """ - return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True) - - def ljust(self, width, fillchar=None): - """Return left-justified string of length width. Padding is done using the specified fill character or space. - - :param int width: Length of output string. - :param str fillchar: Use this character instead of spaces. - """ - if fillchar is not None: - result = self.value_no_colors.ljust(width, fillchar) - else: - result = self.value_no_colors.ljust(width) - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True) - - def rfind(self, sub, start=None, end=None): - """Return the highest index where substring sub is found, such that sub is contained within string[start:end]. - - Optional arguments start and end are interpreted as in slice notation. - - :param str sub: Substring to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.rfind(sub, start, end) - - def rindex(self, sub, start=None, end=None): - """Like .rfind() but raise ValueError when the substring is not found. - - :param str sub: Substring to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.rindex(sub, start, end) - - def rjust(self, width, fillchar=None): - """Return right-justified string of length width. Padding is done using the specified fill character or space. - - :param int width: Length of output string. - :param str fillchar: Use this character instead of spaces. - """ - if fillchar is not None: - result = self.value_no_colors.rjust(width, fillchar) - else: - result = self.value_no_colors.rjust(width) - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True) - - def splitlines(self, keepends=False): - """Return a list of the lines in the string, breaking at line boundaries. - - Line breaks are not included in the resulting list unless keepends is given and True. - - :param bool keepends: Include linebreaks. - """ - return [self.__class__(l) for l in self.value_colors.splitlines(keepends)] - - def startswith(self, prefix, start=0, end=-1): - """Return True if string starts with the specified prefix, False otherwise. - - With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix - can also be a tuple of strings to try. - - :param str prefix: Prefix to search. - :param int start: Beginning position. - :param int end: Stop comparison at this position. - """ - return self.value_no_colors.startswith(prefix, start, end) - - def swapcase(self): - """Return a copy of the string with uppercase characters converted to lowercase and vice versa.""" - return apply_text(self, lambda s: s.swapcase()) - - def title(self): - """Return a titlecased version of the string. - - That is words start with uppercase characters, all remaining cased characters have lowercase. - """ - return apply_text(self, lambda s: s.title()) - - def translate(self, table): - """Return a copy of the string, where all characters have been mapped through the given translation table. - - Table must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None. Unmapped characters are left - untouched. Characters mapped to None are deleted. - - :param table: Translation table. - """ - return apply_text(self, lambda s: s.translate(table)) - - def upper(self): - """Return a copy of the string converted to uppercase.""" - return apply_text(self, lambda s: s.upper()) - - def zfill(self, width): - """Pad a numeric string with zeros on the left, to fill a field of the specified width. - - The string is never truncated. - - :param int width: Length of output string. - """ - if not self.value_no_colors: - result = self.value_no_colors.zfill(width) - else: - result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width)) - return self.__class__(result, keep_tags=True) diff --git a/oletools/thirdparty/colorclass/parse.py b/oletools/thirdparty/colorclass/parse.py deleted file mode 100644 index 46dc28e..0000000 --- a/oletools/thirdparty/colorclass/parse.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Parse color markup tags into ANSI escape sequences.""" - -import re - -from colorclass.codes import ANSICodeMapping, BASE_CODES - -CODE_GROUPS = ( - tuple(set(str(i) for i in BASE_CODES.values() if i and (40 <= i <= 49 or 100 <= i <= 109))), # bg colors - tuple(set(str(i) for i in BASE_CODES.values() if i and (30 <= i <= 39 or 90 <= i <= 99))), # fg colors - ('1', '22'), ('2', '22'), ('3', '23'), ('4', '24'), ('5', '25'), ('6', '26'), ('7', '27'), ('8', '28'), ('9', '29'), -) -RE_ANSI = re.compile(r'(\033\[([\d;]+)m)') -RE_COMBINE = re.compile(r'\033\[([\d;]+)m\033\[([\d;]+)m') -RE_SPLIT = re.compile(r'(\033\[[\d;]+m)') - - -def prune_overridden(ansi_string): - """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. - - :param str ansi_string: Incoming ansi_string with ANSI color codes. - - :return: Color string with pruned color sequences. - :rtype: str - """ - multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes. - - for escape, codes in multi_seqs: - r_codes = list(reversed(codes.split(';'))) - - # Nuke everything before {/all}. - try: - r_codes = r_codes[:r_codes.index('0') + 1] - except ValueError: - pass - - # Thin out groups. - for group in CODE_GROUPS: - for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]): - r_codes.pop(pos) - - # Done. - reduced_codes = ';'.join(sorted(r_codes, key=int)) - if codes != reduced_codes: - ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm') - - return ansi_string - - -def parse_input(tagged_string, disable_colors, keep_tags): - """Perform the actual conversion of tags to ANSI escaped codes. - - Provides a version of the input without any colors for len() and other methods. - - :param str tagged_string: The input unicode value. - :param bool disable_colors: Strip all colors in both outputs. - :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. - - :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. - :rtype: tuple - """ - codes = ANSICodeMapping(tagged_string) - output_colors = getattr(tagged_string, 'value_colors', tagged_string) - - # Convert: '{b}{red}' -> '\033[1m\033[31m' - if not keep_tags: - for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()): - output_colors = output_colors.replace(tag, replacement) - - # Strip colors. - output_no_colors = RE_ANSI.sub('', output_colors) - if disable_colors: - return output_no_colors, output_no_colors - - # Combine: '\033[1m\033[31m' -> '\033[1;31m' - while True: - simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors) - if simplified == output_colors: - break - output_colors = simplified - - # Prune: '\033[31;32;33;34;35m' -> '\033[35m' - output_colors = prune_overridden(output_colors) - - # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' - previous_escape = None - segments = list() - for item in (i for i in RE_SPLIT.split(output_colors) if i): - if RE_SPLIT.match(item): - if item != previous_escape: - segments.append(item) - previous_escape = item - else: - segments.append(item) - output_colors = ''.join(segments) - - return output_colors, output_no_colors diff --git a/oletools/thirdparty/colorclass/search.py b/oletools/thirdparty/colorclass/search.py deleted file mode 100644 index 555402d..0000000 --- a/oletools/thirdparty/colorclass/search.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Determine color of characters that may or may not be adjacent to ANSI escape sequences.""" - -from colorclass.parse import RE_SPLIT - - -def build_color_index(ansi_string): - """Build an index between visible characters and a string with invisible color codes. - - :param str ansi_string: String with color codes (ANSI escape sequences). - - :return: Position of visible characters in color string (indexes match non-color string). - :rtype: tuple - """ - mapping = list() - color_offset = 0 - for item in (i for i in RE_SPLIT.split(ansi_string) if i): - if RE_SPLIT.match(item): - color_offset += len(item) - else: - for _ in range(len(item)): - mapping.append(color_offset) - color_offset += 1 - return tuple(mapping) - - -def find_char_color(ansi_string, pos): - """Determine what color a character is in the string. - - :param str ansi_string: String with color codes (ANSI escape sequences). - :param int pos: Position of the character in the ansi_string. - - :return: Character along with all surrounding color codes. - :rtype: str - """ - result = list() - position = 0 # Set to None when character is found. - for item in (i for i in RE_SPLIT.split(ansi_string) if i): - if RE_SPLIT.match(item): - result.append(item) - if position is not None: - position += len(item) - elif position is not None: - for char in item: - if position == pos: - result.append(char) - position = None - break - position += 1 - return ''.join(result) diff --git a/oletools/thirdparty/colorclass/toggles.py b/oletools/thirdparty/colorclass/toggles.py deleted file mode 100644 index 1ba6bce..0000000 --- a/oletools/thirdparty/colorclass/toggles.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Convenience functions to enable/disable features.""" - -from colorclass.codes import ANSICodeMapping - - -def disable_all_colors(): - """Disable all colors. Strip any color tags or codes.""" - ANSICodeMapping.disable_all_colors() - - -def enable_all_colors(): - """Enable colors.""" - ANSICodeMapping.enable_all_colors() - - -def disable_if_no_tty(): - """Disable all colors if there is no TTY available. - - :return: True if colors are disabled, False if stderr or stdout is a TTY. - :rtype: bool - """ - return ANSICodeMapping.disable_if_no_tty() - - -def is_enabled(): - """Are colors enabled.""" - return not ANSICodeMapping.DISABLE_COLORS - - -def set_light_background(): - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" - ANSICodeMapping.set_light_background() - - -def set_dark_background(): - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" - ANSICodeMapping.set_dark_background() - - -def is_light(): - """Are background colors for light backgrounds.""" - return ANSICodeMapping.LIGHT_BACKGROUND diff --git a/oletools/thirdparty/colorclass/windows.py b/oletools/thirdparty/colorclass/windows.py deleted file mode 100644 index 8f69478..0000000 --- a/oletools/thirdparty/colorclass/windows.py +++ /dev/null @@ -1,388 +0,0 @@ -"""Windows console screen buffer handlers.""" - -from __future__ import print_function - -import atexit -import ctypes -import re -import sys - -from colorclass.codes import ANSICodeMapping, BASE_CODES -from colorclass.core import RE_SPLIT - -ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 -INVALID_HANDLE_VALUE = -1 -IS_WINDOWS = sys.platform == 'win32' -RE_NUMBER_SEARCH = re.compile(r'\033\[([\d;]+)m') -STD_ERROR_HANDLE = -12 -STD_OUTPUT_HANDLE = -11 -WINDOWS_CODES = { - '/all': -33, '/fg': -39, '/bg': -49, - - 'black': 0, 'red': 4, 'green': 2, 'yellow': 6, 'blue': 1, 'magenta': 5, 'cyan': 3, 'white': 7, - - 'bgblack': -8, 'bgred': 64, 'bggreen': 32, 'bgyellow': 96, 'bgblue': 16, 'bgmagenta': 80, 'bgcyan': 48, - 'bgwhite': 112, - - 'hiblack': 8, 'hired': 12, 'higreen': 10, 'hiyellow': 14, 'hiblue': 9, 'himagenta': 13, 'hicyan': 11, 'hiwhite': 15, - - 'hibgblack': 128, 'hibgred': 192, 'hibggreen': 160, 'hibgyellow': 224, 'hibgblue': 144, 'hibgmagenta': 208, - 'hibgcyan': 176, 'hibgwhite': 240, - - '/black': -39, '/red': -39, '/green': -39, '/yellow': -39, '/blue': -39, '/magenta': -39, '/cyan': -39, - '/white': -39, '/hiblack': -39, '/hired': -39, '/higreen': -39, '/hiyellow': -39, '/hiblue': -39, '/himagenta': -39, - '/hicyan': -39, '/hiwhite': -39, - - '/bgblack': -49, '/bgred': -49, '/bggreen': -49, '/bgyellow': -49, '/bgblue': -49, '/bgmagenta': -49, - '/bgcyan': -49, '/bgwhite': -49, '/hibgblack': -49, '/hibgred': -49, '/hibggreen': -49, '/hibgyellow': -49, - '/hibgblue': -49, '/hibgmagenta': -49, '/hibgcyan': -49, '/hibgwhite': -49, -} - - -class COORD(ctypes.Structure): - """COORD structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119.""" - - _fields_ = [ - ('X', ctypes.c_short), - ('Y', ctypes.c_short), - ] - - -class SmallRECT(ctypes.Structure): - """SMALL_RECT structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms686311.""" - - _fields_ = [ - ('Left', ctypes.c_short), - ('Top', ctypes.c_short), - ('Right', ctypes.c_short), - ('Bottom', ctypes.c_short), - ] - - -class ConsoleScreenBufferInfo(ctypes.Structure): - """CONSOLE_SCREEN_BUFFER_INFO structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093.""" - - _fields_ = [ - ('dwSize', COORD), - ('dwCursorPosition', COORD), - ('wAttributes', ctypes.c_ushort), - ('srWindow', SmallRECT), - ('dwMaximumWindowSize', COORD) - ] - - -def init_kernel32(kernel32=None): - """Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles. - - 1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of - kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.kernel32. - 2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams. - 3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be - replaced. - - :raise AttributeError: When called on a non-Windows platform. - - :param kernel32: Optional mock kernel32 object. For testing. - - :return: Loaded kernel32 instance, stderr handle (int), stdout handle (int). - :rtype: tuple - """ - if not kernel32: - kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32 # Load our own instance. Unique memory address. - kernel32.GetStdHandle.argtypes = [ctypes.c_ulong] - kernel32.GetStdHandle.restype = ctypes.c_void_p - kernel32.GetConsoleScreenBufferInfo.argtypes = [ - ctypes.c_void_p, - ctypes.POINTER(ConsoleScreenBufferInfo), - ] - kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long - - # Get handles. - if hasattr(sys.stderr, '_original_stream'): - stderr = INVALID_HANDLE_VALUE - else: - stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE) - if hasattr(sys.stdout, '_original_stream'): - stdout = INVALID_HANDLE_VALUE - else: - stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE) - - return kernel32, stderr, stdout - - -def get_console_info(kernel32, handle): - """Get information about this current console window. - - http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231 - https://code.google.com/p/colorama/issues/detail?id=47 - https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py - - Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout - and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles. - - :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail. - - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. - :param int handle: stderr or stdout handle. - - :return: Foreground and background colors (integers) as well as native ANSI support (bool). - :rtype: tuple - """ - # Query Win32 API. - csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo. - lpcsbi = ctypes.byref(csbi) - dword = ctypes.c_ulong() # Populated by GetConsoleMode. - lpdword = ctypes.byref(dword) - if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword): - raise ctypes.WinError() - - # Parse data. - # buffer_width = int(csbi.dwSize.X - 1) - # buffer_height = int(csbi.dwSize.Y) - # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left) - # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top) - fg_color = csbi.wAttributes % 16 - bg_color = csbi.wAttributes & 240 - native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING) - - return fg_color, bg_color, native_ansi - - -def bg_color_native_ansi(kernel32, stderr, stdout): - """Get background color and if console supports ANSI colors natively for both streams. - - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. - :param int stderr: stderr handle. - :param int stdout: stdout handle. - - :return: Background color (int) and native ANSI support (bool). - :rtype: tuple - """ - try: - if stderr == INVALID_HANDLE_VALUE: - raise OSError - bg_color, native_ansi = get_console_info(kernel32, stderr)[1:] - except OSError: - try: - if stdout == INVALID_HANDLE_VALUE: - raise OSError - bg_color, native_ansi = get_console_info(kernel32, stdout)[1:] - except OSError: - bg_color, native_ansi = WINDOWS_CODES['black'], False - return bg_color, native_ansi - - -class WindowsStream(object): - """Replacement stream which overrides sys.stdout or sys.stderr. When writing or printing, ANSI codes are converted. - - ANSI (Linux/Unix) color codes are converted into win32 system calls, changing the next character's color before - printing it. Resources referenced: - https://github.com/tartley/colorama - http://www.cplusplus.com/articles/2ywTURfi/ - http://thomasfischer.biz/python-and-windows-terminal-colors/ - http://stackoverflow.com/questions/17125440/c-win32-console-color - http://www.tysos.org/svn/trunk/mono/corlib/System/WindowsConsoleDriver.cs - http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python - http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088#_win32_character_attributes - - :cvar list ALL_BG_CODES: List of bg Windows codes. Used to determine if requested color is foreground or background. - :cvar dict COMPILED_CODES: Translation dict. Keys are ANSI codes (values of BASE_CODES), values are Windows codes. - :ivar int default_fg: Foreground Windows color code at the time of instantiation. - :ivar int default_bg: Background Windows color code at the time of instantiation. - """ - - ALL_BG_CODES = [v for k, v in WINDOWS_CODES.items() if k.startswith('bg') or k.startswith('hibg')] - COMPILED_CODES = dict((v, WINDOWS_CODES[k]) for k, v in BASE_CODES.items() if k in WINDOWS_CODES) - - def __init__(self, kernel32, stream_handle, original_stream): - """Constructor. - - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance. - :param int stream_handle: stderr or stdout handle. - :param original_stream: sys.stderr or sys.stdout before being overridden by this class' instance. - """ - self._kernel32 = kernel32 - self._stream_handle = stream_handle - self._original_stream = original_stream - self.default_fg, self.default_bg = self.colors - - def __getattr__(self, item): - """If an attribute/function/etc is not defined in this function, retrieve the one from the original stream. - - Fixes ipython arrow key presses. - """ - return getattr(self._original_stream, item) - - @property - def colors(self): - """Return the current foreground and background colors.""" - try: - return get_console_info(self._kernel32, self._stream_handle)[:2] - except OSError: - return WINDOWS_CODES['white'], WINDOWS_CODES['black'] - - @colors.setter - def colors(self, color_code): - """Change the foreground and background colors for subsequently printed characters. - - None resets colors to their original values (when class was instantiated). - - Since setting a color requires including both foreground and background codes (merged), setting just the - foreground color resets the background color to black, and vice versa. - - This function first gets the current background and foreground colors, merges in the requested color code, and - sets the result. - - However if we need to remove just the foreground color but leave the background color the same (or vice versa) - such as when {/red} is used, we must merge the default foreground color with the current background color. This - is the reason for those negative values. - - :param int color_code: Color code from WINDOWS_CODES. - """ - if color_code is None: - color_code = WINDOWS_CODES['/all'] - - # Get current color code. - current_fg, current_bg = self.colors - - # Handle special negative codes. Also determine the final color code. - if color_code == WINDOWS_CODES['/fg']: - final_color_code = self.default_fg | current_bg # Reset the foreground only. - elif color_code == WINDOWS_CODES['/bg']: - final_color_code = current_fg | self.default_bg # Reset the background only. - elif color_code == WINDOWS_CODES['/all']: - final_color_code = self.default_fg | self.default_bg # Reset both. - elif color_code == WINDOWS_CODES['bgblack']: - final_color_code = current_fg # Black background. - else: - new_is_bg = color_code in self.ALL_BG_CODES - final_color_code = color_code | (current_fg if new_is_bg else current_bg) - - # Set new code. - self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code) - - def write(self, p_str): - """Write to stream. - - :param str p_str: string to print. - """ - for segment in RE_SPLIT.split(p_str): - if not segment: - # Empty string. p_str probably starts with colors so the first item is always ''. - continue - if not RE_SPLIT.match(segment): - # No color codes, print regular text. - print(segment, file=self._original_stream, end='') - self._original_stream.flush() - continue - for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')): - if color_code in self.COMPILED_CODES: - self.colors = self.COMPILED_CODES[color_code] - - -class Windows(object): - """Enable and disable Windows support for ANSI color character codes. - - Call static method Windows.enable() to enable color support for the remainder of the process' lifetime. - - This class is also a context manager. You can do this: - with Windows(): - print(Color('{autored}Test{/autored}')) - - Or this: - with Windows(auto_colors=True): - print(Color('{autored}Test{/autored}')) - """ - - @classmethod - def disable(cls): - """Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values. - - :return: If streams restored successfully. - :rtype: bool - """ - # Skip if not on Windows. - if not IS_WINDOWS: - return False - - # Restore default colors. - if hasattr(sys.stderr, '_original_stream'): - getattr(sys, 'stderr').color = None - if hasattr(sys.stdout, '_original_stream'): - getattr(sys, 'stdout').color = None - - # Restore original streams. - changed = False - if hasattr(sys.stderr, '_original_stream'): - changed = True - sys.stderr = getattr(sys.stderr, '_original_stream') - if hasattr(sys.stdout, '_original_stream'): - changed = True - sys.stdout = getattr(sys.stdout, '_original_stream') - - return changed - - @staticmethod - def is_enabled(): - """Return True if either stderr or stdout has colors enabled.""" - return hasattr(sys.stderr, '_original_stream') or hasattr(sys.stdout, '_original_stream') - - @classmethod - def enable(cls, auto_colors=False, reset_atexit=False): - """Enable color text with print() or sys.stdout.write() (stderr too). - - :param bool auto_colors: Automatically selects dark or light colors based on current terminal's background - color. Only works with {autored} and related tags. - :param bool reset_atexit: Resets original colors upon Python exit (in case you forget to reset it yourself with - a closing tag). Does nothing on native ANSI consoles. - - :return: If streams replaced successfully. - :rtype: bool - """ - if not IS_WINDOWS: - return False # Windows only. - - # Get values from init_kernel32(). - kernel32, stderr, stdout = init_kernel32() - if stderr == INVALID_HANDLE_VALUE and stdout == INVALID_HANDLE_VALUE: - return False # No valid handles, nothing to do. - - # Get console info. - bg_color, native_ansi = bg_color_native_ansi(kernel32, stderr, stdout) - - # Set auto colors: - if auto_colors: - if bg_color in (112, 96, 240, 176, 224, 208, 160): - ANSICodeMapping.set_light_background() - else: - ANSICodeMapping.set_dark_background() - - # Don't replace streams if ANSI codes are natively supported. - if native_ansi: - return False - - # Reset on exit if requested. - if reset_atexit: - atexit.register(cls.disable) - - # Overwrite stream references. - if stderr != INVALID_HANDLE_VALUE: - sys.stderr.flush() - sys.stderr = WindowsStream(kernel32, stderr, sys.stderr) - if stdout != INVALID_HANDLE_VALUE: - sys.stdout.flush() - sys.stdout = WindowsStream(kernel32, stdout, sys.stdout) - - return True - - def __init__(self, auto_colors=False): - """Constructor.""" - self.auto_colors = auto_colors - - def __enter__(self): - """Context manager, enables colors on Windows.""" - self.enable(auto_colors=self.auto_colors) - - def __exit__(self, *_): - """Context manager, disabled colors on Windows.""" - self.disable() diff --git a/oletools/thirdparty/easygui/LICENSE.txt b/oletools/thirdparty/easygui/LICENSE.txt deleted file mode 100644 index b04511b..0000000 --- a/oletools/thirdparty/easygui/LICENSE.txt +++ /dev/null @@ -1,32 +0,0 @@ -LICENSE INFORMATION - -EasyGui version 0.96 - -Copyright (c) 2010, Stephen Raymond Ferg - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING -IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/oletools/thirdparty/easygui/easygui.py b/oletools/thirdparty/easygui/easygui.py deleted file mode 100644 index 016ffd5..0000000 --- a/oletools/thirdparty/easygui/easygui.py +++ /dev/null @@ -1,2492 +0,0 @@ -""" -@version: 0.96(2010-08-29) - -@note: -ABOUT EASYGUI - -EasyGui provides an easy-to-use interface for simple GUI interaction -with a user. It does not require the programmer to know anything about -tkinter, frames, widgets, callbacks or lambda. All GUI interactions are -invoked by simple function calls that return results. - -@note: -WARNING about using EasyGui with IDLE - -You may encounter problems using IDLE to run programs that use EasyGui. Try it -and find out. EasyGui is a collection of Tkinter routines that run their own -event loops. IDLE is also a Tkinter application, with its own event loop. The -two may conflict, with unpredictable results. If you find that you have -problems, try running your EasyGui program outside of IDLE. - -Note that EasyGui requires Tk release 8.0 or greater. - -@note: -LICENSE INFORMATION - -EasyGui version 0.96 - -Copyright (c) 2010, Stephen Raymond Ferg - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - 3. The name of the author may not be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING -IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -@note: -ABOUT THE EASYGUI LICENSE - -This license is what is generally known as the "modified BSD license", -aka "revised BSD", "new BSD", "3-clause BSD". -See http://www.opensource.org/licenses/bsd-license.php - -This license is GPL-compatible. -See http://en.wikipedia.org/wiki/License_compatibility -See http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses - -The BSD License is less restrictive than GPL. -It allows software released under the license to be incorporated into proprietary products. -Works based on the software may be released under a proprietary license or as closed source software. -http://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_.28.22New_BSD_License.22.29 - -""" -egversion = __doc__.split()[1] - -__all__ = ['ynbox' - , 'ccbox' - , 'boolbox' - , 'indexbox' - , 'msgbox' - , 'buttonbox' - , 'integerbox' - , 'multenterbox' - , 'enterbox' - , 'exceptionbox' - , 'choicebox' - , 'codebox' - , 'textbox' - , 'diropenbox' - , 'fileopenbox' - , 'filesavebox' - , 'passwordbox' - , 'multpasswordbox' - , 'multchoicebox' - , 'abouteasygui' - , 'egversion' - , 'egdemo' - , 'EgStore' - ] - -import sys, os -import string -import pickle -import traceback - - -#-------------------------------------------------- -# check python version and take appropriate action -#-------------------------------------------------- -""" -From the python documentation: - -sys.hexversion contains the version number encoded as a single integer. This is -guaranteed to increase with each version, including proper support for non- -production releases. For example, to test that the Python interpreter is at -least version 1.5.2, use: - -if sys.hexversion >= 0x010502F0: - # use some advanced feature - ... -else: - # use an alternative implementation or warn the user - ... -""" - - -if sys.hexversion >= 0x020600F0: - runningPython26 = True -else: - runningPython26 = False - -if sys.hexversion >= 0x030000F0: - runningPython3 = True -else: - runningPython3 = False - -try: - from PIL import Image as PILImage - from PIL import ImageTk as PILImageTk - PILisLoaded = True -except: - PILisLoaded = False - - -if runningPython3: - from tkinter import * - import tkinter.filedialog as tk_FileDialog - from io import StringIO -else: - from Tkinter import * - import tkFileDialog as tk_FileDialog - from StringIO import StringIO - -def write(*args): - args = [str(arg) for arg in args] - args = " ".join(args) - sys.stdout.write(args) - -def writeln(*args): - write(*args) - sys.stdout.write("\n") - -say = writeln - - -if TkVersion < 8.0 : - stars = "*"*75 - writeln("""\n\n\n""" + stars + """ -You are running Tk version: """ + str(TkVersion) + """ -You must be using Tk version 8.0 or greater to use EasyGui. -Terminating. -""" + stars + """\n\n\n""") - sys.exit(0) - -def dq(s): - return '"%s"' % s - -rootWindowPosition = "+300+200" - -PROPORTIONAL_FONT_FAMILY = ("MS", "Sans", "Serif") -MONOSPACE_FONT_FAMILY = ("Courier") - -PROPORTIONAL_FONT_SIZE = 10 -MONOSPACE_FONT_SIZE = 9 #a little smaller, because it it more legible at a smaller size -TEXT_ENTRY_FONT_SIZE = 12 # a little larger makes it easier to see - -#STANDARD_SELECTION_EVENTS = ["Return", "Button-1"] -STANDARD_SELECTION_EVENTS = ["Return", "Button-1", "space"] - -# Initialize some global variables that will be reset later -__choiceboxMultipleSelect = None -__widgetTexts = None -__replyButtonText = None -__choiceboxResults = None -__firstWidget = None -__enterboxText = None -__enterboxDefaultText="" -__multenterboxText = "" -choiceboxChoices = None -choiceboxWidget = None -entryWidget = None -boxRoot = None -ImageErrorMsg = ( - "\n\n---------------------------------------------\n" - "Error: %s\n%s") -#------------------------------------------------------------------- -# various boxes built on top of the basic buttonbox -#----------------------------------------------------------------------- - -#----------------------------------------------------------------------- -# ynbox -#----------------------------------------------------------------------- -def ynbox(msg="Shall I continue?" - , title=" " - , choices=("Yes", "No") - , image=None - ): - """ - Display a msgbox with choices of Yes and No. - - The default is "Yes". - - The returned value is calculated this way:: - if the first choice ("Yes") is chosen, or if the dialog is cancelled: - return 1 - else: - return 0 - - If invoked without a msg argument, displays a generic request for a confirmation - that the user wishes to continue. So it can be used this way:: - if ynbox(): pass # continue - else: sys.exit(0) # exit the program - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg choices: a list or tuple of the choices to be displayed - """ - return boolbox(msg, title, choices, image=image) - - -#----------------------------------------------------------------------- -# ccbox -#----------------------------------------------------------------------- -def ccbox(msg="Shall I continue?" - , title=" " - , choices=("Continue", "Cancel") - , image=None - ): - """ - Display a msgbox with choices of Continue and Cancel. - - The default is "Continue". - - The returned value is calculated this way:: - if the first choice ("Continue") is chosen, or if the dialog is cancelled: - return 1 - else: - return 0 - - If invoked without a msg argument, displays a generic request for a confirmation - that the user wishes to continue. So it can be used this way:: - - if ccbox(): - pass # continue - else: - sys.exit(0) # exit the program - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg choices: a list or tuple of the choices to be displayed - """ - return boolbox(msg, title, choices, image=image) - - -#----------------------------------------------------------------------- -# boolbox -#----------------------------------------------------------------------- -def boolbox(msg="Shall I continue?" - , title=" " - , choices=("Yes","No") - , image=None - ): - """ - Display a boolean msgbox. - - The default is the first choice. - - The returned value is calculated this way:: - if the first choice is chosen, or if the dialog is cancelled: - returns 1 - else: - returns 0 - """ - reply = buttonbox(msg=msg, choices=choices, title=title, image=image) - if reply == choices[0]: return 1 - else: return 0 - - -#----------------------------------------------------------------------- -# indexbox -#----------------------------------------------------------------------- -def indexbox(msg="Shall I continue?" - , title=" " - , choices=("Yes","No") - , image=None - ): - """ - Display a buttonbox with the specified choices. - Return the index of the choice selected. - """ - reply = buttonbox(msg=msg, choices=choices, title=title, image=image) - index = -1 - for choice in choices: - index = index + 1 - if reply == choice: return index - raise AssertionError( - "There is a program logic error in the EasyGui code for indexbox.") - - -#----------------------------------------------------------------------- -# msgbox -#----------------------------------------------------------------------- -def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None): - """ - Display a messagebox - """ - if type(ok_button) != type("OK"): - raise AssertionError("The 'ok_button' argument to msgbox must be a string.") - - return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root) - - -#------------------------------------------------------------------- -# buttonbox -#------------------------------------------------------------------- -def buttonbox(msg="",title=" " - ,choices=("Button1", "Button2", "Button3") - , image=None - , root=None - ): - """ - Display a msg, a title, and a set of buttons. - The buttons are defined by the members of the choices list. - Return the text of the button that the user selected. - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg choices: a list or tuple of the choices to be displayed - """ - global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame - - - # Initialize __replyButtonText to the first choice. - # This is what will be used if the window is closed by the close button. - __replyButtonText = choices[0] - - if root: - root.withdraw() - boxRoot = Toplevel(master=root) - boxRoot.withdraw() - else: - boxRoot = Tk() - boxRoot.withdraw() - - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) - boxRoot.title(title) - boxRoot.iconname('Dialog') - boxRoot.geometry(rootWindowPosition) - boxRoot.minsize(400, 100) - - # ------------- define the messageFrame --------------------------------- - messageFrame = Frame(master=boxRoot) - messageFrame.pack(side=TOP, fill=BOTH) - - # ------------- define the imageFrame --------------------------------- - tk_Image = None - if image: - imageFilename = os.path.normpath(image) - junk,ext = os.path.splitext(imageFilename) - - if os.path.exists(imageFilename): - if ext.lower() in [".gif", ".pgm", ".ppm"]: - tk_Image = PhotoImage(master=boxRoot, file=imageFilename) - else: - if PILisLoaded: - try: - pil_Image = PILImage.open(imageFilename) - tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot) - except: - msg += ImageErrorMsg % (imageFilename, - "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image." - "\n\nPIL reports:\n" + exception_format()) - - else: # PIL is not loaded - msg += ImageErrorMsg % (imageFilename, - "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n" - "You may need to install PIL\n" - "(http://www.pythonware.com/products/pil/)\n" - "to display " + ext + " image files.") - - else: - msg += ImageErrorMsg % (imageFilename, "\nImage file not found.") - - if tk_Image: - imageFrame = Frame(master=boxRoot) - imageFrame.pack(side=TOP, fill=BOTH) - label = Label(imageFrame,image=tk_Image) - label.image = tk_Image # keep a reference! - label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m') - - # ------------- define the buttonsFrame --------------------------------- - buttonsFrame = Frame(master=boxRoot) - buttonsFrame.pack(side=TOP, fill=BOTH) - - # -------------------- place the widgets in the frames ----------------------- - messageWidget = Message(messageFrame, text=msg, width=400) - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') - - __put_buttons_in_buttonframe(choices) - - # -------------- the action begins ----------- - # put the focus on the first button - __firstWidget.focus_force() - - boxRoot.deiconify() - boxRoot.mainloop() - boxRoot.destroy() - if root: root.deiconify() - return __replyButtonText - - -#------------------------------------------------------------------- -# integerbox -#------------------------------------------------------------------- -def integerbox(msg="" - , title=" " - , default="" - , lowerbound=0 - , upperbound=99 - , image = None - , root = None - , **invalidKeywordArguments - ): - """ - Show a box in which a user can enter an integer. - - In addition to arguments for msg and title, this function accepts - integer arguments for "default", "lowerbound", and "upperbound". - - The default argument may be None. - - When the user enters some text, the text is checked to verify that it - can be converted to an integer between the lowerbound and upperbound. - - If it can be, the integer (not the text) is returned. - - If it cannot, then an error msg is displayed, and the integerbox is - redisplayed. - - If the user cancels the operation, None is returned. - - NOTE that the "argLowerBound" and "argUpperBound" arguments are no longer - supported. They have been replaced by "upperbound" and "lowerbound". - """ - if "argLowerBound" in invalidKeywordArguments: - raise AssertionError( - "\nintegerbox no longer supports the 'argLowerBound' argument.\n" - + "Use 'lowerbound' instead.\n\n") - if "argUpperBound" in invalidKeywordArguments: - raise AssertionError( - "\nintegerbox no longer supports the 'argUpperBound' argument.\n" - + "Use 'upperbound' instead.\n\n") - - if default != "": - if type(default) != type(1): - raise AssertionError( - "integerbox received a non-integer value for " - + "default of " + dq(str(default)) , "Error") - - if type(lowerbound) != type(1): - raise AssertionError( - "integerbox received a non-integer value for " - + "lowerbound of " + dq(str(lowerbound)) , "Error") - - if type(upperbound) != type(1): - raise AssertionError( - "integerbox received a non-integer value for " - + "upperbound of " + dq(str(upperbound)) , "Error") - - if msg == "": - msg = ("Enter an integer between " + str(lowerbound) - + " and " - + str(upperbound) - ) - - while 1: - reply = enterbox(msg, title, str(default), image=image, root=root) - if reply == None: return None - - try: - reply = int(reply) - except: - msgbox ("The value that you entered:\n\t%s\nis not an integer." % dq(str(reply)) - , "Error") - continue - - if reply < lowerbound: - msgbox ("The value that you entered is less than the lower bound of " - + str(lowerbound) + ".", "Error") - continue - - if reply > upperbound: - msgbox ("The value that you entered is greater than the upper bound of " - + str(upperbound) + ".", "Error") - continue - - # reply has passed all validation checks. - # It is an integer between the specified bounds. - return reply - -#------------------------------------------------------------------- -# multenterbox -#------------------------------------------------------------------- -def multenterbox(msg="Fill in values for the fields." - , title=" " - , fields=() - , values=() - ): - r""" - Show screen with multiple data entry fields. - - If there are fewer values than names, the list of values is padded with - empty strings until the number of values is the same as the number of names. - - If there are more values than names, the list of values - is truncated so that there are as many values as names. - - Returns a list of the values of the fields, - or None if the user cancels the operation. - - Here is some example code, that shows how values returned from - multenterbox can be checked for validity before they are accepted:: - ---------------------------------------------------------------------- - msg = "Enter your personal information" - title = "Credit Card Application" - fieldNames = ["Name","Street Address","City","State","ZipCode"] - fieldValues = [] # we start with blanks for the values - fieldValues = multenterbox(msg,title, fieldNames) - - # make sure that none of the fields was left blank - while 1: - if fieldValues == None: break - errmsg = "" - for i in range(len(fieldNames)): - if fieldValues[i].strip() == "": - errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) - if errmsg == "": - break # no problems found - fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) - - writeln("Reply was: %s" % str(fieldValues)) - ---------------------------------------------------------------------- - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg fields: a list of fieldnames. - @arg values: a list of field values - """ - return __multfillablebox(msg,title,fields,values,None) - - -#----------------------------------------------------------------------- -# multpasswordbox -#----------------------------------------------------------------------- -def multpasswordbox(msg="Fill in values for the fields." - , title=" " - , fields=tuple() - ,values=tuple() - ): - r""" - Same interface as multenterbox. But in multpassword box, - the last of the fields is assumed to be a password, and - is masked with asterisks. - - Example - ======= - - Here is some example code, that shows how values returned from - multpasswordbox can be checked for validity before they are accepted:: - msg = "Enter logon information" - title = "Demo of multpasswordbox" - fieldNames = ["Server ID", "User ID", "Password"] - fieldValues = [] # we start with blanks for the values - fieldValues = multpasswordbox(msg,title, fieldNames) - - # make sure that none of the fields was left blank - while 1: - if fieldValues == None: break - errmsg = "" - for i in range(len(fieldNames)): - if fieldValues[i].strip() == "": - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) - if errmsg == "": break # no problems found - fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) - - writeln("Reply was: %s" % str(fieldValues)) - """ - return __multfillablebox(msg,title,fields,values,"*") - -def bindArrows(widget): - widget.bind("", tabRight) - widget.bind("" , tabLeft) - - widget.bind("",tabRight) - widget.bind("" , tabLeft) - -def tabRight(event): - boxRoot.event_generate("") - -def tabLeft(event): - boxRoot.event_generate("") - -#----------------------------------------------------------------------- -# __multfillablebox -#----------------------------------------------------------------------- -def __multfillablebox(msg="Fill in values for the fields." - , title=" " - , fields=() - , values=() - , mask = None - ): - global boxRoot, __multenterboxText, __multenterboxDefaultText, cancelButton, entryWidget, okButton - - choices = ["OK", "Cancel"] - if len(fields) == 0: return None - - fields = list(fields[:]) # convert possible tuples to a list - values = list(values[:]) # convert possible tuples to a list - - if len(values) == len(fields): pass - elif len(values) > len(fields): - fields = fields[0:len(values)] - else: - while len(values) < len(fields): - values.append("") - - boxRoot = Tk() - - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) - boxRoot.title(title) - boxRoot.iconname('Dialog') - boxRoot.geometry(rootWindowPosition) - boxRoot.bind("", __multenterboxCancel) - - # -------------------- put subframes in the boxRoot -------------------- - messageFrame = Frame(master=boxRoot) - messageFrame.pack(side=TOP, fill=BOTH) - - #-------------------- the msg widget ---------------------------- - messageWidget = Message(messageFrame, width="4.5i", text=msg) - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m') - - global entryWidgets - entryWidgets = [] - - lastWidgetIndex = len(fields) - 1 - - for widgetIndex in range(len(fields)): - argFieldName = fields[widgetIndex] - argFieldValue = values[widgetIndex] - entryFrame = Frame(master=boxRoot) - entryFrame.pack(side=TOP, fill=BOTH) - - # --------- entryWidget ---------------------------------------------- - labelWidget = Label(entryFrame, text=argFieldName) - labelWidget.pack(side=LEFT) - - entryWidget = Entry(entryFrame, width=40,highlightthickness=2) - entryWidgets.append(entryWidget) - entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE)) - entryWidget.pack(side=RIGHT, padx="3m") - - bindArrows(entryWidget) - - entryWidget.bind("", __multenterboxGetText) - entryWidget.bind("", __multenterboxCancel) - - # for the last entryWidget, if this is a multpasswordbox, - # show the contents as just asterisks - if widgetIndex == lastWidgetIndex: - if mask: - entryWidgets[widgetIndex].configure(show=mask) - - # put text into the entryWidget - entryWidgets[widgetIndex].insert(0,argFieldValue) - widgetIndex += 1 - - # ------------------ ok button ------------------------------- - buttonsFrame = Frame(master=boxRoot) - buttonsFrame.pack(side=BOTTOM, fill=BOTH) - - okButton = Button(buttonsFrame, takefocus=1, text="OK") - bindArrows(okButton) - okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m') - - # for the commandButton, bind activation events to the activation event handler - commandButton = okButton - handler = __multenterboxGetText - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - - # ------------------ cancel button ------------------------------- - cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel") - bindArrows(cancelButton) - cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m') - - # for the commandButton, bind activation events to the activation event handler - commandButton = cancelButton - handler = __multenterboxCancel - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - - # ------------------- time for action! ----------------- - entryWidgets[0].focus_force() # put the focus on the entryWidget - boxRoot.mainloop() # run it! - - # -------- after the run has completed ---------------------------------- - boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now - return __multenterboxText - - -#----------------------------------------------------------------------- -# __multenterboxGetText -#----------------------------------------------------------------------- -def __multenterboxGetText(event): - global __multenterboxText - - __multenterboxText = [] - for entryWidget in entryWidgets: - __multenterboxText.append(entryWidget.get()) - boxRoot.quit() - - -def __multenterboxCancel(event): - global __multenterboxText - __multenterboxText = None - boxRoot.quit() - - -#------------------------------------------------------------------- -# enterbox -#------------------------------------------------------------------- -def enterbox(msg="Enter something." - , title=" " - , default="" - , strip=True - , image=None - , root=None - ): - """ - Show a box in which a user can enter some text. - - You may optionally specify some default text, which will appear in the - enterbox when it is displayed. - - Returns the text that the user entered, or None if he cancels the operation. - - By default, enterbox strips its result (i.e. removes leading and trailing - whitespace). (If you want it not to strip, use keyword argument: strip=False.) - This makes it easier to test the results of the call:: - - reply = enterbox(....) - if reply: - ... - else: - ... - """ - result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root) - if result and strip: - result = result.strip() - return result - - -def passwordbox(msg="Enter your password." - , title=" " - , default="" - , image=None - , root=None - ): - """ - Show a box in which a user can enter a password. - The text is masked with asterisks, so the password is not displayed. - Returns the text that the user entered, or None if he cancels the operation. - """ - return __fillablebox(msg, title, default, mask="*",image=image,root=root) - - -def __fillablebox(msg - , title="" - , default="" - , mask=None - , image=None - , root=None - ): - """ - Show a box in which a user can enter some text. - You may optionally specify some default text, which will appear in the - enterbox when it is displayed. - Returns the text that the user entered, or None if he cancels the operation. - """ - - global boxRoot, __enterboxText, __enterboxDefaultText - global cancelButton, entryWidget, okButton - - if title == None: title == "" - if default == None: default = "" - __enterboxDefaultText = default - __enterboxText = __enterboxDefaultText - - if root: - root.withdraw() - boxRoot = Toplevel(master=root) - boxRoot.withdraw() - else: - boxRoot = Tk() - boxRoot.withdraw() - - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) - boxRoot.title(title) - boxRoot.iconname('Dialog') - boxRoot.geometry(rootWindowPosition) - boxRoot.bind("", __enterboxCancel) - - # ------------- define the messageFrame --------------------------------- - messageFrame = Frame(master=boxRoot) - messageFrame.pack(side=TOP, fill=BOTH) - - # ------------- define the imageFrame --------------------------------- - tk_Image = None - if image: - imageFilename = os.path.normpath(image) - junk,ext = os.path.splitext(imageFilename) - - if os.path.exists(imageFilename): - if ext.lower() in [".gif", ".pgm", ".ppm"]: - tk_Image = PhotoImage(master=boxRoot, file=imageFilename) - else: - if PILisLoaded: - try: - pil_Image = PILImage.open(imageFilename) - tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot) - except: - msg += ImageErrorMsg % (imageFilename, - "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image." - "\n\nPIL reports:\n" + exception_format()) - - else: # PIL is not loaded - msg += ImageErrorMsg % (imageFilename, - "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n" - "You may need to install PIL\n" - "(http://www.pythonware.com/products/pil/)\n" - "to display " + ext + " image files.") - - else: - msg += ImageErrorMsg % (imageFilename, "\nImage file not found.") - - if tk_Image: - imageFrame = Frame(master=boxRoot) - imageFrame.pack(side=TOP, fill=BOTH) - label = Label(imageFrame,image=tk_Image) - label.image = tk_Image # keep a reference! - label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m') - - # ------------- define the buttonsFrame --------------------------------- - buttonsFrame = Frame(master=boxRoot) - buttonsFrame.pack(side=TOP, fill=BOTH) - - - # ------------- define the entryFrame --------------------------------- - entryFrame = Frame(master=boxRoot) - entryFrame.pack(side=TOP, fill=BOTH) - - # ------------- define the buttonsFrame --------------------------------- - buttonsFrame = Frame(master=boxRoot) - buttonsFrame.pack(side=TOP, fill=BOTH) - - #-------------------- the msg widget ---------------------------- - messageWidget = Message(messageFrame, width="4.5i", text=msg) - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m') - - # --------- entryWidget ---------------------------------------------- - entryWidget = Entry(entryFrame, width=40) - bindArrows(entryWidget) - entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE)) - if mask: - entryWidget.configure(show=mask) - entryWidget.pack(side=LEFT, padx="3m") - entryWidget.bind("", __enterboxGetText) - entryWidget.bind("", __enterboxCancel) - # put text into the entryWidget - entryWidget.insert(0,__enterboxDefaultText) - - # ------------------ ok button ------------------------------- - okButton = Button(buttonsFrame, takefocus=1, text="OK") - bindArrows(okButton) - okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m') - - # for the commandButton, bind activation events to the activation event handler - commandButton = okButton - handler = __enterboxGetText - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - - # ------------------ cancel button ------------------------------- - cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel") - bindArrows(cancelButton) - cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m') - - # for the commandButton, bind activation events to the activation event handler - commandButton = cancelButton - handler = __enterboxCancel - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - # ------------------- time for action! ----------------- - entryWidget.focus_force() # put the focus on the entryWidget - boxRoot.deiconify() - boxRoot.mainloop() # run it! - - # -------- after the run has completed ---------------------------------- - if root: root.deiconify() - boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now - return __enterboxText - - -def __enterboxGetText(event): - global __enterboxText - - __enterboxText = entryWidget.get() - boxRoot.quit() - - -def __enterboxRestore(event): - global entryWidget - - entryWidget.delete(0,len(entryWidget.get())) - entryWidget.insert(0, __enterboxDefaultText) - - -def __enterboxCancel(event): - global __enterboxText - - __enterboxText = None - boxRoot.quit() - -def denyWindowManagerClose(): - """ don't allow WindowManager close - """ - x = Tk() - x.withdraw() - x.bell() - x.destroy() - - - -#------------------------------------------------------------------- -# multchoicebox -#------------------------------------------------------------------- -def multchoicebox(msg="Pick as many items as you like." - , title=" " - , choices=() - , **kwargs - ): - """ - Present the user with a list of choices. - allow him to select multiple items and return them in a list. - if the user doesn't choose anything from the list, return the empty list. - return None if he cancelled selection. - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg choices: a list or tuple of the choices to be displayed - """ - if len(choices) == 0: choices = ["Program logic error - no choices were specified."] - - global __choiceboxMultipleSelect - __choiceboxMultipleSelect = 1 - return __choicebox(msg, title, choices) - - -#----------------------------------------------------------------------- -# choicebox -#----------------------------------------------------------------------- -def choicebox(msg="Pick something." - , title=" " - , choices=() - ): - """ - Present the user with a list of choices. - return the choice that he selects. - return None if he cancels the selection selection. - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg choices: a list or tuple of the choices to be displayed - """ - if len(choices) == 0: choices = ["Program logic error - no choices were specified."] - - global __choiceboxMultipleSelect - __choiceboxMultipleSelect = 0 - return __choicebox(msg,title,choices) - - -#----------------------------------------------------------------------- -# __choicebox -#----------------------------------------------------------------------- -def __choicebox(msg - , title - , choices - ): - """ - internal routine to support choicebox() and multchoicebox() - """ - global boxRoot, __choiceboxResults, choiceboxWidget, defaultText - global choiceboxWidget, choiceboxChoices - #------------------------------------------------------------------- - # If choices is a tuple, we make it a list so we can sort it. - # If choices is already a list, we make a new list, so that when - # we sort the choices, we don't affect the list object that we - # were given. - #------------------------------------------------------------------- - choices = list(choices[:]) - if len(choices) == 0: - choices = ["Program logic error - no choices were specified."] - defaultButtons = ["OK", "Cancel"] - - # make sure all choices are strings - for index in range(len(choices)): - choices[index] = str(choices[index]) - - lines_to_show = min(len(choices), 20) - lines_to_show = 20 - - if title == None: title = "" - - # Initialize __choiceboxResults - # This is the value that will be returned if the user clicks the close icon - __choiceboxResults = None - - boxRoot = Tk() - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) - screen_width = boxRoot.winfo_screenwidth() - screen_height = boxRoot.winfo_screenheight() - root_width = int((screen_width * 0.8)) - root_height = int((screen_height * 0.5)) - root_xpos = int((screen_width * 0.1)) - root_ypos = int((screen_height * 0.05)) - - boxRoot.title(title) - boxRoot.iconname('Dialog') - rootWindowPosition = "+0+0" - boxRoot.geometry(rootWindowPosition) - boxRoot.expand=NO - boxRoot.minsize(root_width, root_height) - rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos) - boxRoot.geometry(rootWindowPosition) - - # ---------------- put the frames in the window ----------------------------------------- - message_and_buttonsFrame = Frame(master=boxRoot) - message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO) - - messageFrame = Frame(message_and_buttonsFrame) - messageFrame.pack(side=LEFT, fill=X, expand=YES) - #messageFrame.pack(side=TOP, fill=X, expand=YES) - - buttonsFrame = Frame(message_and_buttonsFrame) - buttonsFrame.pack(side=RIGHT, expand=NO, pady=0) - #buttonsFrame.pack(side=TOP, expand=YES, pady=0) - - choiceboxFrame = Frame(master=boxRoot) - choiceboxFrame.pack(side=BOTTOM, fill=BOTH, expand=YES) - - # -------------------------- put the widgets in the frames ------------------------------ - - # ---------- put a msg widget in the msg frame------------------- - messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9)) - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m') - - # -------- put the choiceboxWidget in the choiceboxFrame --------------------------- - choiceboxWidget = Listbox(choiceboxFrame - , height=lines_to_show - , borderwidth="1m" - , relief="flat" - , bg="white" - ) - - if __choiceboxMultipleSelect: - choiceboxWidget.configure(selectmode=MULTIPLE) - - choiceboxWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - - # add a vertical scrollbar to the frame - rightScrollbar = Scrollbar(choiceboxFrame, orient=VERTICAL, command=choiceboxWidget.yview) - choiceboxWidget.configure(yscrollcommand = rightScrollbar.set) - - # add a horizontal scrollbar to the frame - bottomScrollbar = Scrollbar(choiceboxFrame, orient=HORIZONTAL, command=choiceboxWidget.xview) - choiceboxWidget.configure(xscrollcommand = bottomScrollbar.set) - - # pack the Listbox and the scrollbars. Note that although we must define - # the textArea first, we must pack it last, so that the bottomScrollbar will - # be located properly. - - bottomScrollbar.pack(side=BOTTOM, fill = X) - rightScrollbar.pack(side=RIGHT, fill = Y) - - choiceboxWidget.pack(side=LEFT, padx="1m", pady="1m", expand=YES, fill=BOTH) - - #--------------------------------------------------- - # sort the choices - # eliminate duplicates - # put the choices into the choiceboxWidget - #--------------------------------------------------- - for index in range(len(choices)): - choices[index] = str(choices[index]) - - if runningPython3: - choices.sort(key=str.lower) - else: - choices.sort( lambda x,y: cmp(x.lower(), y.lower())) # case-insensitive sort - - lastInserted = None - choiceboxChoices = [] - for choice in choices: - if choice == lastInserted: pass - else: - choiceboxWidget.insert(END, choice) - choiceboxChoices.append(choice) - lastInserted = choice - - boxRoot.bind('', KeyboardListener) - - # put the buttons in the buttonsFrame - if len(choices) > 0: - okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6) - bindArrows(okButton) - okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") - - # for the commandButton, bind activation events to the activation event handler - commandButton = okButton - handler = __choiceboxGetChoice - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - # now bind the keyboard events - choiceboxWidget.bind("", __choiceboxGetChoice) - choiceboxWidget.bind("", __choiceboxGetChoice) - else: - # now bind the keyboard events - choiceboxWidget.bind("", __choiceboxCancel) - choiceboxWidget.bind("", __choiceboxCancel) - - cancelButton = Button(buttonsFrame, takefocus=YES, text="Cancel", height=1, width=6) - bindArrows(cancelButton) - cancelButton.pack(expand=NO, side=BOTTOM, padx='2m', pady='1m', ipady="1m", ipadx="2m") - - # for the commandButton, bind activation events to the activation event handler - commandButton = cancelButton - handler = __choiceboxCancel - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - - - # add special buttons for multiple select features - if len(choices) > 0 and __choiceboxMultipleSelect: - selectionButtonsFrame = Frame(messageFrame) - selectionButtonsFrame.pack(side=RIGHT, fill=Y, expand=NO) - - selectAllButton = Button(selectionButtonsFrame, text="Select All", height=1, width=6) - bindArrows(selectAllButton) - - selectAllButton.bind("",__choiceboxSelectAll) - selectAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") - - clearAllButton = Button(selectionButtonsFrame, text="Clear All", height=1, width=6) - bindArrows(clearAllButton) - clearAllButton.bind("",__choiceboxClearAll) - clearAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") - - - # -------------------- bind some keyboard events ---------------------------- - boxRoot.bind("", __choiceboxCancel) - - # --------------------- the action begins ----------------------------------- - # put the focus on the choiceboxWidget, and the select highlight on the first item - choiceboxWidget.select_set(0) - choiceboxWidget.focus_force() - - # --- run it! ----- - boxRoot.mainloop() - - boxRoot.destroy() - return __choiceboxResults - - -def __choiceboxGetChoice(event): - global boxRoot, __choiceboxResults, choiceboxWidget - - if __choiceboxMultipleSelect: - __choiceboxResults = [choiceboxWidget.get(index) for index in choiceboxWidget.curselection()] - - else: - choice_index = choiceboxWidget.curselection() - __choiceboxResults = choiceboxWidget.get(choice_index) - - # writeln("Debugging> mouse-event=", event, " event.type=", event.type) - # writeln("Debugging> choice=", choice_index, __choiceboxResults) - boxRoot.quit() - - -def __choiceboxSelectAll(event): - global choiceboxWidget, choiceboxChoices - - choiceboxWidget.selection_set(0, len(choiceboxChoices)-1) - -def __choiceboxClearAll(event): - global choiceboxWidget, choiceboxChoices - - choiceboxWidget.selection_clear(0, len(choiceboxChoices)-1) - - - -def __choiceboxCancel(event): - global boxRoot, __choiceboxResults - - __choiceboxResults = None - boxRoot.quit() - - -def KeyboardListener(event): - global choiceboxChoices, choiceboxWidget - key = event.keysym - if len(key) <= 1: - if key in string.printable: - # Find the key in the list. - # before we clear the list, remember the selected member - try: - start_n = int(choiceboxWidget.curselection()[0]) - except IndexError: - start_n = -1 - - ## clear the selection. - choiceboxWidget.selection_clear(0, 'end') - - ## start from previous selection +1 - for n in range(start_n+1, len(choiceboxChoices)): - item = choiceboxChoices[n] - if item[0].lower() == key.lower(): - choiceboxWidget.selection_set(first=n) - choiceboxWidget.see(n) - return - else: - # has not found it so loop from top - for n in range(len(choiceboxChoices)): - item = choiceboxChoices[n] - if item[0].lower() == key.lower(): - choiceboxWidget.selection_set(first = n) - choiceboxWidget.see(n) - return - - # nothing matched -- we'll look for the next logical choice - for n in range(len(choiceboxChoices)): - item = choiceboxChoices[n] - if item[0].lower() > key.lower(): - if n > 0: - choiceboxWidget.selection_set(first = (n-1)) - else: - choiceboxWidget.selection_set(first = 0) - choiceboxWidget.see(n) - return - - # still no match (nothing was greater than the key) - # we set the selection to the first item in the list - lastIndex = len(choiceboxChoices)-1 - choiceboxWidget.selection_set(first = lastIndex) - choiceboxWidget.see(lastIndex) - return - -#----------------------------------------------------------------------- -# exception_format -#----------------------------------------------------------------------- -def exception_format(): - """ - Convert exception info into a string suitable for display. - """ - return "".join(traceback.format_exception( - sys.exc_info()[0] - , sys.exc_info()[1] - , sys.exc_info()[2] - )) - -#----------------------------------------------------------------------- -# exceptionbox -#----------------------------------------------------------------------- -def exceptionbox(msg=None, title=None): - """ - Display a box that gives information about - an exception that has just been raised. - - The caller may optionally pass in a title for the window, or a - msg to accompany the error information. - - Note that you do not need to (and cannot) pass an exception object - as an argument. The latest exception will automatically be used. - """ - if title == None: title = "Error Report" - if msg == None: - msg = "An error (exception) has occurred in the program." - - codebox(msg, title, exception_format()) - -#------------------------------------------------------------------- -# codebox -#------------------------------------------------------------------- - -def codebox(msg="" - , title=" " - , text="" - ): - """ - Display some text in a monospaced font, with no line wrapping. - This function is suitable for displaying code and text that is - formatted using spaces. - - The text parameter should be a string, or a list or tuple of lines to be - displayed in the textbox. - """ - return textbox(msg, title, text, codebox=1 ) - -#------------------------------------------------------------------- -# textbox -#------------------------------------------------------------------- -def textbox(msg="" - , title=" " - , text="" - , codebox=0 - ): - """ - Display some text in a proportional font with line wrapping at word breaks. - This function is suitable for displaying general written text. - - The text parameter should be a string, or a list or tuple of lines to be - displayed in the textbox. - """ - - if msg == None: msg = "" - if title == None: title = "" - - global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame - global rootWindowPosition - choices = ["OK"] - __replyButtonText = choices[0] - - - boxRoot = Tk() - - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) - - screen_width = boxRoot.winfo_screenwidth() - screen_height = boxRoot.winfo_screenheight() - root_width = int((screen_width * 0.8)) - root_height = int((screen_height * 0.5)) - root_xpos = int((screen_width * 0.1)) - root_ypos = int((screen_height * 0.05)) - - boxRoot.title(title) - boxRoot.iconname('Dialog') - rootWindowPosition = "+0+0" - boxRoot.geometry(rootWindowPosition) - boxRoot.expand=NO - boxRoot.minsize(root_width, root_height) - rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos) - boxRoot.geometry(rootWindowPosition) - - mainframe = Frame(master=boxRoot) - mainframe.pack(side=TOP, fill=BOTH, expand=YES) - - # ---- put frames in the window ----------------------------------- - # we pack the textboxFrame first, so it will expand first - textboxFrame = Frame(mainframe, borderwidth=3) - textboxFrame.pack(side=BOTTOM , fill=BOTH, expand=YES) - - message_and_buttonsFrame = Frame(mainframe) - message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO) - - messageFrame = Frame(message_and_buttonsFrame) - messageFrame.pack(side=LEFT, fill=X, expand=YES) - - buttonsFrame = Frame(message_and_buttonsFrame) - buttonsFrame.pack(side=RIGHT, expand=NO) - - # -------------------- put widgets in the frames -------------------- - - # put a textArea in the top frame - if codebox: - character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE) - textArea = Text(textboxFrame,height=25,width=character_width, padx="2m", pady="1m") - textArea.configure(wrap=NONE) - textArea.configure(font=(MONOSPACE_FONT_FAMILY, MONOSPACE_FONT_SIZE)) - - else: - character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE) - textArea = Text( - textboxFrame - , height=25 - , width=character_width - , padx="2m" - , pady="1m" - ) - textArea.configure(wrap=WORD) - textArea.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - - - # some simple keybindings for scrolling - mainframe.bind("" , textArea.yview_scroll( 1,PAGES)) - mainframe.bind("", textArea.yview_scroll(-1,PAGES)) - - mainframe.bind("", textArea.xview_scroll( 1,PAGES)) - mainframe.bind("" , textArea.xview_scroll(-1,PAGES)) - - mainframe.bind("", textArea.yview_scroll( 1,UNITS)) - mainframe.bind("" , textArea.yview_scroll(-1,UNITS)) - - - # add a vertical scrollbar to the frame - rightScrollbar = Scrollbar(textboxFrame, orient=VERTICAL, command=textArea.yview) - textArea.configure(yscrollcommand = rightScrollbar.set) - - # add a horizontal scrollbar to the frame - bottomScrollbar = Scrollbar(textboxFrame, orient=HORIZONTAL, command=textArea.xview) - textArea.configure(xscrollcommand = bottomScrollbar.set) - - # pack the textArea and the scrollbars. Note that although we must define - # the textArea first, we must pack it last, so that the bottomScrollbar will - # be located properly. - - # Note that we need a bottom scrollbar only for code. - # Text will be displayed with wordwrap, so we don't need to have a horizontal - # scroll for it. - if codebox: - bottomScrollbar.pack(side=BOTTOM, fill=X) - rightScrollbar.pack(side=RIGHT, fill=Y) - - textArea.pack(side=LEFT, fill=BOTH, expand=YES) - - - # ---------- put a msg widget in the msg frame------------------- - messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9)) - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) - messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m') - - # put the buttons in the buttonsFrame - okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6) - okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") - - # for the commandButton, bind activation events to the activation event handler - commandButton = okButton - handler = __textboxOK - for selectionEvent in ["Return","Button-1","Escape"]: - commandButton.bind("<%s>" % selectionEvent, handler) - - - # ----------------- the action begins ---------------------------------------- - try: - # load the text into the textArea - if type(text) == type("abc"): pass - else: - try: - text = "".join(text) # convert a list or a tuple to a string - except: - msgbox("Exception when trying to convert "+ str(type(text)) + " to text in textArea") - sys.exit(16) - textArea.insert(END,text, "normal") - - except: - msgbox("Exception when trying to load the textArea.") - sys.exit(16) - - try: - okButton.focus_force() - except: - msgbox("Exception when trying to put focus on okButton.") - sys.exit(16) - - boxRoot.mainloop() - - # this line MUST go before the line that destroys boxRoot - areaText = textArea.get(0.0,END) - boxRoot.destroy() - return areaText # return __replyButtonText - -#------------------------------------------------------------------- -# __textboxOK -#------------------------------------------------------------------- -def __textboxOK(event): - global boxRoot - boxRoot.quit() - - - -#------------------------------------------------------------------- -# diropenbox -#------------------------------------------------------------------- -def diropenbox(msg=None - , title=None - , default=None - ): - """ - A dialog to get a directory name. - Note that the msg argument, if specified, is ignored. - - Returns the name of a directory, or None if user chose to cancel. - - If the "default" argument specifies a directory name, and that - directory exists, then the dialog box will start with that directory. - """ - title=getFileDialogTitle(msg,title) - localRoot = Tk() - localRoot.withdraw() - if not default: default = None - f = tk_FileDialog.askdirectory( - parent=localRoot - , title=title - , initialdir=default - , initialfile=None - ) - localRoot.destroy() - if not f: return None - return os.path.normpath(f) - - - -#------------------------------------------------------------------- -# getFileDialogTitle -#------------------------------------------------------------------- -def getFileDialogTitle(msg - , title - ): - if msg and title: return "%s - %s" % (title,msg) - if msg and not title: return str(msg) - if title and not msg: return str(title) - return None # no message and no title - -#------------------------------------------------------------------- -# class FileTypeObject for use with fileopenbox -#------------------------------------------------------------------- -class FileTypeObject: - def __init__(self,filemask): - if len(filemask) == 0: - raise AssertionError('Filetype argument is empty.') - - self.masks = [] - - if type(filemask) == type("abc"): # a string - self.initializeFromString(filemask) - - elif type(filemask) == type([]): # a list - if len(filemask) < 2: - raise AssertionError('Invalid filemask.\n' - +'List contains less than 2 members: "%s"' % filemask) - else: - self.name = filemask[-1] - self.masks = list(filemask[:-1] ) - else: - raise AssertionError('Invalid filemask: "%s"' % filemask) - - def __eq__(self,other): - if self.name == other.name: return True - return False - - def add(self,other): - for mask in other.masks: - if mask in self.masks: pass - else: self.masks.append(mask) - - def toTuple(self): - return (self.name,tuple(self.masks)) - - def isAll(self): - if self.name == "All files": return True - return False - - def initializeFromString(self, filemask): - # remove everything except the extension from the filemask - self.ext = os.path.splitext(filemask)[1] - if self.ext == "" : self.ext = ".*" - if self.ext == ".": self.ext = ".*" - self.name = self.getName() - self.masks = ["*" + self.ext] - - def getName(self): - e = self.ext - if e == ".*" : return "All files" - if e == ".txt": return "Text files" - if e == ".py" : return "Python files" - if e == ".pyc" : return "Python files" - if e == ".xls": return "Excel files" - if e.startswith("."): - return e[1:].upper() + " files" - return e.upper() + " files" - - -#------------------------------------------------------------------- -# fileopenbox -#------------------------------------------------------------------- -def fileopenbox(msg=None - , title=None - , default="*" - , filetypes=None - ): - """ - A dialog to get a file name. - - About the "default" argument - ============================ - The "default" argument specifies a filepath that (normally) - contains one or more wildcards. - fileopenbox will display only files that match the default filepath. - If omitted, defaults to "*" (all files in the current directory). - - WINDOWS EXAMPLE:: - ...default="c:/myjunk/*.py" - will open in directory c:\myjunk\ and show all Python files. - - WINDOWS EXAMPLE:: - ...default="c:/myjunk/test*.py" - will open in directory c:\myjunk\ and show all Python files - whose names begin with "test". - - - Note that on Windows, fileopenbox automatically changes the path - separator to the Windows path separator (backslash). - - About the "filetypes" argument - ============================== - If specified, it should contain a list of items, - where each item is either:: - - a string containing a filemask # e.g. "*.txt" - - a list of strings, where all of the strings except the last one - are filemasks (each beginning with "*.", - such as "*.txt" for text files, "*.py" for Python files, etc.). - and the last string contains a filetype description - - EXAMPLE:: - filetypes = ["*.css", ["*.htm", "*.html", "HTML files"] ] - - NOTE THAT - ========= - - If the filetypes list does not contain ("All files","*"), - it will be added. - - If the filetypes list does not contain a filemask that includes - the extension of the "default" argument, it will be added. - For example, if default="*abc.py" - and no filetypes argument was specified, then - "*.py" will automatically be added to the filetypes argument. - - @rtype: string or None - @return: the name of a file, or None if user chose to cancel - - @arg msg: the msg to be displayed. - @arg title: the window title - @arg default: filepath with wildcards - @arg filetypes: filemasks that a user can choose, e.g. "*.txt" - """ - localRoot = Tk() - localRoot.withdraw() - - initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) - - #------------------------------------------------------------ - # if initialfile contains no wildcards; we don't want an - # initial file. It won't be used anyway. - # Also: if initialbase is simply "*", we don't want an - # initialfile; it is not doing any useful work. - #------------------------------------------------------------ - if (initialfile.find("*") < 0) and (initialfile.find("?") < 0): - initialfile = None - elif initialbase == "*": - initialfile = None - - f = tk_FileDialog.askopenfilename(parent=localRoot - , title=getFileDialogTitle(msg,title) - , initialdir=initialdir - , initialfile=initialfile - , filetypes=filetypes - ) - - localRoot.destroy() - - if not f: return None - return os.path.normpath(f) - - -#------------------------------------------------------------------- -# filesavebox -#------------------------------------------------------------------- -def filesavebox(msg=None - , title=None - , default="" - , filetypes=None - ): - """ - A file to get the name of a file to save. - Returns the name of a file, or None if user chose to cancel. - - The "default" argument should contain a filename (i.e. the - current name of the file to be saved). It may also be empty, - or contain a filemask that includes wildcards. - - The "filetypes" argument works like the "filetypes" argument to - fileopenbox. - """ - - localRoot = Tk() - localRoot.withdraw() - - initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) - - f = tk_FileDialog.asksaveasfilename(parent=localRoot - , title=getFileDialogTitle(msg,title) - , initialfile=initialfile - , initialdir=initialdir - , filetypes=filetypes - ) - localRoot.destroy() - if not f: return None - return os.path.normpath(f) - - -#------------------------------------------------------------------- -# -# fileboxSetup -# -#------------------------------------------------------------------- -def fileboxSetup(default,filetypes): - if not default: default = os.path.join(".","*") - initialdir, initialfile = os.path.split(default) - if not initialdir : initialdir = "." - if not initialfile: initialfile = "*" - initialbase, initialext = os.path.splitext(initialfile) - initialFileTypeObject = FileTypeObject(initialfile) - - allFileTypeObject = FileTypeObject("*") - ALL_filetypes_was_specified = False - - if not filetypes: filetypes= [] - filetypeObjects = [] - - for filemask in filetypes: - fto = FileTypeObject(filemask) - - if fto.isAll(): - ALL_filetypes_was_specified = True # remember this - - if fto == initialFileTypeObject: - initialFileTypeObject.add(fto) # add fto to initialFileTypeObject - else: - filetypeObjects.append(fto) - - #------------------------------------------------------------------ - # make sure that the list of filetypes includes the ALL FILES type. - #------------------------------------------------------------------ - if ALL_filetypes_was_specified: - pass - elif allFileTypeObject == initialFileTypeObject: - pass - else: - filetypeObjects.insert(0,allFileTypeObject) - #------------------------------------------------------------------ - # Make sure that the list includes the initialFileTypeObject - # in the position in the list that will make it the default. - # This changed between Python version 2.5 and 2.6 - #------------------------------------------------------------------ - if len(filetypeObjects) == 0: - filetypeObjects.append(initialFileTypeObject) - - if initialFileTypeObject in (filetypeObjects[0], filetypeObjects[-1]): - pass - else: - if runningPython26: - filetypeObjects.append(initialFileTypeObject) - else: - filetypeObjects.insert(0,initialFileTypeObject) - - filetypes = [fto.toTuple() for fto in filetypeObjects] - - return initialbase, initialfile, initialdir, filetypes - -#------------------------------------------------------------------- -# utility routines -#------------------------------------------------------------------- -# These routines are used by several other functions in the EasyGui module. - -def __buttonEvent(event): - """ - Handle an event that is generated by a person clicking a button. - """ - global boxRoot, __widgetTexts, __replyButtonText - __replyButtonText = __widgetTexts[event.widget] - boxRoot.quit() # quit the main loop - - -def __put_buttons_in_buttonframe(choices): - """Put the buttons in the buttons frame - """ - global __widgetTexts, __firstWidget, buttonsFrame - - __firstWidget = None - __widgetTexts = {} - - i = 0 - - for buttonText in choices: - tempButton = Button(buttonsFrame, takefocus=1, text=buttonText) - bindArrows(tempButton) - tempButton.pack(expand=YES, side=LEFT, padx='1m', pady='1m', ipadx='2m', ipady='1m') - - # remember the text associated with this widget - __widgetTexts[tempButton] = buttonText - - # remember the first widget, so we can put the focus there - if i == 0: - __firstWidget = tempButton - i = 1 - - # for the commandButton, bind activation events to the activation event handler - commandButton = tempButton - handler = __buttonEvent - for selectionEvent in STANDARD_SELECTION_EVENTS: - commandButton.bind("<%s>" % selectionEvent, handler) - -#----------------------------------------------------------------------- -# -# class EgStore -# -#----------------------------------------------------------------------- -class EgStore: - r""" -A class to support persistent storage. - -You can use EgStore to support the storage and retrieval -of user settings for an EasyGui application. - - -# Example A -#----------------------------------------------------------------------- -# define a class named Settings as a subclass of EgStore -#----------------------------------------------------------------------- -class Settings(EgStore): -:: - def __init__(self, filename): # filename is required - #------------------------------------------------- - # Specify default/initial values for variables that - # this particular application wants to remember. - #------------------------------------------------- - self.userId = "" - self.targetServer = "" - - #------------------------------------------------- - # For subclasses of EgStore, these must be - # the last two statements in __init__ - #------------------------------------------------- - self.filename = filename # this is required - self.restore() # restore values from the storage file if possible - - - -# Example B -#----------------------------------------------------------------------- -# create settings, a persistent Settings object -#----------------------------------------------------------------------- -settingsFile = "myApp_settings.txt" -settings = Settings(settingsFile) - -user = "obama_barak" -server = "whitehouse1" -settings.userId = user -settings.targetServer = server -settings.store() # persist the settings - -# run code that gets a new value for userId, and persist the settings -user = "biden_joe" -settings.userId = user -settings.store() - - -# Example C -#----------------------------------------------------------------------- -# recover the Settings instance, change an attribute, and store it again. -#----------------------------------------------------------------------- -settings = Settings(settingsFile) -settings.userId = "vanrossum_g" -settings.store() - -""" - def __init__(self, filename): # obtaining filename is required - self.filename = None - raise NotImplementedError() - - def restore(self): - """ - Set the values of whatever attributes are recoverable - from the pickle file. - - Populate the attributes (the __dict__) of the EgStore object - from the attributes (the __dict__) of the pickled object. - - If the pickled object has attributes that have been initialized - in the EgStore object, then those attributes of the EgStore object - will be replaced by the values of the corresponding attributes - in the pickled object. - - If the pickled object is missing some attributes that have - been initialized in the EgStore object, then those attributes - of the EgStore object will retain the values that they were - initialized with. - - If the pickled object has some attributes that were not - initialized in the EgStore object, then those attributes - will be ignored. - - IN SUMMARY: - - After the recover() operation, the EgStore object will have all, - and only, the attributes that it had when it was initialized. - - Where possible, those attributes will have values recovered - from the pickled object. - """ - if not os.path.exists(self.filename): return self - if not os.path.isfile(self.filename): return self - - try: - f = open(self.filename,"rb") - unpickledObject = pickle.load(f) - f.close() - - for key in list(self.__dict__.keys()): - default = self.__dict__[key] - self.__dict__[key] = unpickledObject.__dict__.get(key,default) - except: - pass - - return self - - def store(self): - """ - Save the attributes of the EgStore object to a pickle file. - Note that if the directory for the pickle file does not already exist, - the store operation will fail. - """ - f = open(self.filename, "wb") - pickle.dump(self, f) - f.close() - - - def kill(self): - """ - Delete my persistent file (i.e. pickle file), if it exists. - """ - if os.path.isfile(self.filename): - os.remove(self.filename) - return - - def __str__(self): - """ - return my contents as a string in an easy-to-read format. - """ - # find the length of the longest attribute name - longest_key_length = 0 - keys = [] - for key in self.__dict__.keys(): - keys.append(key) - longest_key_length = max(longest_key_length, len(key)) - - keys.sort() # sort the attribute names - lines = [] - for key in keys: - value = self.__dict__[key] - key = key.ljust(longest_key_length) - lines.append("%s : %s\n" % (key,repr(value)) ) - return "".join(lines) # return a string showing the attributes - - - - -#----------------------------------------------------------------------- -# -# test/demo easygui -# -#----------------------------------------------------------------------- -def egdemo(): - """ - Run the EasyGui demo. - """ - # clear the console - writeln("\n" * 100) - - intro_message = ("Pick the kind of box that you wish to demo.\n" - + "\n * Python version " + sys.version - + "\n * EasyGui version " + egversion - + "\n * Tk version " + str(TkVersion) - ) - - #========================================== END DEMONSTRATION DATA - - - while 1: # do forever - choices = [ - "msgbox", - "buttonbox", - "buttonbox(image) -- a buttonbox that displays an image", - "choicebox", - "multchoicebox", - "textbox", - "ynbox", - "ccbox", - "enterbox", - "enterbox(image) -- an enterbox that displays an image", - "exceptionbox", - "codebox", - "integerbox", - "boolbox", - "indexbox", - "filesavebox", - "fileopenbox", - "passwordbox", - "multenterbox", - "multpasswordbox", - "diropenbox", - "About EasyGui", - " Help" - ] - choice = choicebox(msg=intro_message - , title="EasyGui " + egversion - , choices=choices) - - if not choice: return - - reply = choice.split() - - if reply[0] == "msgbox": - reply = msgbox("short msg", "This is a long title") - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "About": - reply = abouteasygui() - - elif reply[0] == "Help": - _demo_help() - - elif reply[0] == "buttonbox": - reply = buttonbox() - writeln("Reply was: %s" % repr(reply)) - - title = "Demo of Buttonbox with many, many buttons!" - msg = "This buttonbox shows what happens when you specify too many buttons." - reply = buttonbox(msg=msg, title=title, choices=choices) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "buttonbox(image)": - _demo_buttonbox_with_image() - - elif reply[0] == "boolbox": - reply = boolbox() - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "enterbox": - image = "python_and_check_logo.gif" - message = "Enter the name of your best friend."\ - "\n(Result will be stripped.)" - reply = enterbox(message, "Love!", " Suzy Smith ") - writeln("Reply was: %s" % repr(reply)) - - message = "Enter the name of your best friend."\ - "\n(Result will NOT be stripped.)" - reply = enterbox(message, "Love!", " Suzy Smith ",strip=False) - writeln("Reply was: %s" % repr(reply)) - - reply = enterbox("Enter the name of your worst enemy:", "Hate!") - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "enterbox(image)": - image = "python_and_check_logo.gif" - message = "What kind of snake is this?" - reply = enterbox(message, "Quiz",image=image) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "exceptionbox": - try: - thisWillCauseADivideByZeroException = 1/0 - except: - exceptionbox() - - elif reply[0] == "integerbox": - reply = integerbox( - "Enter a number between 3 and 333", - "Demo: integerbox WITH a default value", - 222, 3, 333) - writeln("Reply was: %s" % repr(reply)) - - reply = integerbox( - "Enter a number between 0 and 99", - "Demo: integerbox WITHOUT a default value" - ) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "diropenbox" : _demo_diropenbox() - elif reply[0] == "fileopenbox": _demo_fileopenbox() - elif reply[0] == "filesavebox": _demo_filesavebox() - - elif reply[0] == "indexbox": - title = reply[0] - msg = "Demo of " + reply[0] - choices = ["Choice1", "Choice2", "Choice3", "Choice4"] - reply = indexbox(msg, title, choices) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "passwordbox": - reply = passwordbox("Demo of password box WITHOUT default" - + "\n\nEnter your secret password", "Member Logon") - writeln("Reply was: %s" % str(reply)) - - reply = passwordbox("Demo of password box WITH default" - + "\n\nEnter your secret password", "Member Logon", "alfie") - writeln("Reply was: %s" % str(reply)) - - elif reply[0] == "multenterbox": - msg = "Enter your personal information" - title = "Credit Card Application" - fieldNames = ["Name","Street Address","City","State","ZipCode"] - fieldValues = [] # we start with blanks for the values - fieldValues = multenterbox(msg,title, fieldNames) - - # make sure that none of the fields was left blank - while 1: - if fieldValues == None: break - errmsg = "" - for i in range(len(fieldNames)): - if fieldValues[i].strip() == "": - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) - if errmsg == "": break # no problems found - fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) - - writeln("Reply was: %s" % str(fieldValues)) - - elif reply[0] == "multpasswordbox": - msg = "Enter logon information" - title = "Demo of multpasswordbox" - fieldNames = ["Server ID", "User ID", "Password"] - fieldValues = [] # we start with blanks for the values - fieldValues = multpasswordbox(msg,title, fieldNames) - - # make sure that none of the fields was left blank - while 1: - if fieldValues == None: break - errmsg = "" - for i in range(len(fieldNames)): - if fieldValues[i].strip() == "": - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) - if errmsg == "": break # no problems found - fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) - - writeln("Reply was: %s" % str(fieldValues)) - - elif reply[0] == "ynbox": - title = "Demo of ynbox" - msg = "Were you expecting the Spanish Inquisition?" - reply = ynbox(msg, title) - writeln("Reply was: %s" % repr(reply)) - if reply: - msgbox("NOBODY expects the Spanish Inquisition!", "Wrong!") - - elif reply[0] == "ccbox": - title = "Demo of ccbox" - reply = ccbox(msg,title) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "choicebox": - title = "Demo of choicebox" - longchoice = "This is an example of a very long option which you may or may not wish to choose."*2 - listChoices = ["nnn", "ddd", "eee", "fff", "aaa", longchoice - , "aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk", "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq", "rrr", "sss", "ttt", "uuu", "vvv"] - - msg = "Pick something. " + ("A wrapable sentence of text ?! "*30) + "\nA separate line of text."*6 - reply = choicebox(msg=msg, choices=listChoices) - writeln("Reply was: %s" % repr(reply)) - - msg = "Pick something. " - reply = choicebox(msg=msg, title=title, choices=listChoices) - writeln("Reply was: %s" % repr(reply)) - - msg = "Pick something. " - reply = choicebox(msg="The list of choices is empty!", choices=[]) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "multchoicebox": - listChoices = ["aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk" - , "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq" - , "rrr", "sss", "ttt", "uuu", "vvv"] - - msg = "Pick as many choices as you wish." - reply = multchoicebox(msg,"Demo of multchoicebox", listChoices) - writeln("Reply was: %s" % repr(reply)) - - elif reply[0] == "textbox": _demo_textbox(reply[0]) - elif reply[0] == "codebox": _demo_codebox(reply[0]) - - else: - msgbox("Choice\n\n" + choice + "\n\nis not recognized", "Program Logic Error") - return - - -def _demo_textbox(reply): - text_snippet = ((\ -"""It was the best of times, and it was the worst of times. The rich ate cake, and the poor had cake recommended to them, but wished only for enough cash to buy bread. The time was ripe for revolution! """ \ -*5)+"\n\n")*10 - title = "Demo of textbox" - msg = "Here is some sample text. " * 16 - reply = textbox(msg, title, text_snippet) - writeln("Reply was: %s" % str(reply)) - -def _demo_codebox(reply): - code_snippet = ("dafsdfa dasflkj pp[oadsij asdfp;ij asdfpjkop asdfpok asdfpok asdfpok"*3) +"\n"+\ -"""# here is some dummy Python code -for someItem in myListOfStuff: - do something(someItem) - do something() - do something() - if somethingElse(someItem): - doSomethingEvenMoreInteresting() - -"""*16 - msg = "Here is some sample code. " * 16 - reply = codebox(msg, "Code Sample", code_snippet) - writeln("Reply was: %s" % repr(reply)) - - -def _demo_buttonbox_with_image(): - - msg = "Do you like this picture?\nIt is " - choices = ["Yes","No","No opinion"] - - for image in [ - "python_and_check_logo.gif" - ,"python_and_check_logo.jpg" - ,"python_and_check_logo.png" - ,"zzzzz.gif"]: - - reply=buttonbox(msg + image,image=image,choices=choices) - writeln("Reply was: %s" % repr(reply)) - - -def _demo_help(): - savedStdout = sys.stdout # save the sys.stdout file object - sys.stdout = capturedOutput = StringIO() - help("easygui") - sys.stdout = savedStdout # restore the sys.stdout file object - codebox("EasyGui Help",text=capturedOutput.getvalue()) - -def _demo_filesavebox(): - filename = "myNewFile.txt" - title = "File SaveAs" - msg ="Save file as:" - - f = filesavebox(msg,title,default=filename) - writeln("You chose to save file: %s" % f) - -def _demo_diropenbox(): - title = "Demo of diropenbox" - msg = "Pick the directory that you wish to open." - d = diropenbox(msg, title) - writeln("You chose directory...: %s" % d) - - d = diropenbox(msg, title,default="./") - writeln("You chose directory...: %s" % d) - - d = diropenbox(msg, title,default="c:/") - writeln("You chose directory...: %s" % d) - - -def _demo_fileopenbox(): - msg = "Python files" - title = "Open files" - default="*.py" - f = fileopenbox(msg,title,default=default) - writeln("You chose to open file: %s" % f) - - default="./*.gif" - filetypes = ["*.jpg",["*.zip","*.tgs","*.gz", "Archive files"],["*.htm", "*.html","HTML files"]] - f = fileopenbox(msg,title,default=default,filetypes=filetypes) - writeln("You chose to open file: %s" % f) - - """#deadcode -- testing ---------------------------------------- - f = fileopenbox(None,None,default=default) - writeln("You chose to open file: %s" % f) - - f = fileopenbox(None,title,default=default) - writeln("You chose to open file: %s" % f) - - f = fileopenbox(msg,None,default=default) - writeln("You chose to open file: %s" % f) - - f = fileopenbox(default=default) - writeln("You chose to open file: %s" % f) - - f = fileopenbox(default=None) - writeln("You chose to open file: %s" % f) - #----------------------------------------------------deadcode """ - - -def _dummy(): - pass - -EASYGUI_ABOUT_INFORMATION = ''' -======================================================================== -0.96(2010-08-29) -======================================================================== -This version fixes some problems with version independence. - -BUG FIXES ------------------------------------------------------- - * A statement with Python 2.x-style exception-handling syntax raised - a syntax error when running under Python 3.x. - Thanks to David Williams for reporting this problem. - - * Under some circumstances, PIL was unable to display non-gif images - that it should have been able to display. - The cause appears to be non-version-independent import syntax. - PIL modules are now imported with a version-independent syntax. - Thanks to Horst Jens for reporting this problem. - -LICENSE CHANGE ------------------------------------------------------- -Starting with this version, EasyGui is licensed under what is generally known as -the "modified BSD license" (aka "revised BSD", "new BSD", "3-clause BSD"). -This license is GPL-compatible but less restrictive than GPL. -Earlier versions were licensed under the Creative Commons Attribution License 2.0. - - -======================================================================== -0.95(2010-06-12) -======================================================================== - -ENHANCEMENTS ------------------------------------------------------- - * Previous versions of EasyGui could display only .gif image files using the - msgbox "image" argument. This version can now display all image-file formats - supported by PIL the Python Imaging Library) if PIL is installed. - If msgbox is asked to open a non-gif image file, it attempts to import - PIL and to use PIL to convert the image file to a displayable format. - If PIL cannot be imported (probably because PIL is not installed) - EasyGui displays an error message saying that PIL must be installed in order - to display the image file. - - Note that - http://www.pythonware.com/products/pil/ - says that PIL doesn't yet support Python 3.x. - - -======================================================================== -0.94(2010-06-06) -======================================================================== - -ENHANCEMENTS ------------------------------------------------------- - * The codebox and textbox functions now return the contents of the box, rather - than simply the name of the button ("Yes"). This makes it possible to use - codebox and textbox as data-entry widgets. A big "thank you!" to Dominic - Comtois for requesting this feature, patiently explaining his requirement, - and helping to discover the tkinter techniques to implement it. - - NOTE THAT in theory this change breaks backward compatibility. But because - (in previous versions of EasyGui) the value returned by codebox and textbox - was meaningless, no application should have been checking it. So in actual - practice, this change should not break backward compatibility. - - * Added support for SPACEBAR to command buttons. Now, when keyboard - focus is on a command button, a press of the SPACEBAR will act like - a press of the ENTER key; it will activate the command button. - - * Added support for keyboard navigation with the arrow keys (up,down,left,right) - to the fields and buttons in enterbox, multenterbox and multpasswordbox, - and to the buttons in choicebox and all buttonboxes. - - * added highlightthickness=2 to entry fields in multenterbox and - multpasswordbox. Now it is easier to tell which entry field has - keyboard focus. - - -BUG FIXES ------------------------------------------------------- - * In EgStore, the pickle file is now opened with "rb" and "wb" rather than - with "r" and "w". This change is necessary for compatibility with Python 3+. - Thanks to Marshall Mattingly for reporting this problem and providing the fix. - - * In integerbox, the actual argument names did not match the names described - in the docstring. Thanks to Daniel Zingaro of at University of Toronto for - reporting this problem. - - * In integerbox, the "argLowerBound" and "argUpperBound" arguments have been - renamed to "lowerbound" and "upperbound" and the docstring has been corrected. - - NOTE THAT THIS CHANGE TO THE ARGUMENT-NAMES BREAKS BACKWARD COMPATIBILITY. - If argLowerBound or argUpperBound are used, an AssertionError with an - explanatory error message is raised. - - * In choicebox, the signature to choicebox incorrectly showed choicebox as - accepting a "buttons" argument. The signature has been fixed. - - -======================================================================== -0.93(2009-07-07) -======================================================================== - -ENHANCEMENTS ------------------------------------------------------- - - * Added exceptionbox to display stack trace of exceptions - - * modified names of some font-related constants to make it - easier to customize them - - -======================================================================== -0.92(2009-06-22) -======================================================================== - -ENHANCEMENTS ------------------------------------------------------- - - * Added EgStore class to to provide basic easy-to-use persistence. - -BUG FIXES ------------------------------------------------------- - - * Fixed a bug that was preventing Linux users from copying text out of - a textbox and a codebox. This was not a problem for Windows users. - -''' - -def abouteasygui(): - """ - shows the easygui revision history - """ - codebox("About EasyGui\n"+egversion,"EasyGui",EASYGUI_ABOUT_INFORMATION) - return None - - - -if __name__ == '__main__': - if True: - egdemo() - else: - # test the new root feature - root = Tk() - msg = """This is a test of a main Tk() window in which we will place an easygui msgbox. - It will be an interesting experiment.\n\n""" - messageWidget = Message(root, text=msg, width=1000) - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') - messageWidget = Message(root, text=msg, width=1000) - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') - - - msgbox("this is a test of passing in boxRoot", root=root) - msgbox("this is a second test of passing in boxRoot", root=root) - - reply = enterbox("Enter something", root=root) - writeln("You wrote:", reply) - - reply = enterbox("Enter something else", root=root) - writeln("You wrote:", reply) - root.destroy() diff --git a/oletools/thirdparty/olefile/CONTRIBUTORS.txt b/oletools/thirdparty/olefile/CONTRIBUTORS.txt deleted file mode 100644 index 32db267..0000000 --- a/oletools/thirdparty/olefile/CONTRIBUTORS.txt +++ /dev/null @@ -1,17 +0,0 @@ -CONTRIBUTORS for the olefile project -==================================== - -This is a non-exhaustive list of all the people who helped me improve the -olefile project (formerly OleFileIO_PL), in approximative chronological order. -Please contact me if I forgot to mention your name. - -A big thank you to all of them: - -- Niko Ehrenfeuchter: added support for Jython -- Niko Ehrenfeuchter, Martijn Berger and Dave Jones: helped fix 4K sector support -- Martin Panter: conversion to Python 3.x/2.6+ -- mete0r_kr: added support for file-like objects -- chuckleberryfinn: fixed bug in getproperties -- Martijn, Ben G.: bug report for 64 bits platforms -- Philippe Lagadec: main author and maintainer since 2005 -- and of course Fredrik Lundh: original author of OleFileIO from 1995 to 2005 diff --git a/oletools/thirdparty/olefile/LICENSE.txt b/oletools/thirdparty/olefile/LICENSE.txt deleted file mode 100644 index 506a3d7..0000000 --- a/oletools/thirdparty/olefile/LICENSE.txt +++ /dev/null @@ -1,56 +0,0 @@ -LICENSE for the olefile package: - -olefile (formerly OleFileIO_PL) is copyright (c) 2005-2016 Philippe Lagadec -(http://www.decalage.info) - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------- - -olefile is based on source code from the OleFileIO module of the Python -Imaging Library (PIL) published by Fredrik Lundh under the following license: - -The Python Imaging Library (PIL) is -- Copyright (c) 1997-2005 by Secret Labs AB -- Copyright (c) 1995-2005 by Fredrik Lundh - -By obtaining, using, and/or copying this software and/or its associated -documentation, you agree that you have read, understood, and will comply with -the following terms and conditions: - -Permission to use, copy, modify, and distribute this software and its -associated documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appears in all copies, and that both -that copyright notice and this permission notice appear in supporting -documentation, and that the name of Secret Labs AB or the author not be used -in advertising or publicity pertaining to distribution of the software without -specific, written prior permission. - -SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN -NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, -INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. diff --git a/oletools/thirdparty/olefile/README.html b/oletools/thirdparty/olefile/README.html deleted file mode 100644 index 74d95ac..0000000 --- a/oletools/thirdparty/olefile/README.html +++ /dev/null @@ -1,81 +0,0 @@ -

olefile (formerly OleFileIO_PL)

-

olefile is a Python package to parse, read and write Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft Office 97-2003 documents, vbaProject.bin in MS Office 2007+ files, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file formats, McAfee antivirus quarantine files, etc.

-

Quick links: Home page - Download/Install - Documentation - Report Issues/Suggestions/Questions - Contact the author - Repository - Updates on Twitter

-

News

-

Follow all updates and news on Twitter: https://twitter.com/decalage2

-
    -
  • 2016-02-02 v0.43: fixed issues #26 and #27, better handling of malformed files, use python logging.
  • -
  • 2015-01-25 v0.42: improved handling of special characters in stream/storage names on Python 2.x (using UTF-8 instead of Latin-1), fixed bug in listdir with empty storages.
  • -
  • 2014-11-25 v0.41: OleFileIO.open and isOleFile now support OLE files stored in byte strings, fixed installer for python 3, added support for Jython (Niko Ehrenfeuchter)
  • -
  • 2014-10-01 v0.40: renamed OleFileIO_PL to olefile, added initial write support for streams >4K, updated doc and license, improved the setup script.
  • -
  • 2014-07-27 v0.31: fixed support for large files with 4K sectors, thanks to Niko Ehrenfeuchter, Martijn Berger and Dave Jones. Added test scripts from Pillow (by hugovk). Fixed setup for Python 3 (Martin Panter)
  • -
  • 2014-02-04 v0.30: now compatible with Python 3.x, thanks to Martin Panter who did most of the hard work.
  • -
  • 2013-07-24 v0.26: added methods to parse stream/storage timestamps, improved listdir to include storages, fixed parsing of direntry timestamps
  • -
  • 2013-05-27 v0.25: improved metadata extraction, properties parsing and exception handling, fixed issue #12
  • -
  • 2013-05-07 v0.24: new features to extract metadata (get_metadata method and OleMetadata class), improved getproperties to convert timestamps to Python datetime
  • -
  • 2012-10-09: published python-oletools, a package of analysis tools based on OleFileIO_PL
  • -
  • 2012-09-11 v0.23: added support for file-like objects, fixed issue #8
  • -
  • 2012-02-17 v0.22: fixed issues #7 (bug in getproperties) and #2 (added close method)
  • -
  • 2011-10-20: code hosted on bitbucket to ease contributions and bug tracking
  • -
  • 2010-01-24 v0.21: fixed support for big-endian CPUs, such as PowerPC Macs.
  • -
  • 2009-12-11 v0.20: small bugfix in OleFileIO.open when filename is not plain str.
  • -
  • 2009-12-10 v0.19: fixed support for 64 bits platforms (thanks to Ben G. and Martijn for reporting the bug)
  • -
  • see changelog in source code for more info.
  • -
-

Download/Install

-

If you have pip or setuptools installed (pip is included in Python 2.7.9+), you may simply run pip install olefile or easy_install olefile for the first installation.

-

To update olefile, run pip install -U olefile.

-

Otherwise, see https://bitbucket.org/decalage/olefileio_pl/wiki/Install

-

Features

-
    -
  • Parse, read and write any OLE file such as Microsoft Office 97-2003 legacy document formats (Word .doc, Excel .xls, PowerPoint .ppt, Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook messages, StickyNotes, Zeiss AxioVision ZVI files, Olympus FluoView OIB files, etc
  • -
  • List all the streams and storages contained in an OLE file
  • -
  • Open streams as files
  • -
  • Parse and read property streams, containing metadata of the file
  • -
  • Portable, pure Python module, no dependency
  • -
-

olefile can be used as an independent package or with PIL/Pillow.

-

olefile is mostly meant for developers. If you are looking for tools to analyze OLE files or to extract data (especially for security purposes such as malware analysis and forensics), then please also check my python-oletools, which are built upon olefile and provide a higher-level interface.

-

History

-

olefile is based on the OleFileIO module from PIL, the excellent Python Imaging Library, created and maintained by Fredrik Lundh. The olefile API is still compatible with PIL, but since 2005 I have improved the internal implementation significantly, with new features, bugfixes and a more robust design. From 2005 to 2014 the project was called OleFileIO_PL, and in 2014 I changed its name to olefile to celebrate its 9 years and its new write features.

-

As far as I know, olefile is the most complete and robust Python implementation to read MS OLE2 files, portable on several operating systems. (please tell me if you know other similar Python modules)

-

Since 2014 olefile/OleFileIO_PL has been integrated into Pillow, the friendly fork of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly.

-

Main improvements over the original version of OleFileIO in PIL:

-
    -
  • Compatible with Python 3.x and 2.6+
  • -
  • Many bug fixes
  • -
  • Support for files larger than 6.8MB
  • -
  • Support for 64 bits platforms and big-endian CPUs
  • -
  • Robust: many checks to detect malformed files
  • -
  • Runtime option to choose if malformed files should be parsed or raise exceptions
  • -
  • Improved API
  • -
  • Metadata extraction, stream/storage timestamps (e.g. for document forensics)
  • -
  • Can open file-like objects
  • -
  • Added setup.py and install.bat to ease installation
  • -
  • More convenient slash-based syntax for stream paths
  • -
  • Write features
  • -
-

Documentation

-

Please see the online documentation for more information, especially the OLE overview and the API page which describe how to use olefile in Python applications. A copy of the same documentation is also provided in the doc subfolder of the olefile package.

-

Real-life examples

-

A real-life example: using OleFileIO_PL for malware analysis and forensics.

-

See also this paper about python tools for forensics, which features olefile.

-

License

-

olefile (formerly OleFileIO_PL) is copyright (c) 2005-2016 Philippe Lagadec (http://www.decalage.info)

-

All rights reserved.

-

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

-
    -
  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • -
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • -
-

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-
-

olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license:

-

The Python Imaging Library (PIL) is

-
    -
  • Copyright (c) 1997-2005 by Secret Labs AB
  • -
  • Copyright (c) 1995-2005 by Fredrik Lundh
  • -
-

By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions:

-

Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

-

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

diff --git a/oletools/thirdparty/olefile/README.rst b/oletools/thirdparty/olefile/README.rst deleted file mode 100644 index 04d7775..0000000 --- a/oletools/thirdparty/olefile/README.rst +++ /dev/null @@ -1,226 +0,0 @@ -olefile (formerly OleFileIO\_PL) -================================ - -`olefile `__ is a Python package to -parse, read and write `Microsoft OLE2 -files `__ -(also called Structured Storage, Compound File Binary Format or Compound -Document File Format), such as Microsoft Office 97-2003 documents, -vbaProject.bin in MS Office 2007+ files, Image Composer and FlashPix -files, Outlook messages, StickyNotes, several Microscopy file formats, -McAfee antivirus quarantine files, etc. - -**Quick links:** `Home page `__ - -`Download/Install `__ -- `Documentation `__ - -`Report -Issues/Suggestions/Questions `__ -- `Contact the author `__ - -`Repository `__ - `Updates -on Twitter `__ - -News ----- - -Follow all updates and news on Twitter: https://twitter.com/decalage2 - -- **2016-02-02 v0.43**: fixed issues - `#26 `__ - and - `#27 `__, - better handling of malformed files, use python logging. -- 2015-01-25 v0.42: improved handling of special characters in - stream/storage names on Python 2.x (using UTF-8 instead of Latin-1), - fixed bug in listdir with empty storages. -- 2014-11-25 v0.41: OleFileIO.open and isOleFile now support OLE files - stored in byte strings, fixed installer for python 3, added support - for Jython (Niko Ehrenfeuchter) -- 2014-10-01 v0.40: renamed OleFileIO\_PL to olefile, added initial - write support for streams >4K, updated doc and license, improved the - setup script. -- 2014-07-27 v0.31: fixed support for large files with 4K sectors, - thanks to Niko Ehrenfeuchter, Martijn Berger and Dave Jones. Added - test scripts from Pillow (by hugovk). Fixed setup for Python 3 - (Martin Panter) -- 2014-02-04 v0.30: now compatible with Python 3.x, thanks to Martin - Panter who did most of the hard work. -- 2013-07-24 v0.26: added methods to parse stream/storage timestamps, - improved listdir to include storages, fixed parsing of direntry - timestamps -- 2013-05-27 v0.25: improved metadata extraction, properties parsing - and exception handling, fixed `issue - #12 `__ -- 2013-05-07 v0.24: new features to extract metadata (get\_metadata - method and OleMetadata class), improved getproperties to convert - timestamps to Python datetime -- 2012-10-09: published - `python-oletools `__, a - package of analysis tools based on OleFileIO\_PL -- 2012-09-11 v0.23: added support for file-like objects, fixed `issue - #8 `__ -- 2012-02-17 v0.22: fixed issues #7 (bug in getproperties) and #2 - (added close method) -- 2011-10-20: code hosted on bitbucket to ease contributions and bug - tracking -- 2010-01-24 v0.21: fixed support for big-endian CPUs, such as PowerPC - Macs. -- 2009-12-11 v0.20: small bugfix in OleFileIO.open when filename is not - plain str. -- 2009-12-10 v0.19: fixed support for 64 bits platforms (thanks to Ben - G. and Martijn for reporting the bug) -- see changelog in source code for more info. - -Download/Install ----------------- - -If you have pip or setuptools installed (pip is included in Python -2.7.9+), you may simply run **pip install olefile** or **easy\_install -olefile** for the first installation. - -To update olefile, run **pip install -U olefile**. - -Otherwise, see https://bitbucket.org/decalage/olefileio\_pl/wiki/Install - -Features --------- - -- Parse, read and write any OLE file such as Microsoft Office 97-2003 - legacy document formats (Word .doc, Excel .xls, PowerPoint .ppt, - Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook - messages, StickyNotes, Zeiss AxioVision ZVI files, Olympus FluoView - OIB files, etc -- List all the streams and storages contained in an OLE file -- Open streams as files -- Parse and read property streams, containing metadata of the file -- Portable, pure Python module, no dependency - -olefile can be used as an independent package or with PIL/Pillow. - -olefile is mostly meant for developers. If you are looking for tools to -analyze OLE files or to extract data (especially for security purposes -such as malware analysis and forensics), then please also check my -`python-oletools `__, which -are built upon olefile and provide a higher-level interface. - -History -------- - -olefile is based on the OleFileIO module from -`PIL `__, the -excellent Python Imaging Library, created and maintained by Fredrik -Lundh. The olefile API is still compatible with PIL, but since 2005 I -have improved the internal implementation significantly, with new -features, bugfixes and a more robust design. From 2005 to 2014 the -project was called OleFileIO\_PL, and in 2014 I changed its name to -olefile to celebrate its 9 years and its new write features. - -As far as I know, olefile is the most complete and robust Python -implementation to read MS OLE2 files, portable on several operating -systems. (please tell me if you know other similar Python modules) - -Since 2014 olefile/OleFileIO\_PL has been integrated into -`Pillow `__, the friendly fork of PIL. -olefile will continue to be improved as a separate project, and new -versions will be merged into Pillow regularly. - -Main improvements over the original version of OleFileIO in PIL: ----------------------------------------------------------------- - -- Compatible with Python 3.x and 2.6+ -- Many bug fixes -- Support for files larger than 6.8MB -- Support for 64 bits platforms and big-endian CPUs -- Robust: many checks to detect malformed files -- Runtime option to choose if malformed files should be parsed or raise - exceptions -- Improved API -- Metadata extraction, stream/storage timestamps (e.g. for document - forensics) -- Can open file-like objects -- Added setup.py and install.bat to ease installation -- More convenient slash-based syntax for stream paths -- Write features - -Documentation -------------- - -Please see the `online -documentation `__ for -more information, especially the `OLE -overview `__ -and the `API -page `__ which -describe how to use olefile in Python applications. A copy of the same -documentation is also provided in the doc subfolder of the olefile -package. - -Real-life examples ------------------- - -A real-life example: `using OleFileIO\_PL for malware analysis and -forensics `__. - -See also `this -paper `__ -about python tools for forensics, which features olefile. - -License -------- - -olefile (formerly OleFileIO\_PL) is copyright (c) 2005-2016 Philippe -Lagadec (http://www.decalage.info) - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - --------------- - -olefile is based on source code from the OleFileIO module of the Python -Imaging Library (PIL) published by Fredrik Lundh under the following -license: - -The Python Imaging Library (PIL) is - -- Copyright (c) 1997-2005 by Secret Labs AB -- Copyright (c) 1995-2005 by Fredrik Lundh - -By obtaining, using, and/or copying this software and/or its associated -documentation, you agree that you have read, understood, and will comply -with the following terms and conditions: - -Permission to use, copy, modify, and distribute this software and its -associated documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appears in all copies, -and that both that copyright notice and this permission notice appear in -supporting documentation, and that the name of Secret Labs AB or the -author not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR -ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER -RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/oletools/thirdparty/olefile/__init__.py b/oletools/thirdparty/olefile/__init__.py deleted file mode 100644 index 59b442d..0000000 --- a/oletools/thirdparty/olefile/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/local/bin/python -# -*- coding: latin-1 -*- -""" -olefile (formerly OleFileIO_PL) - -Module to read/write Microsoft OLE2 files (also called Structured Storage or -Microsoft Compound Document File Format), such as Microsoft Office 97-2003 -documents, Image Composer and FlashPix files, Outlook messages, ... -This version is compatible with Python 2.6+ and 3.x - -Project website: http://www.decalage.info/olefile - -olefile is copyright (c) 2005-2015 Philippe Lagadec (http://www.decalage.info) - -olefile is based on the OleFileIO module from the PIL library v1.1.6 -See: http://www.pythonware.com/products/pil/index.htm - -The Python Imaging Library (PIL) is - Copyright (c) 1997-2005 by Secret Labs AB - Copyright (c) 1995-2005 by Fredrik Lundh - -See source code and LICENSE.txt for information on usage and redistribution. -""" - -# first try to import olefile for Python 2.6+/3.x -from .olefile import * -# import metadata not covered by *: -from .olefile import __version__, __author__, __date__ diff --git a/oletools/thirdparty/olefile/doc/API.html b/oletools/thirdparty/olefile/doc/API.html deleted file mode 100644 index 633755e..0000000 --- a/oletools/thirdparty/olefile/doc/API.html +++ /dev/null @@ -1,164 +0,0 @@ - - - - - - - - - -

How to use olefile - API

-

This page is part of the documentation for olefile. It explains how to use all its features to parse and write OLE files. For more information about OLE files, see OLE_Overview.

-

olefile can be used as an independent module or with PIL/Pillow. The main functions and methods are explained below.

-

For more information, see also the file olefile.html, sample code at the end of the module itself, and docstrings within the code.

-

Import olefile

-

When the olefile package has been installed, it can be imported in Python applications with this statement:

-
import olefile
-

Before v0.40, olefile was named OleFileIO_PL. To maintain backward compatibility with older applications and samples, a simple script is also installed so that the following statement imports olefile as OleFileIO_PL:

-
import OleFileIO_PL
-

As of version 0.30, the code has been changed to be compatible with Python 3.x. As a consequence, compatibility with Python 2.5 or older is not provided anymore. However, a copy of OleFileIO_PL v0.26 (with some backported enhancements) is available as olefile2.py. When importing the olefile package, it falls back automatically to olefile2 if running on Python 2.5 or older. This is implemented in olefile/init.py. (new in v0.40)

-

If you think olefile should stay compatible with Python 2.5 or older, please contact me.

-

Test if a file is an OLE container

-

Use isOleFile to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile returns True if it is an OLE file, False otherwise (new in v0.16).

-
assert olefile.isOleFile('myfile.doc')
-

The argument of isOleFile can be (new in v0.41):

-
    -
  • the path of the file to open on disk (bytes or unicode string smaller than 1536 bytes),
  • -
  • or a bytes string containing the file in memory. (bytes string longer than 1535 bytes),
  • -
  • or a file-like object (with read and seek methods).
  • -
-

Open an OLE file from disk

-

Create an OleFileIO object with the file path as parameter:

-
ole = olefile.OleFileIO('myfile.doc')
-

Open an OLE file from a bytes string

-

This is useful if the file is already stored in memory as a bytes string.

-
ole = olefile.OleFileIO(s)
-

Note: olefile checks the size of the string provided as argument to determine if it is a file path or the content of an OLE file. An OLE file cannot be smaller than 1536 bytes. If the string is larger than 1535 bytes, then it is expected to contain an OLE file, otherwise it is expected to be a file path.

-

(new in v0.41)

-

Open an OLE file from a file-like object

-

This is useful if the file is not on disk but only available as a file-like object (with read, seek and tell methods).

-
ole = olefile.OleFileIO(f)
-

If the file-like object does not have seek or tell methods, the easiest solution is to read the file entirely in a bytes string before parsing:

-
data = f.read()
-ole = olefile.OleFileIO(data)
-

How to handle malformed OLE files

-

By default, the parser is configured to be as robust and permissive as possible, allowing to parse most malformed OLE files. Only fatal errors will raise an exception. It is possible to tell the parser to be more strict in order to raise exceptions for files that do not fully conform to the OLE specifications, using the raise_defect option (new in v0.14):

-
ole = olefile.OleFileIO('myfile.doc', raise_defects=olefile.DEFECT_INCORRECT)
-

When the parsing is done, the list of non-fatal issues detected is available as a list in the parsing_issues attribute of the OleFileIO object (new in 0.25):

-
print('Non-fatal issues raised during parsing:')
-if ole.parsing_issues:
-    for exctype, msg in ole.parsing_issues:
-        print('- %s: %s' % (exctype.__name__, msg))
-else:
-    print('None')
-

Open an OLE file in write mode

-

Before using the write features, the OLE file must be opened in read/write mode:

-
ole = olefile.OleFileIO('test.doc', write_mode=True)
-

(new in v0.40)

-

The code for write features is new and it has not been thoroughly tested yet. See issue #6 for the roadmap and the implementation status. If you encounter any issue, please send me your feedback or report issues.

-

Syntax for stream and storage paths

-

Two different syntaxes are allowed for methods that need or return the path of streams and storages:

-
    -
  1. Either a list of strings including all the storages from the root up to the stream/storage name. For example a stream called "WordDocument" at the root will have ['WordDocument'] as full path. A stream called "ThisDocument" located in the storage "Macros/VBA" will be ['Macros', 'VBA', 'ThisDocument']. This is the original syntax from PIL. While hard to read and not very convenient, this syntax works in all cases.

  2. -
  3. Or a single string with slashes to separate storage and stream names (similar to the Unix path syntax). The previous examples would be 'WordDocument' and 'Macros/VBA/ThisDocument'. This syntax is easier, but may fail if a stream or storage name contains a slash (which is normally not allowed, according to the Microsoft specifications [MS-CFB]). (new in v0.15)

  4. -
-

Both are case-insensitive.

-

Switching between the two is easy:

-
slash_path = '/'.join(list_path)
-list_path  = slash_path.split('/')
-

Encoding:

-
    -
  • Stream and Storage names are stored in Unicode format in OLE files, which means they may contain special characters (e.g. Greek, Cyrillic, Japanese, etc) that applications must support to avoid exceptions.
  • -
  • On Python 2.x, all stream and storage paths are handled by olefile in bytes strings, using the UTF-8 encoding by default. If you need to use Unicode instead, add the option path_encoding=None when creating the OleFileIO object. This is new in v0.42. Olefile was using the Latin-1 encoding until v0.41, therefore special characters were not supported.
  • -
  • On Python 3.x, all stream and storage paths are handled by olefile in unicode strings, without encoding.
  • -
-

Get the list of streams

-

listdir() returns a list of all the streams contained in the OLE file, including those stored in storages. Each stream is listed itself as a list, as described above.

-
print(ole.listdir())
-

Sample result:

-
[['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation']
-, ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA',
-'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT']
-, ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']]
-

As an option it is possible to choose if storages should also be listed, with or without streams (new in v0.26):

-
ole.listdir (streams=False, storages=True)
-

Test if known streams/storages exist:

-

exists(path) checks if a given stream or storage exists in the OLE file (new in v0.16). The provided path is case-insensitive.

-
if ole.exists('worddocument'):
-    print("This is a Word document.")
-    if ole.exists('macros/vba'):
-         print("This document seems to contain VBA macros.")
-

Read data from a stream

-

openstream(path) opens a stream as a file-like object. The provided path is case-insensitive.

-

The following example extracts the "Pictures" stream from a PPT file:

-
pics = ole.openstream('Pictures')
-data = pics.read()
-

Get information about a stream/storage

-

Several methods can provide the size, type and timestamps of a given stream/storage:

-

get_size(path) returns the size of a stream in bytes (new in v0.16):

-
s = ole.get_size('WordDocument')
-

get_type(path) returns the type of a stream/storage, as one of the following constants: STGTY_STREAM for a stream, STGTY_STORAGE for a storage, STGTY_ROOT for the root entry, and False for a non existing path (new in v0.15).

-
t = ole.get_type('WordDocument')
-

get_ctime(path) and get_mtime(path) return the creation and modification timestamps of a stream/storage, as a Python datetime object with UTC timezone. Please note that these timestamps are only present if the application that created the OLE file explicitly stored them, which is rarely the case. When not present, these methods return None (new in v0.26).

-
c = ole.get_ctime('WordDocument')
-m = ole.get_mtime('WordDocument')
-

The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute (new in v0.26):

-
c = ole.root.getctime()
-m = ole.root.getmtime()
-

Note: all these methods are case-insensitive.

-

Overwriting a sector

-

The write_sect method can overwrite any sector of the file. If the provided data is smaller than the sector size (normally 512 bytes, sometimes 4KB), data is padded with null characters. (new in v0.40)

-

Here is an example:

-
ole.write_sect(0x17, b'TEST')
-

Note: following the MS-CFB specifications, sector 0 is actually the second sector of the file. You may use -1 as index to write the first sector.

-

Overwriting a stream

-

The write_stream method can overwrite an existing stream in the file. The new stream data must be the exact same size as the existing one. For now, write_stream can only write streams of 4KB or larger (stored in the main FAT).

-

For example, you may change text in a MS Word document:

-
ole = olefile.OleFileIO('test.doc', write_mode=True)
-data = ole.openstream('WordDocument').read()
-data = data.replace(b'foo', b'bar')
-ole.write_stream('WordDocument', data)
-ole.close()
-

(new in v0.40)

-

Extract metadata

-

get_metadata() will check if standard property streams exist, parse all the properties they contain, and return an OleMetadata object with the found properties as attributes (new in v0.24).

-
meta = ole.get_metadata()
-print('Author:', meta.author)
-print('Title:', meta.title)
-print('Creation date:', meta.create_time)
-# print all metadata:
-meta.dump()
-

Available attributes include:

-
codepage, title, subject, author, keywords, comments, template,
-last_saved_by, revision_number, total_edit_time, last_printed, create_time,
-last_saved_time, num_pages, num_words, num_chars, thumbnail,
-creating_application, security, codepage_doc, category, presentation_target,
-bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
-scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
-chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
-version, dig_sig, content_type, content_status, language, doc_version
-

See the source code of the OleMetadata class for more information.

-

Parse a property stream

-

get_properties(path) can be used to parse any property stream that is not handled by get_metadata. It returns a dictionary indexed by integers. Each integer is the index of the property, pointing to its value. For example in the standard property stream '05SummaryInformation', the document title is property #2, and the subject is #3.

-
p = ole.getproperties('specialprops')
-

By default as in the original PIL version, timestamp properties are converted into a number of seconds since Jan 1,1601. With the option convert_time, you can obtain more convenient Python datetime objects (UTC timezone). If some time properties should not be converted (such as total editing time in '05SummaryInformation'), the list of indexes can be passed as no_conversion (new in v0.25):

-
p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10])
-

Close the OLE file

-

Unless your application is a simple script that terminates after processing an OLE file, do not forget to close each OleFileIO object after parsing to close the file on disk. (new in v0.22)

-
ole.close()
-

Use olefile as a script for testing/debugging

-

olefile can also be used as a script from the command-line to display the structure of an OLE file and its metadata, for example:

-
olefile.py myfile.doc
-

You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information.

-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/API.md b/oletools/thirdparty/olefile/doc/API.md deleted file mode 100644 index e4a9667..0000000 --- a/oletools/thirdparty/olefile/doc/API.md +++ /dev/null @@ -1,313 +0,0 @@ -How to use olefile - API -======================== - -This page is part of the documentation for [olefile](https://bitbucket.org/decalage/olefileio_pl/wiki). It explains -how to use all its features to parse and write OLE files. For more information about OLE files, see [[OLE_Overview]]. - -olefile can be used as an independent module or with PIL/Pillow. The main functions and methods are explained below. - -For more information, see also the file **olefile.html**, sample code at the end of the module itself, and docstrings within the code. - - - -Import olefile --------------- - -When the olefile package has been installed, it can be imported in Python applications with this statement: - - :::python - import olefile - -Before v0.40, olefile was named OleFileIO_PL. To maintain backward compatibility with older applications and samples, a -simple script is also installed so that the following statement imports olefile as OleFileIO_PL: - - :::python - import OleFileIO_PL - -As of version 0.30, the code has been changed to be compatible with Python 3.x. As a consequence, compatibility with -Python 2.5 or older is not provided anymore. However, a copy of OleFileIO_PL v0.26 (with some backported enhancements) -is available as olefile2.py. When importing the olefile package, it falls back automatically to olefile2 if running on -Python 2.5 or older. This is implemented in olefile/__init__.py. (new in v0.40) - -If you think olefile should stay compatible with Python 2.5 or older, please [contact me](http://decalage.info/contact). - - -## Test if a file is an OLE container - -Use **isOleFile** to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile -returns True if it is an OLE file, False otherwise (new in v0.16). - - :::python - assert olefile.isOleFile('myfile.doc') - -The argument of isOleFile can be (new in v0.41): - -- the path of the file to open on disk (bytes or unicode string smaller than 1536 bytes), -- or a bytes string containing the file in memory. (bytes string longer than 1535 bytes), -- or a file-like object (with read and seek methods). - -## Open an OLE file from disk - -Create an **OleFileIO** object with the file path as parameter: - - :::python - ole = olefile.OleFileIO('myfile.doc') - -## Open an OLE file from a bytes string - -This is useful if the file is already stored in memory as a bytes string. - - :::python - ole = olefile.OleFileIO(s) - -Note: olefile checks the size of the string provided as argument to determine if it is a file path or the content of an -OLE file. An OLE file cannot be smaller than 1536 bytes. If the string is larger than 1535 bytes, then it is expected to -contain an OLE file, otherwise it is expected to be a file path. - -(new in v0.41) - - -## Open an OLE file from a file-like object - -This is useful if the file is not on disk but only available as a file-like object (with read, seek and tell methods). - - :::python - ole = olefile.OleFileIO(f) - -If the file-like object does not have seek or tell methods, the easiest solution is to read the file entirely in -a bytes string before parsing: - - :::python - data = f.read() - ole = olefile.OleFileIO(data) - - -## How to handle malformed OLE files - -By default, the parser is configured to be as robust and permissive as possible, allowing to parse most malformed OLE files. Only fatal errors will raise an exception. It is possible to tell the parser to be more strict in order to raise exceptions for files that do not fully conform to the OLE specifications, using the raise_defect option (new in v0.14): - - :::python - ole = olefile.OleFileIO('myfile.doc', raise_defects=olefile.DEFECT_INCORRECT) - -When the parsing is done, the list of non-fatal issues detected is available as a list in the parsing_issues attribute of the OleFileIO object (new in 0.25): - - :::python - print('Non-fatal issues raised during parsing:') - if ole.parsing_issues: - for exctype, msg in ole.parsing_issues: - print('- %s: %s' % (exctype.__name__, msg)) - else: - print('None') - - -## Open an OLE file in write mode - -Before using the write features, the OLE file must be opened in read/write mode: - - :::python - ole = olefile.OleFileIO('test.doc', write_mode=True) - -(new in v0.40) - -The code for write features is new and it has not been thoroughly tested yet. See [issue #6](https://bitbucket.org/decalage/olefileio_pl/issue/6/improve-olefileio_pl-to-write-ole-files) for the roadmap and the implementation status. If you encounter any issue, please send me your [feedback](http://www.decalage.info/en/contact) or [report issues](https://bitbucket.org/decalage/olefileio_pl/issues?status=new&status=open). - - -## Syntax for stream and storage paths - -Two different syntaxes are allowed for methods that need or return the path of streams and storages: - -1) Either a **list of strings** including all the storages from the root up to the stream/storage name. For example a -stream called "WordDocument" at the root will have ['WordDocument'] as full path. A stream called "ThisDocument" -located in the storage "Macros/VBA" will be ['Macros', 'VBA', 'ThisDocument']. This is the original syntax from PIL. -While hard to read and not very convenient, this syntax works in all cases. - -2) Or a **single string with slashes** to separate storage and stream names (similar to the Unix path syntax). -The previous examples would be 'WordDocument' and 'Macros/VBA/ThisDocument'. This syntax is easier, but may fail if a -stream or storage name contains a slash (which is normally not allowed, according to the Microsoft specifications [MS-CFB]). (new in v0.15) - -Both are case-insensitive. - -Switching between the two is easy: - - :::python - slash_path = '/'.join(list_path) - list_path = slash_path.split('/') - -**Encoding**: - -- Stream and Storage names are stored in Unicode format in OLE files, which means they may contain special characters - (e.g. Greek, Cyrillic, Japanese, etc) that applications must support to avoid exceptions. -- **On Python 2.x**, all stream and storage paths are handled by olefile in bytes strings, using the **UTF-8 encoding** - by default. If you need to use Unicode instead, add the option **path_encoding=None** when creating the OleFileIO - object. This is new in v0.42. Olefile was using the Latin-1 encoding until v0.41, therefore special characters were - not supported. -- **On Python 3.x**, all stream and storage paths are handled by olefile in unicode strings, without encoding. - -## Get the list of streams - -listdir() returns a list of all the streams contained in the OLE file, including those stored in storages. -Each stream is listed itself as a list, as described above. - - :::python - print(ole.listdir()) - -Sample result: - - :::python - [['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation'] - , ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA', - 'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT'] - , ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']] - -As an option it is possible to choose if storages should also be listed, with or without streams (new in v0.26): - - :::python - ole.listdir (streams=False, storages=True) - - -## Test if known streams/storages exist: - -exists(path) checks if a given stream or storage exists in the OLE file (new in v0.16). The provided path is case-insensitive. - - :::python - if ole.exists('worddocument'): - print("This is a Word document.") - if ole.exists('macros/vba'): - print("This document seems to contain VBA macros.") - - -## Read data from a stream - -openstream(path) opens a stream as a file-like object. The provided path is case-insensitive. - -The following example extracts the "Pictures" stream from a PPT file: - - :::python - pics = ole.openstream('Pictures') - data = pics.read() - - -## Get information about a stream/storage - -Several methods can provide the size, type and timestamps of a given stream/storage: - -get_size(path) returns the size of a stream in bytes (new in v0.16): - - :::python - s = ole.get_size('WordDocument') - -get_type(path) returns the type of a stream/storage, as one of the following constants: STGTY\_STREAM for a stream, STGTY\_STORAGE for a storage, STGTY\_ROOT for the root entry, and False for a non existing path (new in v0.15). - - :::python - t = ole.get_type('WordDocument') - -get\_ctime(path) and get\_mtime(path) return the creation and modification timestamps of a stream/storage, as a Python datetime object with UTC timezone. Please note that these timestamps are only present if the application that created the OLE file explicitly stored them, which is rarely the case. When not present, these methods return None (new in v0.26). - - :::python - c = ole.get_ctime('WordDocument') - m = ole.get_mtime('WordDocument') - -The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute (new in v0.26): - - :::python - c = ole.root.getctime() - m = ole.root.getmtime() - -Note: all these methods are case-insensitive. - -## Overwriting a sector - -The write_sect method can overwrite any sector of the file. If the provided data is smaller than the sector size (normally 512 bytes, sometimes 4KB), data is padded with null characters. (new in v0.40) - -Here is an example: - - :::python - ole.write_sect(0x17, b'TEST') - -Note: following the [MS-CFB specifications](http://msdn.microsoft.com/en-us/library/dd942138.aspx), sector 0 is actually the second sector of the file. You may use -1 as index to write the first sector. - - -## Overwriting a stream - -The write_stream method can overwrite an existing stream in the file. The new stream data must be the exact same size as the existing one. For now, write_stream can only write streams of 4KB or larger (stored in the main FAT). - -For example, you may change text in a MS Word document: - - :::python - ole = olefile.OleFileIO('test.doc', write_mode=True) - data = ole.openstream('WordDocument').read() - data = data.replace(b'foo', b'bar') - ole.write_stream('WordDocument', data) - ole.close() - -(new in v0.40) - - - -## Extract metadata - -get_metadata() will check if standard property streams exist, parse all the properties they contain, and return an OleMetadata object with the found properties as attributes (new in v0.24). - - :::python - meta = ole.get_metadata() - print('Author:', meta.author) - print('Title:', meta.title) - print('Creation date:', meta.create_time) - # print all metadata: - meta.dump() - -Available attributes include: - - :::text - codepage, title, subject, author, keywords, comments, template, - last_saved_by, revision_number, total_edit_time, last_printed, create_time, - last_saved_time, num_pages, num_words, num_chars, thumbnail, - creating_application, security, codepage_doc, category, presentation_target, - bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips, - scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty, - chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed, - version, dig_sig, content_type, content_status, language, doc_version - -See the source code of the OleMetadata class for more information. - - -## Parse a property stream - -get\_properties(path) can be used to parse any property stream that is not handled by get\_metadata. It returns a dictionary indexed by integers. Each integer is the index of the property, pointing to its value. For example in the standard property stream '\x05SummaryInformation', the document title is property #2, and the subject is #3. - - :::python - p = ole.getproperties('specialprops') - -By default as in the original PIL version, timestamp properties are converted into a number of seconds since Jan 1,1601. With the option convert\_time, you can obtain more convenient Python datetime objects (UTC timezone). If some time properties should not be converted (such as total editing time in '\x05SummaryInformation'), the list of indexes can be passed as no_conversion (new in v0.25): - - :::python - p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10]) - - -## Close the OLE file - -Unless your application is a simple script that terminates after processing an OLE file, do not forget to close each OleFileIO object after parsing to close the file on disk. (new in v0.22) - - :::python - ole.close() - -## Use olefile as a script for testing/debugging - -olefile can also be used as a script from the command-line to display the structure of an OLE file and its metadata, for example: - - :::text - olefile.py myfile.doc - -You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information. - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/Contribute.html b/oletools/thirdparty/olefile/doc/Contribute.html deleted file mode 100644 index 2ae57ca..0000000 --- a/oletools/thirdparty/olefile/doc/Contribute.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - -

How to Suggest Improvements, Report Issues or Contribute

-

This is a personal open-source project, developed on my spare time. Any contribution, suggestion, feedback or bug report is welcome.

-

To suggest improvements, report a bug or any issue, please use the issue reporting page, providing all the information and files to reproduce the problem.

-

If possible please join the debugging output of olefile. For this, launch the following command :

-
    olefile.py -d -c file >debug.txt 
-

You may also contact the author directly to provide feedback.

-

The code is available in a Mercurial repository on Bitbucket. You may use it to submit enhancements using forks and pull requests.

-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/Contribute.md b/oletools/thirdparty/olefile/doc/Contribute.md deleted file mode 100644 index 0de1e4b..0000000 --- a/oletools/thirdparty/olefile/doc/Contribute.md +++ /dev/null @@ -1,28 +0,0 @@ -How to Suggest Improvements, Report Issues or Contribute -======================================================== - -This is a personal open-source project, developed on my spare time. Any contribution, suggestion, feedback or bug report is welcome. - -To **suggest improvements, report a bug or any issue**, please use the [issue reporting page](https://bitbucket.org/decalage/olefileio_pl/issues?status=new&status=open), providing all the information and files to reproduce the problem. - -If possible please join the debugging output of olefile. For this, launch the following command : - - :::text - olefile.py -d -c file >debug.txt - - -You may also [contact the author](http://decalage.info/contact) directly to **provide feedback**. - -The code is available in [a Mercurial repository on Bitbucket](https://bitbucket.org/decalage/olefileio_pl). You may use it to **submit enhancements** using forks and pull requests. - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/Home.html b/oletools/thirdparty/olefile/doc/Home.html deleted file mode 100644 index 57e734d..0000000 --- a/oletools/thirdparty/olefile/doc/Home.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - -

olefile v0.42 documentation

-

This is the home page of the documentation for olefile. The latest version can be found online, otherwise a copy is provided in the doc subfolder of the package.

-

olefile is a Python package to parse, read and write Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file formats, McAfee antivirus quarantine files, etc.

-

Quick links: Home page - Download/Install - Documentation - Report Issues/Suggestions/Questions - Contact the author - Repository - Updates on Twitter

-

Documentation pages

- -

Features

-
    -
  • Parse, read and write any OLE file such as Microsoft Office 97-2003 legacy document formats (Word .doc, Excel .xls, PowerPoint .ppt, Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook messages, StickyNotes, Zeiss AxioVision ZVI files, Olympus FluoView OIB files, etc
  • -
  • List all the streams and storages contained in an OLE file
  • -
  • Open streams as files
  • -
  • Parse and read property streams, containing metadata of the file
  • -
  • Portable, pure Python module, no dependency
  • -
-

olefile can be used as an independent module or with PIL/Pillow.

-

olefile is mostly meant for developers. If you are looking for tools to analyze OLE files or to extract data (especially for security purposes such as malware analysis and forensics), then please also check my python-oletools, which are built upon olefile and provide a higher-level interface.

-

History

-

olefile is based on the OleFileIO module from PIL, the excellent Python Imaging Library, created and maintained by Fredrik Lundh. The olefile API is still compatible with PIL, but since 2005 I have improved the internal implementation significantly, with new features, bugfixes and a more robust design. From 2005 to 2014 the project was called OleFileIO_PL, and in 2014 I changed its name to olefile to celebrate its 9 years and its new write features.

-

As far as I know, this module is the most complete and robust Python implementation to read MS OLE2 files, portable on several operating systems. (please tell me if you know other similar Python modules)

-

Since 2014 olefile/OleFileIO_PL has been integrated into Pillow, the friendly fork of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly.

-

Main improvements over the original version of OleFileIO in PIL:

-
    -
  • Compatible with Python 3.x and 2.6+
  • -
  • Many bug fixes
  • -
  • Support for files larger than 6.8MB
  • -
  • Support for 64 bits platforms and big-endian CPUs
  • -
  • Robust: many checks to detect malformed files
  • -
  • Runtime option to choose if malformed files should be parsed or raise exceptions
  • -
  • Improved API
  • -
  • Metadata extraction, stream/storage timestamps (e.g. for document forensics)
  • -
  • Can open file-like objects
  • -
  • Added setup.py and install.bat to ease installation
  • -
  • More convenient slash-based syntax for stream paths
  • -
  • Write features
  • -
-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/Home.md b/oletools/thirdparty/olefile/doc/Home.md deleted file mode 100644 index 4f22e55..0000000 --- a/oletools/thirdparty/olefile/doc/Home.md +++ /dev/null @@ -1,94 +0,0 @@ -olefile v0.42 documentation -=========================== - -This is the home page of the documentation for olefile. The latest version can be found -[online](https://bitbucket.org/decalage/olefileio_pl/wiki), otherwise a copy is provided in the doc subfolder of the package. - -[olefile](http://www.decalage.info/olefile) is a Python package to parse, read and write -[Microsoft OLE2 files](http://en.wikipedia.org/wiki/Compound_File_Binary_Format) -(also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft -Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file -formats, McAfee antivirus quarantine files, etc. - - -**Quick links:** -[Home page](http://www.decalage.info/olefile) - -[Download/Install](https://bitbucket.org/decalage/olefileio_pl/wiki/Install) - -[Documentation](https://bitbucket.org/decalage/olefileio_pl/wiki) - -[Report Issues/Suggestions/Questions](https://bitbucket.org/decalage/olefileio_pl/issues?status=new&status=open) - -[Contact the author](http://decalage.info/contact) - -[Repository](https://bitbucket.org/decalage/olefileio_pl) - -[Updates on Twitter](https://twitter.com/decalage2) - -Documentation pages -------------------- - -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage - - -Features --------- - -- Parse, read and write any OLE file such as Microsoft Office 97-2003 legacy document formats (Word .doc, Excel .xls, - PowerPoint .ppt, Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook messages, StickyNotes, Zeiss - AxioVision ZVI files, Olympus FluoView OIB files, etc -- List all the streams and storages contained in an OLE file -- Open streams as files -- Parse and read property streams, containing metadata of the file -- Portable, pure Python module, no dependency - -olefile can be used as an independent module or with PIL/Pillow. - -olefile is mostly meant for developers. If you are looking for tools to analyze OLE files or to extract data -(especially for security purposes such as malware analysis and forensics), then please also check my -[python-oletools](http://www.decalage.info/python/oletools), which are built upon olefile and provide a higher-level -interface. - - -History -------- - -olefile is based on the OleFileIO module from [PIL](http://www.pythonware.com/products/pil/index.htm), the excellent -Python Imaging Library, created and maintained by Fredrik Lundh. The olefile API is still compatible with PIL, but -since 2005 I have improved the internal implementation significantly, with new features, bugfixes and a more robust -design. From 2005 to 2014 the project was called OleFileIO_PL, and in 2014 I changed its name to olefile to celebrate -its 9 years and its new write features. - -As far as I know, this module is the most complete and robust Python implementation to read MS OLE2 files, portable on -several operating systems. (please tell me if you know other similar Python modules) - -Since 2014 olefile/OleFileIO_PL has been integrated into [Pillow](http://python-imaging.github.io/), the friendly fork -of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly. - -Main improvements over the original version of OleFileIO in PIL: ----------------------------------------------------------------- - -- Compatible with Python 3.x and 2.6+ -- Many bug fixes -- Support for files larger than 6.8MB -- Support for 64 bits platforms and big-endian CPUs -- Robust: many checks to detect malformed files -- Runtime option to choose if malformed files should be parsed or raise exceptions -- Improved API -- Metadata extraction, stream/storage timestamps (e.g. for document forensics) -- Can open file-like objects -- Added setup.py and install.bat to ease installation -- More convenient slash-based syntax for stream paths -- Write features - - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/Install.html b/oletools/thirdparty/olefile/doc/Install.html deleted file mode 100644 index 1560a94..0000000 --- a/oletools/thirdparty/olefile/doc/Install.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - -

How to Download and Install olefile

-

Pre-requisites

-

olefile requires Python 2.6, 2.7 or 3.x.

-

For Python 2.5 and older, olefile falls back to an older version (based on OleFileIO_PL 0.26) which might not contain all the enhancements implemented in olefile.

-

Download and Install

-

To use olefile with other Python applications or your own scripts, the simplest solution is to run pip install olefile or easy_install olefile, to download and install the package in one go. Pip is part of the standard Python distribution since v2.7.9.

-

To update olefile if a previous version is already installed, run pip install -U olefile.

-

Otherwise you may download/extract the zip archive in a temporary directory and run python setup.py install.

-

On Windows you may simply double-click on install.bat.

-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/Install.md b/oletools/thirdparty/olefile/doc/Install.md deleted file mode 100644 index 6afa624..0000000 --- a/oletools/thirdparty/olefile/doc/Install.md +++ /dev/null @@ -1,37 +0,0 @@ -How to Download and Install olefile -=================================== - -Pre-requisites --------------- - -olefile requires Python 2.6, 2.7 or 3.x. - -For Python 2.5 and older, olefile falls back to an older version (based on OleFileIO_PL 0.26) which might not contain -all the enhancements implemented in olefile. - - -Download and Install --------------------- - -To use olefile with other Python applications or your own scripts, the simplest solution is to run **pip install olefile** -or **easy_install olefile**, to download and install the package in one go. Pip is part of the standard Python -distribution since v2.7.9. - -To update olefile if a previous version is already installed, run **pip install -U olefile**. - -Otherwise you may download/extract the [zip archive](https://bitbucket.org/decalage/olefileio_pl/downloads) in a -temporary directory and run **python setup.py install**. - -On Windows you may simply double-click on **install.bat**. - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/License.html b/oletools/thirdparty/olefile/doc/License.html deleted file mode 100644 index f83c512..0000000 --- a/oletools/thirdparty/olefile/doc/License.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - -

License for olefile

-

olefile (formerly OleFileIO_PL) is copyright (c) 2005-2015 Philippe Lagadec (http://www.decalage.info)

-

All rights reserved.

-

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

-
    -
  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • -
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • -
-

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-
-

olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license:

-

The Python Imaging Library (PIL) is

-
    -
  • Copyright (c) 1997-2005 by Secret Labs AB
  • -
  • Copyright (c) 1995-2005 by Fredrik Lundh
  • -
-

By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions:

-

Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

-

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/License.md b/oletools/thirdparty/olefile/doc/License.md deleted file mode 100644 index 28bc4c1..0000000 --- a/oletools/thirdparty/olefile/doc/License.md +++ /dev/null @@ -1,54 +0,0 @@ -License for olefile -=================== - -olefile (formerly OleFileIO_PL) is copyright (c) 2005-2015 Philippe Lagadec ([http://www.decalage.info](http://www.decalage.info)) - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------- - -olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license: - -The Python Imaging Library (PIL) is - -- Copyright (c) 1997-2005 by Secret Labs AB -- Copyright (c) 1995-2005 by Fredrik Lundh - -By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: - -Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. - -SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/OLE_Overview.html b/oletools/thirdparty/olefile/doc/OLE_Overview.html deleted file mode 100644 index ed48120..0000000 --- a/oletools/thirdparty/olefile/doc/OLE_Overview.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - -

About the structure of OLE files

-

This page is part of the documentation for olefile. It provides a brief overview of the structure of Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file formats, McAfee antivirus quarantine files, etc.

-

An OLE file can be seen as a mini file system or a Zip archive: It contains streams of data that look like files embedded within the OLE file. Each stream has a name. For example, the main stream of a MS Word document containing its text is named "WordDocument".

-

An OLE file can also contain storages. A storage is a folder that contains streams or other storages. For example, a MS Word document with VBA macros has a storage called "Macros".

-

Special streams can contain properties. A property is a specific value that can be used to store information such as the metadata of a document (title, author, creation date, etc). Property stream names usually start with the character '05'.

-

For example, a typical MS Word document may look like this:

-
-

-
-

Go to the API page to see how to use all olefile features to parse OLE files.

-
-

olefile documentation

- - - diff --git a/oletools/thirdparty/olefile/doc/OLE_Overview.md b/oletools/thirdparty/olefile/doc/OLE_Overview.md deleted file mode 100644 index db7fa66..0000000 --- a/oletools/thirdparty/olefile/doc/OLE_Overview.md +++ /dev/null @@ -1,29 +0,0 @@ -About the structure of OLE files -================================ - -This page is part of the documentation for [olefile](https://bitbucket.org/decalage/olefileio_pl/wiki). It provides a brief overview of the structure of [Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format)](http://en.wikipedia.org/wiki/Compound_File_Binary_Format), such as Microsoft Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file formats, McAfee antivirus quarantine files, etc. - -An OLE file can be seen as a mini file system or a Zip archive: It contains **streams** of data that look like files embedded within the OLE file. Each stream has a name. For example, the main stream of a MS Word document containing its text is named "WordDocument". - -An OLE file can also contain **storages**. A storage is a folder that contains streams or other storages. For example, a MS Word document with VBA macros has a storage called "Macros". - -Special streams can contain **properties**. A property is a specific value that can be used to store information such as the metadata of a document (title, author, creation date, etc). Property stream names usually start with the character '\x05'. - -For example, a typical MS Word document may look like this: - -![](OLE_VBA_sample.png) - -Go to the [[API]] page to see how to use all olefile features to parse OLE files. - - --------------------------------------------------------------------------- - -olefile documentation ---------------------- - -- [[Home]] -- [[License]] -- [[Install]] -- [[Contribute]], Suggest Improvements or Report Issues -- [[OLE_Overview]] -- [[API]] and Usage diff --git a/oletools/thirdparty/olefile/doc/OLE_VBA_sample.png b/oletools/thirdparty/olefile/doc/OLE_VBA_sample.png deleted file mode 100644 index 93f74d5..0000000 --- a/oletools/thirdparty/olefile/doc/OLE_VBA_sample.png +++ /dev/null diff --git a/oletools/thirdparty/olefile/olefile.html b/oletools/thirdparty/olefile/olefile.html deleted file mode 100644 index b7d1981..0000000 --- a/oletools/thirdparty/olefile/olefile.html +++ /dev/null @@ -1,432 +0,0 @@ - - -Python: module olefile - - - - -
 
- 
olefile (version 0.42, 2015-01-24)
index
.\olefile.py
-

# olefile (formerly OleFileIO_PL) version 0.42 2015-01-24
-#
-# Module to read/write Microsoft OLE2 files (also called Structured Storage or
-# Microsoft Compound Document File Format), such as Microsoft Office 97-2003
-# documents, Image Composer and FlashPix files, Outlook messages, ...
-# This version is compatible with Python 2.6+ and 3.x
-#
-# Project website: http://www.decalage.info/olefile
-#
-# olefile is copyright (c) 2005-2015 Philippe Lagadec (http://www.decalage.info)
-#
-# olefile is based on the OleFileIO module from the PIL library v1.1.6
-# See: http://www.pythonware.com/products/pil/index.htm
-#
-# The Python Imaging Library (PIL) is
-# Copyright (c) 1997-2005 by Secret Labs AB
-# Copyright (c) 1995-2005 by Fredrik Lundh
-#
-# See source code and LICENSE.txt for information on usage and redistribution.

-

- - - - - -
 
-Modules
       
array
-datetime
-
io
-os
-
struct
-sys
-

- - - - - -
 
-Classes
       
-
OleFileIO -
OleMetadata -
-

- - - - - - - -
 
-class OleFileIO
   OLE container object

-This class encapsulates the interface to an OLE 2 structured
-storage file.  Use the listdir and openstream methods to
-access the contents of this file.

-Object names are given as a list of strings, one for each subentry
-level.  The root entry should be omitted.  For example, the following
-code extracts all image streams from a Microsoft Image Composer file::

-    ole = OleFileIO("fan.mic")

-    for entry in ole.listdir():
-        if entry[1:2] == "Image":
-            fin = ole.openstream(entry)
-            fout = open(entry[0:1], "wb")
-            while True:
-                s = fin.read(8192)
-                if not s:
-                    break
-                fout.write(s)

-You can use the viewer application provided with the Python Imaging
-Library to view the resulting files (which happens to be standard
-TIFF files).
 
 Methods defined here:
-
__init__(self, filename=None, raise_defects=40, write_mode=False, debug=False, path_encoding='utf-8')
Constructor for the OleFileIO class.

-:param filename: file to open.

-    - if filename is a string smaller than 1536 bytes, it is the path
-      of the file to open. (bytes or unicode string)
-    - if filename is a string longer than 1535 bytes, it is parsed
-      as the content of an OLE file in memory. (bytes type only)
-    - if filename is a file-like object (with read, seek and tell methods),
-      it is parsed as-is.

-:param raise_defects: minimal level for defects to be raised as exceptions.
-    (use DEFECT_FATAL for a typical application, DEFECT_INCORRECT for a
-    security-oriented application, see source code for details)

-:param write_mode: bool, if True the file is opened in read/write mode instead
-    of read-only by default.

-:param debug: bool, set debug mode

-:param path_encoding: None or str, name of the codec to use for path
-    names (streams and storages), or None for Unicode.
-    Unicode by default on Python 3+, UTF-8 on Python 2.x.
-    (new in olefile 0.42, was hardcoded to Latin-1 until olefile v0.41)
- -
close(self)
close the OLE file, to release the file object
- -
dumpdirectory(self)
Dump directory (for debugging only)
- -
dumpfat(self, fat, firstindex=0)
Displays a part of FAT in human-readable form for debugging purpose
- -
dumpsect(self, sector, firstindex=0)
Displays a sector in a human-readable form, for debugging purpose.
- -
exists(self, filename)
Test if given filename exists as a stream or a storage in the OLE
-container.
-Note: filename is case-insensitive.

-:param filename: path of stream in storage tree. (see openstream for syntax)
-:returns: True if object exist, else False.
- -
get_metadata(self)
Parse standard properties streams, return an OleMetadata object
-containing all the available metadata.
-(also stored in the metadata attribute of the OleFileIO object)

-new in version 0.25
- -
get_rootentry_name(self)
Return root entry name. Should usually be 'Root Entry' or 'R' in most
-implementations.
- -
get_size(self, filename)
Return size of a stream in the OLE container, in bytes.

-:param filename: path of stream in storage tree (see openstream for syntax)
-:returns: size in bytes (long integer)
-:exception IOError: if file not found
-:exception TypeError: if this is not a stream.
- -
get_type(self, filename)
Test if given filename exists as a stream or a storage in the OLE
-container, and return its type.

-:param filename: path of stream in storage tree. (see openstream for syntax)
-:returns: False if object does not exist, its entry type (>0) otherwise:

-    - STGTY_STREAM: a stream
-    - STGTY_STORAGE: a storage
-    - STGTY_ROOT: the root entry
- -
getctime(self, filename)
Return creation time of a stream/storage.

-:param filename: path of stream/storage in storage tree. (see openstream for
-    syntax)
-:returns: None if creation time is null, a python datetime object
-    otherwise (UTC timezone)

-new in version 0.26
- -
getmtime(self, filename)
Return modification time of a stream/storage.

-:param filename: path of stream/storage in storage tree. (see openstream for
-    syntax)
-:returns: None if modification time is null, a python datetime object
-    otherwise (UTC timezone)

-new in version 0.26
- -
getproperties(self, filename, convert_time=False, no_conversion=None)
Return properties described in substream.

-:param filename: path of stream in storage tree (see openstream for syntax)
-:param convert_time: bool, if True timestamps will be converted to Python datetime
-:param no_conversion: None or list of int, timestamps not to be converted
-    (for example total editing time is not a real timestamp)

-:returns: a dictionary of values indexed by id (integer)
- -
getsect(self, sect)
Read given sector from file on disk.

-:param sect: int, sector index
-:returns: a string containing the sector data.
- -
listdir(self, streams=True, storages=False)
Return a list of streams and/or storages stored in this file

-:param streams: bool, include streams if True (True by default) - new in v0.26
-:param storages: bool, include storages if True (False by default) - new in v0.26
-    (note: the root storage is never included)
-:returns: list of stream and/or storage paths
- -
loaddirectory(self, sect)
Load the directory.

-:param sect: sector index of directory stream.
- -
loadfat(self, header)
Load the FAT table.
- -
loadfat_sect(self, sect)
Adds the indexes of the given sector to the FAT

-:param sect: string containing the first FAT sector, or array of long integers
-:returns: index of last FAT sector.
- -
loadminifat(self)
Load the MiniFAT table.
- -
open(self, filename, write_mode=False)
Open an OLE2 file in read-only or read/write mode.
-Read and parse the header, FAT and directory.

-:param filename: string-like or file-like object, OLE file to parse

-    - if filename is a string smaller than 1536 bytes, it is the path
-      of the file to open. (bytes or unicode string)
-    - if filename is a string longer than 1535 bytes, it is parsed
-      as the content of an OLE file in memory. (bytes type only)
-    - if filename is a file-like object (with read, seek and tell methods),
-      it is parsed as-is.

-:param write_mode: bool, if True the file is opened in read/write mode instead
-    of read-only by default. (ignored if filename is not a path)
- -
openstream(self, filename)
Open a stream as a read-only file object (BytesIO).
-Note: filename is case-insensitive.

-:param filename: path of stream in storage tree (except root entry), either:

-    - a string using Unix path syntax, for example:
-      'storage_1/storage_1.2/stream'
-    - or a list of storage filenames, path to the desired stream/storage.
-      Example: ['storage_1', 'storage_1.2', 'stream']

-:returns: file object (read-only)
-:exception IOError: if filename not found, or if this is not a stream.
- -
sect2array(self, sect)
convert a sector to an array of 32 bits unsigned integers,
-swapping bytes on big endian CPUs such as PowerPC (old Macs)
- -
write_sect(self, sect, data, padding='\x00')
Write given sector to file on disk.

-:param sect: int, sector index
-:param data: bytes, sector data
-:param padding: single byte, padding character if data < sector size
- -
write_stream(self, stream_name, data)
Write a stream to disk. For now, it is only possible to replace an
-existing stream by data of the same size.

-:param stream_name: path of stream in storage tree (except root entry), either:

-    - a string using Unix path syntax, for example:
-      'storage_1/storage_1.2/stream'
-    - or a list of storage filenames, path to the desired stream/storage.
-      Example: ['storage_1', 'storage_1.2', 'stream']

-:param data: bytes, data to be written, must be the same size as the original
-    stream.
- -

- - - - - - - -
 
-class OleMetadata
   class to parse and store metadata from standard properties of OLE files.

-Available attributes:
-codepage, title, subject, author, keywords, comments, template,
-last_saved_by, revision_number, total_edit_time, last_printed, create_time,
-last_saved_time, num_pages, num_words, num_chars, thumbnail,
-creating_application, security, codepage_doc, category, presentation_target,
-bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
-scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
-chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
-version, dig_sig, content_type, content_status, language, doc_version

-Note: an attribute is set to None when not present in the properties of the
-OLE file.

-References for SummaryInformation stream:
-- http://msdn.microsoft.com/en-us/library/dd942545.aspx
-- http://msdn.microsoft.com/en-us/library/dd925819%28v=office.12%29.aspx
-- http://msdn.microsoft.com/en-us/library/windows/desktop/aa380376%28v=vs.85%29.aspx
-- http://msdn.microsoft.com/en-us/library/aa372045.aspx
-- http://sedna-soft.de/summary-information-stream/
-- http://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html

-References for DocumentSummaryInformation stream:
-- http://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx
-- http://msdn.microsoft.com/en-us/library/windows/desktop/aa380374%28v=vs.85%29.aspx
-- http://poi.apache.org/apidocs/org/apache/poi/hpsf/DocumentSummaryInformation.html

-new in version 0.25
 
 Methods defined here:
-
__init__(self)
Constructor for OleMetadata
-All attributes are set to None by default
- -
dump(self)
Dump all metadata, for debugging purposes.
- -
parse_properties(self, olefile)
Parse standard properties of an OLE file, from the streams
-"SummaryInformation" and "DocumentSummaryInformation",
-if present.
-Properties are converted to strings, integers or python datetime objects.
-If a property is not present, its value is set to None.
- -
-Data and other attributes defined here:
-
DOCSUM_ATTRIBS = ['codepage_doc', 'category', 'presentation_target', 'bytes', 'lines', 'paragraphs', 'slides', 'notes', 'hidden_slides', 'mm_clips', 'scale_crop', 'heading_pairs', 'titles_of_parts', 'manager', 'company', 'links_dirty', 'chars_with_spaces', 'unused', 'shared_doc', 'link_base', ...]
- -
SUMMARY_ATTRIBS = ['codepage', 'title', 'subject', 'author', 'keywords', 'comments', 'template', 'last_saved_by', 'revision_number', 'total_edit_time', 'last_printed', 'create_time', 'last_saved_time', 'num_pages', 'num_words', 'num_chars', 'thumbnail', 'creating_application', 'security']
- -

- - - - - -
 
-Functions
       
debug = debug_pass(msg)
-
debug_pass(msg)
-
debug_print(msg)
-
filetime2datetime(filetime)
convert FILETIME (64 bits int) to Python datetime.datetime
-
i16(c, o=0)
Converts a 2-bytes (16 bits) string to an integer.

-:param c: string containing bytes to convert
-:param o: offset of bytes to convert in string
-
i32(c, o=0)
Converts a 4-bytes (32 bits) string to an integer.

-:param c: string containing bytes to convert
-:param o: offset of bytes to convert in string
-
i8(c)
# version for Python 2.x
-
isOleFile(filename)
Test if a file is an OLE container (according to the magic bytes in its header).

-:param filename: string-like or file-like object, OLE file to parse

-    - if filename is a string smaller than 1536 bytes, it is the path
-      of the file to open. (bytes or unicode string)
-    - if filename is a string longer than 1535 bytes, it is parsed
-      as the content of an OLE file in memory. (bytes type only)
-    - if filename is a file-like object (with read and seek methods),
-      it is parsed as-is.

-:returns: True if OLE, False otherwise.
-
set_debug_mode(debug_mode)
Set debug mode on or off, to control display of debugging messages.
-:param mode: True or False
-

- - - - - -
 
-Data
       DEBUG_MODE = False
-DEFAULT_PATH_ENCODING = 'utf-8'
-DEFECT_FATAL = 40
-DEFECT_INCORRECT = 30
-DEFECT_POTENTIAL = 20
-DEFECT_UNSURE = 10
-DIFSECT = 4294967292L
-ENDOFCHAIN = 4294967294L
-FATSECT = 4294967293L
-FREESECT = 4294967295L
-KEEP_UNICODE_NAMES = True
-MAGIC = '\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'
-MAXREGSECT = 4294967290L
-MAXREGSID = 4294967290L
-MINIMAL_OLEFILE_SIZE = 1536
-NOSTREAM = 4294967295L
-STGTY_EMPTY = 0
-STGTY_LOCKBYTES = 3
-STGTY_PROPERTY = 4
-STGTY_ROOT = 5
-STGTY_STORAGE = 1
-STGTY_STREAM = 2
-UINT32 = 'L'
-VT = {0: 'VT_EMPTY', 1: 'VT_NULL', 2: 'VT_I2', 3: 'VT_I4', 4: 'VT_R4', 5: 'VT_R8', 6: 'VT_CY', 7: 'VT_DATE', 8: 'VT_BSTR', 9: 'VT_DISPATCH', ...}
-VT_BLOB = 65
-VT_BLOB_OBJECT = 70
-VT_BOOL = 11
-VT_BSTR = 8
-VT_CARRAY = 28
-VT_CF = 71
-VT_CLSID = 72
-VT_CY = 6
-VT_DATE = 7
-VT_DECIMAL = 14
-VT_DISPATCH = 9
-VT_EMPTY = 0
-VT_ERROR = 10
-VT_FILETIME = 64
-VT_HRESULT = 25
-VT_I1 = 16
-VT_I2 = 2
-VT_I4 = 3
-VT_I8 = 20
-VT_INT = 22
-VT_LPSTR = 30
-VT_LPWSTR = 31
-VT_NULL = 1
-VT_PTR = 26
-VT_R4 = 4
-VT_R8 = 5
-VT_SAFEARRAY = 27
-VT_STORAGE = 67
-VT_STORED_OBJECT = 69
-VT_STREAM = 66
-VT_STREAMED_OBJECT = 68
-VT_UI1 = 17
-VT_UI2 = 18
-VT_UI4 = 19
-VT_UI8 = 21
-VT_UINT = 23
-VT_UNKNOWN = 13
-VT_USERDEFINED = 29
-VT_VARIANT = 12
-VT_VECTOR = 4096
-VT_VOID = 24
-WORD_CLSID = '00020900-0000-0000-C000-000000000046'
-__author__ = 'Philippe Lagadec'
-__date__ = '2015-01-24'
-__version__ = '0.42'
-keyword = 'VT_UNKNOWN'
-print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536)
-var = 13

- - - - - -
 
-Author
       Philippe Lagadec
- \ No newline at end of file diff --git a/oletools/thirdparty/olefile/olefile.py b/oletools/thirdparty/olefile/olefile.py deleted file mode 100644 index a22b942..0000000 --- a/oletools/thirdparty/olefile/olefile.py +++ /dev/null @@ -1,2478 +0,0 @@ -""" -olefile (formerly OleFileIO_PL) - -Module to read/write Microsoft OLE2 files (also called Structured Storage or -Microsoft Compound Document File Format), such as Microsoft Office 97-2003 -documents, Image Composer and FlashPix files, Outlook messages, ... -This version is compatible with Python 2.6+ and 3.x - -Project website: https://www.decalage.info/olefile - -olefile is copyright (c) 2005-2017 Philippe Lagadec -(https://www.decalage.info) - -olefile is based on the OleFileIO module from the PIL library v1.1.7 -See: http://www.pythonware.com/products/pil/index.htm -and http://svn.effbot.org/public/tags/pil-1.1.7/PIL/OleFileIO.py - -The Python Imaging Library (PIL) is -Copyright (c) 1997-2009 by Secret Labs AB -Copyright (c) 1995-2009 by Fredrik Lundh - -See source code and LICENSE.txt for information on usage and redistribution. -""" - -# Since OleFileIO_PL v0.30, only Python 2.6+ and 3.x is supported -# This import enables print() as a function rather than a keyword -# (main requirement to be compatible with Python 3.x) -# The comment on the line below should be printed on Python 2.5 or older: -from __future__ import print_function # This version of olefile requires Python 2.6+ or 3.x. - - -#--- LICENSE ------------------------------------------------------------------ - -# olefile (formerly OleFileIO_PL) is copyright (c) 2005-2017 Philippe Lagadec -# (https://www.decalage.info) -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# ---------- -# PIL License: -# -# olefile is based on source code from the OleFileIO module of the Python -# Imaging Library (PIL) published by Fredrik Lundh under the following license: - -# The Python Imaging Library (PIL) is -# Copyright (c) 1997-2009 by Secret Labs AB -# Copyright (c) 1995-2009 by Fredrik Lundh -# -# By obtaining, using, and/or copying this software and/or its associated -# documentation, you agree that you have read, understood, and will comply with -# the following terms and conditions: -# -# Permission to use, copy, modify, and distribute this software and its -# associated documentation for any purpose and without fee is hereby granted, -# provided that the above copyright notice appears in all copies, and that both -# that copyright notice and this permission notice appear in supporting -# documentation, and that the name of Secret Labs AB or the author(s) not be used -# in advertising or publicity pertaining to distribution of the software -# without specific, written prior permission. -# -# SECRET LABS AB AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -# IN NO EVENT SHALL SECRET LABS AB OR THE AUTHORS BE LIABLE FOR ANY SPECIAL, -# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -# PERFORMANCE OF THIS SOFTWARE. - -#----------------------------------------------------------------------------- -# CHANGELOG: (only olefile/OleFileIO_PL changes compared to PIL 1.1.6) -# 2005-05-11 v0.10 PL: - a few fixes for Python 2.4 compatibility -# (all changes flagged with [PL]) -# 2006-02-22 v0.11 PL: - a few fixes for some Office 2003 documents which raise -# exceptions in OleStream.__init__() -# 2006-06-09 v0.12 PL: - fixes for files above 6.8MB (DIFAT in loadfat) -# - added some constants -# - added header values checks -# - added some docstrings -# - getsect: bugfix in case sectors >512 bytes -# - getsect: added conformity checks -# - DEBUG_MODE constant to activate debug display -# 2007-09-04 v0.13 PL: - improved/translated (lots of) comments -# - updated license -# - converted tabs to 4 spaces -# 2007-11-19 v0.14 PL: - added OleFileIO._raise_defect() to adapt sensitivity -# - improved _unicode() to use Python 2.x unicode support -# - fixed bug in OleDirectoryEntry -# 2007-11-25 v0.15 PL: - added safety checks to detect FAT loops -# - fixed OleStream which didn't check stream size -# - added/improved many docstrings and comments -# - moved helper functions _unicode and _clsid out of -# OleFileIO class -# - improved OleFileIO._find() to add Unix path syntax -# - OleFileIO._find() is now case-insensitive -# - added get_type() and get_rootentry_name() -# - rewritten loaddirectory and OleDirectoryEntry -# 2007-11-27 v0.16 PL: - added OleDirectoryEntry.kids_dict -# - added detection of duplicate filenames in storages -# - added detection of duplicate references to streams -# - added get_size() and exists() to OleDirectoryEntry -# - added isOleFile to check header before parsing -# - added __all__ list to control public keywords in pydoc -# 2007-12-04 v0.17 PL: - added _load_direntry to fix a bug in loaddirectory -# - improved _unicode(), added workarounds for Python <2.3 -# - added set_debug_mode and -d option to set debug mode -# - fixed bugs in OleFileIO.open and OleDirectoryEntry -# - added safety check in main for large or binary -# properties -# - allow size>0 for storages for some implementations -# 2007-12-05 v0.18 PL: - fixed several bugs in handling of FAT, MiniFAT and -# streams -# - added option '-c' in main to check all streams -# 2009-12-10 v0.19 PL: - bugfix for 32 bit arrays on 64 bits platforms -# (thanks to Ben G. and Martijn for reporting the bug) -# 2009-12-11 v0.20 PL: - bugfix in OleFileIO.open when filename is not plain str -# 2010-01-22 v0.21 PL: - added support for big-endian CPUs such as PowerPC Macs -# 2012-02-16 v0.22 PL: - fixed bug in getproperties, patch by chuckleberryfinn -# (https://github.com/decalage2/olefile/issues/7) -# - added close method to OleFileIO (fixed issue #2) -# 2012-07-25 v0.23 PL: - added support for file-like objects (patch by mete0r_kr) -# 2013-05-05 v0.24 PL: - getproperties: added conversion from filetime to python -# datetime -# - main: displays properties with date format -# - new class OleMetadata to parse standard properties -# - added get_metadata method -# 2013-05-07 v0.24 PL: - a few improvements in OleMetadata -# 2013-05-24 v0.25 PL: - getproperties: option to not convert some timestamps -# - OleMetaData: total_edit_time is now a number of seconds, -# not a timestamp -# - getproperties: added support for VT_BOOL, VT_INT, V_UINT -# - getproperties: filter out null chars from strings -# - getproperties: raise non-fatal defects instead of -# exceptions when properties cannot be parsed properly -# 2013-05-27 PL: - getproperties: improved exception handling -# - _raise_defect: added option to set exception type -# - all non-fatal issues are now recorded, and displayed -# when run as a script -# 2013-07-11 v0.26 PL: - added methods to get modification and creation times -# of a directory entry or a storage/stream -# - fixed parsing of direntry timestamps -# 2013-07-24 PL: - new options in listdir to list storages and/or streams -# 2014-02-04 v0.30 PL: - upgraded code to support Python 3.x by Martin Panter -# - several fixes for Python 2.6 (xrange, MAGIC) -# - reused i32 from Pillow's _binary -# 2014-07-18 v0.31 - preliminary support for 4K sectors -# 2014-07-27 v0.31 PL: - a few improvements in OleFileIO.open (header parsing) -# - Fixed loadfat for large files with 4K sectors (issue #3) -# 2014-07-30 v0.32 PL: - added write_sect to write sectors to disk -# - added write_mode option to OleFileIO.__init__ and open -# 2014-07-31 PL: - fixed padding in write_sect for Python 3, added checks -# - added write_stream to write a stream to disk -# 2014-09-26 v0.40 PL: - renamed OleFileIO_PL to olefile -# 2014-11-09 NE: - added support for Jython (Niko Ehrenfeuchter) -# 2014-11-13 v0.41 PL: - improved isOleFile and OleFileIO.open to support OLE -# data in a string buffer and file-like objects. -# 2014-11-21 PL: - updated comments according to Pillow's commits -# 2015-01-24 v0.42 PL: - changed the default path name encoding from Latin-1 -# to UTF-8 on Python 2.x (Unicode on Python 3.x) -# - added path_encoding option to override the default -# - fixed a bug in _list when a storage is empty -# 2015-04-17 v0.43 PL: - slight changes in OleDirectoryEntry -# 2015-10-19 - fixed issue #26 in OleFileIO.getproperties -# (using id and type as local variable names) -# 2015-10-29 - replaced debug() with proper logging -# - use optparse to handle command line options -# - improved attribute names in OleFileIO class -# 2015-11-05 - fixed issue #27 by correcting the MiniFAT sector -# cutoff size if invalid. -# 2016-02-02 - logging is disabled by default -# 2016-04-26 v0.44 PL: - added enable_logging -# - renamed _OleDirectoryEntry and _OleStream without '_' -# - in OleStream use _raise_defect instead of exceptions -# 2016-04-27 - added support for incomplete streams and incorrect -# directory entries (to read malformed documents) -# 2016-05-04 - fixed slight bug in OleStream -# 2016-11-27 DR: - added method to get the clsid of a storage/stream -# (Daniel Roethlisberger) -# 2017-05-31 v0.45 BS: - PR #114 from oletools to handle excessive number of -# properties: -# https://github.com/decalage2/oletools/pull/114 -# 2017-07-11 PL: - ignore incorrect ByteOrder (issue #70) - -__date__ = "2017-07-11" -__version__ = '0.45dev2' -__author__ = "Philippe Lagadec" - -#----------------------------------------------------------------------------- -# TODO (for version 1.0): -# + get rid of print statements, to simplify Python 2.x and 3.x support -# + add is_stream and is_storage -# + remove leading and trailing slashes where a path is used -# + add functions path_list2str and path_str2list -# + fix how all the methods handle unicode str and/or bytes as arguments -# + add path attrib to _OleDirEntry, set it once and for all in init or -# append_kids (then listdir/_list can be simplified) -# - TESTS with Linux, MacOSX, Python 1.5.2, various files, PIL, ... -# - add underscore to each private method, to avoid their display in -# pydoc/epydoc documentation - Remove it for classes to be documented -# - replace all raised exceptions with _raise_defect (at least in OleFileIO) -# - merge code from OleStream and OleFileIO.getsect to read sectors -# (maybe add a class for FAT and MiniFAT ?) -# - add method to check all streams (follow sectors chains without storing all -# stream in memory, and report anomalies) -# - use OleDirectoryEntry.kids_dict to improve _find and _list ? -# - fix Unicode names handling (find some way to stay compatible with Py1.5.2) -# => if possible avoid converting names to Latin-1 -# - review DIFAT code: fix handling of DIFSECT blocks in FAT (not stop) -# - rewrite OleFileIO.getproperties -# - improve docstrings to show more sample uses -# - see also original notes and FIXME below -# - remove all obsolete FIXMEs -# - OleMetadata: fix version attrib according to -# https://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx - -# IDEAS: -# - in OleFileIO._open and OleStream, use size=None instead of 0x7FFFFFFF for -# streams with unknown size -# - use arrays of int instead of long integers for FAT/MiniFAT, to improve -# performance and reduce memory usage ? (possible issue with values >2^31) -# - provide tests with unittest (may need write support to create samples) -# - move all debug code (and maybe dump methods) to a separate module, with -# a class which inherits OleFileIO ? -# - fix docstrings to follow epydoc format -# - add support for big endian byte order ? -# - create a simple OLE explorer with wxPython - -# FUTURE EVOLUTIONS to add write support: -# see issue #6 on GitHub: -# https://github.com/decalage2/olefile/issues/6 - -#----------------------------------------------------------------------------- -# NOTES from PIL 1.1.6: - -# History: -# 1997-01-20 fl Created -# 1997-01-22 fl Fixed 64-bit portability quirk -# 2003-09-09 fl Fixed typo in OleFileIO.loadfat (noted by Daniel Haertle) -# 2004-02-29 fl Changed long hex constants to signed integers -# -# Notes: -# FIXME: sort out sign problem (eliminate long hex constants) -# FIXME: change filename to use "a/b/c" instead of ["a", "b", "c"] -# FIXME: provide a glob mechanism function (using fnmatchcase) -# -# Literature: -# -# "FlashPix Format Specification, Appendix A", Kodak and Microsoft, -# September 1996. -# -# Quotes: -# -# "If this document and functionality of the Software conflict, -# the actual functionality of the Software represents the correct -# functionality" -- Microsoft, in the OLE format specification - -#------------------------------------------------------------------------------ - -__all__ = ['isOleFile', 'OleFileIO', 'OleMetadata', 'enable_logging', - 'MAGIC', 'STGTY_EMPTY', - 'STGTY_STREAM', 'STGTY_STORAGE', 'STGTY_ROOT', 'STGTY_PROPERTY', - 'STGTY_LOCKBYTES', 'MINIMAL_OLEFILE_SIZE', 'NOSTREAM'] - -import io -import sys -import struct, array, os.path, datetime, logging - -#=== COMPATIBILITY WORKAROUNDS ================================================ - -#[PL] Define explicitly the public API to avoid private objects in pydoc: -#TODO: add more -# __all__ = ['OleFileIO', 'isOleFile', 'MAGIC'] - -# For Python 3.x, need to redefine long as int: -if str is not bytes: - long = int - -# Need to make sure we use xrange both on Python 2 and 3.x: -try: - # on Python 2 we need xrange: - iterrange = xrange -except: - # no xrange, for Python 3 it was renamed as range: - iterrange = range - -#[PL] workaround to fix an issue with array item size on 64 bits systems: -if array.array('L').itemsize == 4: - # on 32 bits platforms, long integers in an array are 32 bits: - UINT32 = 'L' -elif array.array('I').itemsize == 4: - # on 64 bits platforms, integers in an array are 32 bits: - UINT32 = 'I' -elif array.array('i').itemsize == 4: - # On 64 bit Jython, signed integers ('i') are the only way to store our 32 - # bit values in an array in a *somewhat* reasonable way, as the otherwise - # perfectly suited 'H' (unsigned int, 32 bits) results in a completely - # unusable behaviour. This is most likely caused by the fact that Java - # doesn't have unsigned values, and thus Jython's "array" implementation, - # which is based on "jarray", doesn't have them either. - # NOTE: to trick Jython into converting the values it would normally - # interpret as "signed" into "unsigned", a binary-and operation with - # 0xFFFFFFFF can be used. This way it is possible to use the same comparing - # operations on all platforms / implementations. The corresponding code - # lines are flagged with a 'JYTHON-WORKAROUND' tag below. - UINT32 = 'i' -else: - raise ValueError('Need to fix a bug with 32 bit arrays, please contact author...') - - -#[PL] These workarounds were inspired from the Path module -# (see http://www.jorendorff.com/articles/python/path/) -try: - basestring -except NameError: - basestring = str - -#[PL] Experimental setting: if True, OLE filenames will be kept in Unicode -# if False (default PIL behaviour), all filenames are converted to Latin-1. -KEEP_UNICODE_NAMES = True - -if sys.version_info[0] < 3: - # On Python 2.x, the default encoding for path names is UTF-8: - DEFAULT_PATH_ENCODING = 'utf-8' -else: - # On Python 3.x, the default encoding for path names is Unicode (None): - DEFAULT_PATH_ENCODING = None - - -# === LOGGING ================================================================= - -class NullHandler(logging.Handler): - """ - Log Handler without output, to avoid printing messages if logging is not - configured by the main application. - Python 2.7 has logging.NullHandler, but this is necessary for 2.6: - see https://docs.python.org/2.6/library/logging.html#configuring-logging-for-a-library - """ - def emit(self, record): - pass - -def get_logger(name, level=logging.CRITICAL+1): - """ - Create a suitable logger object for this module. - The goal is not to change settings of the root logger, to avoid getting - other modules' logs on the screen. - If a logger exists with same name, reuse it. (Else it would have duplicate - handlers and messages would be doubled.) - The level is set to CRITICAL+1 by default, to avoid any logging. - """ - # First, test if there is already a logger with the same name, else it - # will generate duplicate messages (due to duplicate handlers): - if name in logging.Logger.manager.loggerDict: - #NOTE: another less intrusive but more "hackish" solution would be to - # use getLogger then test if its effective level is not default. - logger = logging.getLogger(name) - # make sure level is OK: - logger.setLevel(level) - return logger - # get a new logger: - logger = logging.getLogger(name) - # only add a NullHandler for this logger, it is up to the application - # to configure its own logging: - logger.addHandler(NullHandler()) - logger.setLevel(level) - return logger - - -# a global logger object used for debugging: -log = get_logger('olefile') - - -def enable_logging(): - """ - Enable logging for this module (disabled by default). - This will set the module-specific logger level to NOTSET, which - means the main application controls the actual logging level. - """ - log.setLevel(logging.NOTSET) - - -#=== CONSTANTS =============================================================== - -#: magic bytes that should be at the beginning of every OLE file: -MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1' - -#[PL]: added constants for Sector IDs (from AAF specifications) -MAXREGSECT = 0xFFFFFFFA #: (-6) maximum SECT -DIFSECT = 0xFFFFFFFC #: (-4) denotes a DIFAT sector in a FAT -FATSECT = 0xFFFFFFFD #: (-3) denotes a FAT sector in a FAT -ENDOFCHAIN = 0xFFFFFFFE #: (-2) end of a virtual stream chain -FREESECT = 0xFFFFFFFF #: (-1) unallocated sector - -#[PL]: added constants for Directory Entry IDs (from AAF specifications) -MAXREGSID = 0xFFFFFFFA #: (-6) maximum directory entry ID -NOSTREAM = 0xFFFFFFFF #: (-1) unallocated directory entry - -#[PL] object types in storage (from AAF specifications) -STGTY_EMPTY = 0 #: empty directory entry -STGTY_STORAGE = 1 #: element is a storage object -STGTY_STREAM = 2 #: element is a stream object -STGTY_LOCKBYTES = 3 #: element is an ILockBytes object -STGTY_PROPERTY = 4 #: element is an IPropertyStorage object -STGTY_ROOT = 5 #: element is a root storage - -# Unknown size for a stream (used by OleStream): -UNKNOWN_SIZE = 0x7FFFFFFF - -# -# -------------------------------------------------------------------- -# property types - -VT_EMPTY=0; VT_NULL=1; VT_I2=2; VT_I4=3; VT_R4=4; VT_R8=5; VT_CY=6; -VT_DATE=7; VT_BSTR=8; VT_DISPATCH=9; VT_ERROR=10; VT_BOOL=11; -VT_VARIANT=12; VT_UNKNOWN=13; VT_DECIMAL=14; VT_I1=16; VT_UI1=17; -VT_UI2=18; VT_UI4=19; VT_I8=20; VT_UI8=21; VT_INT=22; VT_UINT=23; -VT_VOID=24; VT_HRESULT=25; VT_PTR=26; VT_SAFEARRAY=27; VT_CARRAY=28; -VT_USERDEFINED=29; VT_LPSTR=30; VT_LPWSTR=31; VT_FILETIME=64; -VT_BLOB=65; VT_STREAM=66; VT_STORAGE=67; VT_STREAMED_OBJECT=68; -VT_STORED_OBJECT=69; VT_BLOB_OBJECT=70; VT_CF=71; VT_CLSID=72; -VT_VECTOR=0x1000; - -# map property id to name (for debugging purposes) - -VT = {} -for keyword, var in list(vars().items()): - if keyword[:3] == "VT_": - VT[var] = keyword - -# -# -------------------------------------------------------------------- -# Some common document types (root.clsid fields) - -WORD_CLSID = "00020900-0000-0000-C000-000000000046" -#TODO: check Excel, PPT, ... - -#[PL]: Defect levels to classify parsing errors - see OleFileIO._raise_defect() -DEFECT_UNSURE = 10 # a case which looks weird, but not sure it's a defect -DEFECT_POTENTIAL = 20 # a potential defect -DEFECT_INCORRECT = 30 # an error according to specifications, but parsing - # can go on -DEFECT_FATAL = 40 # an error which cannot be ignored, parsing is - # impossible - -# Minimal size of an empty OLE file, with 512-bytes sectors = 1536 bytes -# (this is used in isOleFile and OleFile.open) -MINIMAL_OLEFILE_SIZE = 1536 - -#[PL] add useful constants to __all__: -# for key in list(vars().keys()): -# if key.startswith('STGTY_') or key.startswith('DEFECT_'): -# __all__.append(key) - - -#=== FUNCTIONS =============================================================== - -def isOleFile (filename): - """ - Test if a file is an OLE container (according to the magic bytes in its header). - - .. note:: - This function only checks the first 8 bytes of the file, not the - rest of the OLE structure. - - .. versionadded:: 0.16 - - :param filename: filename, contents or file-like object of the OLE file (string-like or file-like object) - - - if filename is a string smaller than 1536 bytes, it is the path - of the file to open. (bytes or unicode string) - - if filename is a string longer than 1535 bytes, it is parsed - as the content of an OLE file in memory. (bytes type only) - - if filename is a file-like object (with read and seek methods), - it is parsed as-is. - - :type filename: bytes or str or unicode or file - :returns: True if OLE, False otherwise. - :rtype: bool - """ - # check if filename is a string-like or file-like object: - if hasattr(filename, 'read'): - # file-like object: use it directly - header = filename.read(len(MAGIC)) - # just in case, seek back to start of file: - filename.seek(0) - elif isinstance(filename, bytes) and len(filename) >= MINIMAL_OLEFILE_SIZE: - # filename is a bytes string containing the OLE file to be parsed: - header = filename[:len(MAGIC)] - else: - # string-like object: filename of file on disk - with open(filename, 'rb') as fp: - header = fp.read(len(MAGIC)) - if header == MAGIC: - return True - else: - return False - - -if bytes is str: - # version for Python 2.x - def i8(c): - return ord(c) -else: - # version for Python 3.x - def i8(c): - return c if c.__class__ is int else c[0] - - -def i16(c, o = 0): - """ - Converts a 2-bytes (16 bits) string to an integer. - - :param c: string containing bytes to convert - :param o: offset of bytes to convert in string - """ - return struct.unpack(" len(fat): - self.ole._raise_defect(DEFECT_INCORRECT, 'malformed OLE document, stream too large') - # optimization(?): data is first a list of strings, and join() is called - # at the end to concatenate all in one string. - # (this may not be really useful with recent Python versions) - data = [] - # if size is zero, then first sector index should be ENDOFCHAIN: - if size == 0 and sect != ENDOFCHAIN: - log.debug('size == 0 and sect != ENDOFCHAIN:') - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE sector index for empty stream') - #[PL] A fixed-length for loop is used instead of an undefined while - # loop to avoid DoS attacks: - for i in range(nb_sectors): - log.debug('Reading stream sector[%d] = %Xh' % (i, sect)) - # Sector index may be ENDOFCHAIN, but only if size was unknown - if sect == ENDOFCHAIN: - if unknown_size: - log.debug('Reached ENDOFCHAIN sector for stream with unknown size') - break - else: - # else this means that the stream is smaller than declared: - log.debug('sect=ENDOFCHAIN before expected size') - self.ole._raise_defect(DEFECT_INCORRECT, 'incomplete OLE stream') - # sector index should be within FAT: - if sect<0 or sect>=len(fat): - log.debug('sect=%d (%X) / len(fat)=%d' % (sect, sect, len(fat))) - log.debug('i=%d / nb_sectors=%d' %(i, nb_sectors)) -## tmp_data = b"".join(data) -## f = open('test_debug.bin', 'wb') -## f.write(tmp_data) -## f.close() -## log.debug('data read so far: %d bytes' % len(tmp_data)) - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE FAT, sector index out of range') - # stop reading here if the exception is ignored: - break - #TODO: merge this code with OleFileIO.getsect() ? - #TODO: check if this works with 4K sectors: - try: - fp.seek(offset + sectorsize * sect) - except: - log.debug('sect=%d, seek=%d, filesize=%d' % - (sect, offset+sectorsize*sect, filesize)) - self.ole._raise_defect(DEFECT_INCORRECT, 'OLE sector index out of range') - # stop reading here if the exception is ignored: - break - sector_data = fp.read(sectorsize) - # [PL] check if there was enough data: - # Note: if sector is the last of the file, sometimes it is not a - # complete sector (of 512 or 4K), so we may read less than - # sectorsize. - if len(sector_data)!=sectorsize and sect!=(len(fat)-1): - log.debug('sect=%d / len(fat)=%d, seek=%d / filesize=%d, len read=%d' % - (sect, len(fat), offset+sectorsize*sect, filesize, len(sector_data))) - log.debug('seek+len(read)=%d' % (offset+sectorsize*sect+len(sector_data))) - self.ole._raise_defect(DEFECT_INCORRECT, 'incomplete OLE sector') - data.append(sector_data) - # jump to next sector in the FAT: - try: - sect = fat[sect] & 0xFFFFFFFF # JYTHON-WORKAROUND - except IndexError: - # [PL] if pointer is out of the FAT an exception is raised - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE FAT, sector index out of range') - # stop reading here if the exception is ignored: - break - #[PL] Last sector should be a "end of chain" marker: - # if sect != ENDOFCHAIN: - # raise IOError('incorrect last sector index in OLE stream') - data = b"".join(data) - # Data is truncated to the actual stream size: - if len(data) >= size: - log.debug('Read data of length %d, truncated to stream size %d' % (len(data), size)) - data = data[:size] - # actual stream size is stored for future use: - self.size = size - elif unknown_size: - # actual stream size was not known, now we know the size of read - # data: - log.debug('Read data of length %d, the stream size was unknown' % len(data)) - self.size = len(data) - else: - # read data is less than expected: - log.debug('Read data of length %d, less than expected stream size %d' % (len(data), size)) - # TODO: provide details in exception message - self.size = len(data) - self.ole._raise_defect(DEFECT_INCORRECT, 'OLE stream size is less than declared') - # when all data is read in memory, BytesIO constructor is called - io.BytesIO.__init__(self, data) - # Then the OleStream object can be used as a read-only file object. - - -#--- OleDirectoryEntry ------------------------------------------------------- - -class OleDirectoryEntry: - - """ - OLE2 Directory Entry - """ - #[PL] parsing code moved from OleFileIO.loaddirectory - - # struct to parse directory entries: - # <: little-endian byte order, standard sizes - # (note: this should guarantee that Q returns a 64 bits int) - # 64s: string containing entry name in unicode UTF-16 (max 31 chars) + null char = 64 bytes - # H: uint16, number of bytes used in name buffer, including null = (len+1)*2 - # B: uint8, dir entry type (between 0 and 5) - # B: uint8, color: 0=black, 1=red - # I: uint32, index of left child node in the red-black tree, NOSTREAM if none - # I: uint32, index of right child node in the red-black tree, NOSTREAM if none - # I: uint32, index of child root node if it is a storage, else NOSTREAM - # 16s: CLSID, unique identifier (only used if it is a storage) - # I: uint32, user flags - # Q (was 8s): uint64, creation timestamp or zero - # Q (was 8s): uint64, modification timestamp or zero - # I: uint32, SID of first sector if stream or ministream, SID of 1st sector - # of stream containing ministreams if root entry, 0 otherwise - # I: uint32, total stream size in bytes if stream (low 32 bits), 0 otherwise - # I: uint32, total stream size in bytes if stream (high 32 bits), 0 otherwise - STRUCT_DIRENTRY = '<64sHBBIII16sIQQIII' - # size of a directory entry: 128 bytes - DIRENTRY_SIZE = 128 - assert struct.calcsize(STRUCT_DIRENTRY) == DIRENTRY_SIZE - - - def __init__(self, entry, sid, olefile): - """ - Constructor for an OleDirectoryEntry object. - Parses a 128-bytes entry from the OLE Directory stream. - - :param entry : string (must be 128 bytes long) - :param sid : index of this directory entry in the OLE file directory - :param olefile: OleFileIO containing this directory entry - """ - self.sid = sid - # ref to olefile is stored for future use - self.olefile = olefile - # kids is a list of children entries, if this entry is a storage: - # (list of OleDirectoryEntry objects) - self.kids = [] - # kids_dict is a dictionary of children entries, indexed by their - # name in lowercase: used to quickly find an entry, and to detect - # duplicates - self.kids_dict = {} - # flag used to detect if the entry is referenced more than once in - # directory: - self.used = False - # decode DirEntry - ( - self.name_raw, # 64s: string containing entry name in unicode UTF-16 (max 31 chars) + null char = 64 bytes - self.namelength, # H: uint16, number of bytes used in name buffer, including null = (len+1)*2 - self.entry_type, - self.color, - self.sid_left, - self.sid_right, - self.sid_child, - clsid, - self.dwUserFlags, - self.createTime, - self.modifyTime, - self.isectStart, - self.sizeLow, - self.sizeHigh - ) = struct.unpack(OleDirectoryEntry.STRUCT_DIRENTRY, entry) - if self.entry_type not in [STGTY_ROOT, STGTY_STORAGE, STGTY_STREAM, STGTY_EMPTY]: - olefile._raise_defect(DEFECT_INCORRECT, 'unhandled OLE storage type') - # only first directory entry can (and should) be root: - if self.entry_type == STGTY_ROOT and sid != 0: - olefile._raise_defect(DEFECT_INCORRECT, 'duplicate OLE root entry') - if sid == 0 and self.entry_type != STGTY_ROOT: - olefile._raise_defect(DEFECT_INCORRECT, 'incorrect OLE root entry') - #log.debug(struct.unpack(fmt_entry, entry[:len_entry])) - # name should be at most 31 unicode characters + null character, - # so 64 bytes in total (31*2 + 2): - if self.namelength>64: - olefile._raise_defect(DEFECT_INCORRECT, 'incorrect DirEntry name length >64 bytes') - # if exception not raised, namelength is set to the maximum value: - self.namelength = 64 - # only characters without ending null char are kept: - self.name_utf16 = self.name_raw[:(self.namelength-2)] - #TODO: check if the name is actually followed by a null unicode character ([MS-CFB] 2.6.1) - #TODO: check if the name does not contain forbidden characters: - # [MS-CFB] 2.6.1: "The following characters are illegal and MUST NOT be part of the name: '/', '\', ':', '!'." - # name is converted from UTF-16LE to the path encoding specified in the OleFileIO: - self.name = olefile._decode_utf16_str(self.name_utf16) - - log.debug('DirEntry SID=%d: %s' % (self.sid, repr(self.name))) - log.debug(' - type: %d' % self.entry_type) - log.debug(' - sect: %Xh' % self.isectStart) - log.debug(' - SID left: %d, right: %d, child: %d' % (self.sid_left, - self.sid_right, self.sid_child)) - - # sizeHigh is only used for 4K sectors, it should be zero for 512 bytes - # sectors, BUT apparently some implementations set it as 0xFFFFFFFF, 1 - # or some other value so it cannot be raised as a defect in general: - if olefile.sectorsize == 512: - if self.sizeHigh != 0 and self.sizeHigh != 0xFFFFFFFF: - log.debug('sectorsize=%d, sizeLow=%d, sizeHigh=%d (%X)' % - (olefile.sectorsize, self.sizeLow, self.sizeHigh, self.sizeHigh)) - olefile._raise_defect(DEFECT_UNSURE, 'incorrect OLE stream size') - self.size = self.sizeLow - else: - self.size = self.sizeLow + (long(self.sizeHigh)<<32) - log.debug(' - size: %d (sizeLow=%d, sizeHigh=%d)' % (self.size, self.sizeLow, self.sizeHigh)) - - self.clsid = _clsid(clsid) - # a storage should have a null size, BUT some implementations such as - # Word 8 for Mac seem to allow non-null values => Potential defect: - if self.entry_type == STGTY_STORAGE and self.size != 0: - olefile._raise_defect(DEFECT_POTENTIAL, 'OLE storage with size>0') - # check if stream is not already referenced elsewhere: - if self.entry_type in (STGTY_ROOT, STGTY_STREAM) and self.size>0: - if self.size < olefile.minisectorcutoff \ - and self.entry_type==STGTY_STREAM: # only streams can be in MiniFAT - # ministream object - minifat = True - else: - minifat = False - olefile._check_duplicate_stream(self.isectStart, minifat) - - - - def build_storage_tree(self): - """ - Read and build the red-black tree attached to this OleDirectoryEntry - object, if it is a storage. - Note that this method builds a tree of all subentries, so it should - only be called for the root object once. - """ - log.debug('build_storage_tree: SID=%d - %s - sid_child=%d' - % (self.sid, repr(self.name), self.sid_child)) - if self.sid_child != NOSTREAM: - # if child SID is not NOSTREAM, then this entry is a storage. - # Let's walk through the tree of children to fill the kids list: - self.append_kids(self.sid_child) - - # Note from OpenOffice documentation: the safest way is to - # recreate the tree because some implementations may store broken - # red-black trees... - - # in the OLE file, entries are sorted on (length, name). - # for convenience, we sort them on name instead: - # (see rich comparison methods in this class) - self.kids.sort() - - - def append_kids(self, child_sid): - """ - Walk through red-black tree of children of this directory entry to add - all of them to the kids list. (recursive method) - - :param child_sid: index of child directory entry to use, or None when called - first time for the root. (only used during recursion) - """ - log.debug('append_kids: child_sid=%d' % child_sid) - #[PL] this method was added to use simple recursion instead of a complex - # algorithm. - # if this is not a storage or a leaf of the tree, nothing to do: - if child_sid == NOSTREAM: - return - # check if child SID is in the proper range: - if child_sid<0 or child_sid>=len(self.olefile.direntries): - self.olefile._raise_defect(DEFECT_INCORRECT, 'OLE DirEntry index out of range') - else: - # get child direntry: - child = self.olefile._load_direntry(child_sid) #direntries[child_sid] - log.debug('append_kids: child_sid=%d - %s - sid_left=%d, sid_right=%d, sid_child=%d' - % (child.sid, repr(child.name), child.sid_left, child.sid_right, child.sid_child)) - # the directory entries are organized as a red-black tree. - # (cf. Wikipedia for details) - # First walk through left side of the tree: - self.append_kids(child.sid_left) - # Check if its name is not already used (case-insensitive): - name_lower = child.name.lower() - if name_lower in self.kids_dict: - self.olefile._raise_defect(DEFECT_INCORRECT, - "Duplicate filename in OLE storage") - # Then the child_sid OleDirectoryEntry object is appended to the - # kids list and dictionary: - self.kids.append(child) - self.kids_dict[name_lower] = child - # Check if kid was not already referenced in a storage: - if child.used: - self.olefile._raise_defect(DEFECT_INCORRECT, - 'OLE Entry referenced more than once') - child.used = True - # Finally walk through right side of the tree: - self.append_kids(child.sid_right) - # Afterwards build kid's own tree if it's also a storage: - child.build_storage_tree() - - - def __eq__(self, other): - "Compare entries by name" - return self.name == other.name - - def __lt__(self, other): - "Compare entries by name" - return self.name < other.name - - def __ne__(self, other): - return not self.__eq__(other) - - def __le__(self, other): - return self.__eq__(other) or self.__lt__(other) - - # Reflected __lt__() and __le__() will be used for __gt__() and __ge__() - - #TODO: replace by the same function as MS implementation ? - # (order by name length first, then case-insensitive order) - - - def dump(self, tab = 0): - "Dump this entry, and all its subentries (for debug purposes only)" - TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)", - "(property)", "(root)"] - print(" "*tab + repr(self.name), TYPES[self.entry_type], end=' ') - if self.entry_type in (STGTY_STREAM, STGTY_ROOT): - print(self.size, "bytes", end=' ') - print() - if self.entry_type in (STGTY_STORAGE, STGTY_ROOT) and self.clsid: - print(" "*tab + "{%s}" % self.clsid) - - for kid in self.kids: - kid.dump(tab + 2) - - - def getmtime(self): - """ - Return modification time of a directory entry. - - :returns: None if modification time is null, a python datetime object - otherwise (UTC timezone) - - new in version 0.26 - """ - if self.modifyTime == 0: - return None - return filetime2datetime(self.modifyTime) - - - def getctime(self): - """ - Return creation time of a directory entry. - - :returns: None if modification time is null, a python datetime object - otherwise (UTC timezone) - - new in version 0.26 - """ - if self.createTime == 0: - return None - return filetime2datetime(self.createTime) - - -#--- OleFileIO ---------------------------------------------------------------- - -class OleFileIO: - """ - OLE container object - - This class encapsulates the interface to an OLE 2 structured - storage file. Use the listdir and openstream methods to - access the contents of this file. - - Object names are given as a list of strings, one for each subentry - level. The root entry should be omitted. For example, the following - code extracts all image streams from a Microsoft Image Composer file:: - - ole = OleFileIO("fan.mic") - - for entry in ole.listdir(): - if entry[1:2] == "Image": - fin = ole.openstream(entry) - fout = open(entry[0:1], "wb") - while True: - s = fin.read(8192) - if not s: - break - fout.write(s) - - You can use the viewer application provided with the Python Imaging - Library to view the resulting files (which happens to be standard - TIFF files). - """ - - def __init__(self, filename=None, raise_defects=DEFECT_FATAL, - write_mode=False, debug=False, path_encoding=DEFAULT_PATH_ENCODING): - """ - Constructor for the OleFileIO class. - - :param filename: file to open. - - - if filename is a string smaller than 1536 bytes, it is the path - of the file to open. (bytes or unicode string) - - if filename is a string longer than 1535 bytes, it is parsed - as the content of an OLE file in memory. (bytes type only) - - if filename is a file-like object (with read, seek and tell methods), - it is parsed as-is. - - :param raise_defects: minimal level for defects to be raised as exceptions. - (use DEFECT_FATAL for a typical application, DEFECT_INCORRECT for a - security-oriented application, see source code for details) - - :param write_mode: bool, if True the file is opened in read/write mode instead - of read-only by default. - - :param debug: bool, set debug mode (deprecated, not used anymore) - - :param path_encoding: None or str, name of the codec to use for path - names (streams and storages), or None for Unicode. - Unicode by default on Python 3+, UTF-8 on Python 2.x. - (new in olefile 0.42, was hardcoded to Latin-1 until olefile v0.41) - """ - # minimal level for defects to be raised as exceptions: - self._raise_defects_level = raise_defects - #: list of defects/issues not raised as exceptions: - #: tuples of (exception type, message) - self.parsing_issues = [] - self.write_mode = write_mode - self.path_encoding = path_encoding - self._filesize = None - self.fp = None - if filename: - self.open(filename, write_mode=write_mode) - - - def _raise_defect(self, defect_level, message, exception_type=IOError): - """ - This method should be called for any defect found during file parsing. - It may raise an IOError exception according to the minimal level chosen - for the OleFileIO object. - - :param defect_level: defect level, possible values are: - - - DEFECT_UNSURE : a case which looks weird, but not sure it's a defect - - DEFECT_POTENTIAL : a potential defect - - DEFECT_INCORRECT : an error according to specifications, but parsing can go on - - DEFECT_FATAL : an error which cannot be ignored, parsing is impossible - - :param message: string describing the defect, used with raised exception. - :param exception_type: exception class to be raised, IOError by default - """ - # added by [PL] - if defect_level >= self._raise_defects_level: - log.error(message) - raise exception_type(message) - else: - # just record the issue, no exception raised: - self.parsing_issues.append((exception_type, message)) - log.warning(message) - - - def _decode_utf16_str(self, utf16_str, errors='replace'): - """ - Decode a string encoded in UTF-16 LE format, as found in the OLE - directory or in property streams. Return a string encoded - according to the path_encoding specified for the OleFileIO object. - - :param utf16_str: bytes string encoded in UTF-16 LE format - :param errors: str, see python documentation for str.decode() - :return: str, encoded according to path_encoding - """ - unicode_str = utf16_str.decode('UTF-16LE', errors) - if self.path_encoding: - # an encoding has been specified for path names: - return unicode_str.encode(self.path_encoding, errors) - else: - # path_encoding=None, return the Unicode string as-is: - return unicode_str - - - def open(self, filename, write_mode=False): - """ - Open an OLE2 file in read-only or read/write mode. - Read and parse the header, FAT and directory. - - :param filename: string-like or file-like object, OLE file to parse - - - if filename is a string smaller than 1536 bytes, it is the path - of the file to open. (bytes or unicode string) - - if filename is a string longer than 1535 bytes, it is parsed - as the content of an OLE file in memory. (bytes type only) - - if filename is a file-like object (with read, seek and tell methods), - it is parsed as-is. - - :param write_mode: bool, if True the file is opened in read/write mode instead - of read-only by default. (ignored if filename is not a path) - """ - self.write_mode = write_mode - #[PL] check if filename is a string-like or file-like object: - # (it is better to check for a read() method) - if hasattr(filename, 'read'): - #TODO: also check seek and tell methods? - # file-like object: use it directly - self.fp = filename - elif isinstance(filename, bytes) and len(filename) >= MINIMAL_OLEFILE_SIZE: - # filename is a bytes string containing the OLE file to be parsed: - # convert it to BytesIO - self.fp = io.BytesIO(filename) - else: - # string-like object: filename of file on disk - if self.write_mode: - # open file in mode 'read with update, binary' - # According to https://docs.python.org/2/library/functions.html#open - # 'w' would truncate the file, 'a' may only append on some Unixes - mode = 'r+b' - else: - # read-only mode by default - mode = 'rb' - self.fp = open(filename, mode) - # obtain the filesize by using seek and tell, which should work on most - # file-like objects: - #TODO: do it above, using getsize with filename when possible? - #TODO: fix code to fail with clear exception when filesize cannot be obtained - filesize=0 - self.fp.seek(0, os.SEEK_END) - try: - filesize = self.fp.tell() - finally: - self.fp.seek(0) - self._filesize = filesize - log.debug('File size: %d bytes (%Xh)' % (self._filesize, self._filesize)) - - # lists of streams in FAT and MiniFAT, to detect duplicate references - # (list of indexes of first sectors of each stream) - self._used_streams_fat = [] - self._used_streams_minifat = [] - - header = self.fp.read(512) - - if len(header) != 512 or header[:8] != MAGIC: - log.debug('Magic = %r instead of %r' % (header[:8], MAGIC)) - self._raise_defect(DEFECT_FATAL, "not an OLE2 structured storage file") - - # [PL] header structure according to AAF specifications: - ##Header - ##struct StructuredStorageHeader { // [offset from start (bytes), length (bytes)] - ##BYTE _abSig[8]; // [00H,08] {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, - ## // 0x1a, 0xe1} for current version - ##CLSID _clsid; // [08H,16] reserved must be zero (WriteClassStg/ - ## // GetClassFile uses root directory class id) - ##USHORT _uMinorVersion; // [18H,02] minor version of the format: 33 is - ## // written by reference implementation - ##USHORT _uDllVersion; // [1AH,02] major version of the dll/format: 3 for - ## // 512-byte sectors, 4 for 4 KB sectors - ##USHORT _uByteOrder; // [1CH,02] 0xFFFE: indicates Intel byte-ordering - ##USHORT _uSectorShift; // [1EH,02] size of sectors in power-of-two; - ## // typically 9 indicating 512-byte sectors - ##USHORT _uMiniSectorShift; // [20H,02] size of mini-sectors in power-of-two; - ## // typically 6 indicating 64-byte mini-sectors - ##USHORT _usReserved; // [22H,02] reserved, must be zero - ##ULONG _ulReserved1; // [24H,04] reserved, must be zero - ##FSINDEX _csectDir; // [28H,04] must be zero for 512-byte sectors, - ## // number of SECTs in directory chain for 4 KB - ## // sectors - ##FSINDEX _csectFat; // [2CH,04] number of SECTs in the FAT chain - ##SECT _sectDirStart; // [30H,04] first SECT in the directory chain - ##DFSIGNATURE _signature; // [34H,04] signature used for transactions; must - ## // be zero. The reference implementation - ## // does not support transactions - ##ULONG _ulMiniSectorCutoff; // [38H,04] maximum size for a mini stream; - ## // typically 4096 bytes - ##SECT _sectMiniFatStart; // [3CH,04] first SECT in the MiniFAT chain - ##FSINDEX _csectMiniFat; // [40H,04] number of SECTs in the MiniFAT chain - ##SECT _sectDifStart; // [44H,04] first SECT in the DIFAT chain - ##FSINDEX _csectDif; // [48H,04] number of SECTs in the DIFAT chain - ##SECT _sectFat[109]; // [4CH,436] the SECTs of first 109 FAT sectors - ##}; - - # [PL] header decoding: - # '<' indicates little-endian byte ordering for Intel (cf. struct module help) - fmt_header = '<8s16sHHHHHHLLLLLLLLLL' - header_size = struct.calcsize(fmt_header) - log.debug( "fmt_header size = %d, +FAT = %d" % (header_size, header_size + 109*4) ) - header1 = header[:header_size] - ( - self.header_signature, - self.header_clsid, - self.minor_version, - self.dll_version, - self.byte_order, - self.sector_shift, - self.mini_sector_shift, - self.reserved1, - self.reserved2, - self.num_dir_sectors, - self.num_fat_sectors, - self.first_dir_sector, - self.transaction_signature_number, - self.mini_stream_cutoff_size, - self.first_mini_fat_sector, - self.num_mini_fat_sectors, - self.first_difat_sector, - self.num_difat_sectors - ) = struct.unpack(fmt_header, header1) - log.debug( struct.unpack(fmt_header, header1)) - - if self.header_signature != MAGIC: - # OLE signature should always be present - self._raise_defect(DEFECT_FATAL, "incorrect OLE signature") - if self.header_clsid != bytearray(16): - # according to AAF specs, CLSID should always be zero - self._raise_defect(DEFECT_INCORRECT, "incorrect CLSID in OLE header") - log.debug( "Minor Version = %d" % self.minor_version ) - # TODO: according to MS-CFB, minor version should be 0x003E - log.debug( "DLL Version = %d (expected: 3 or 4)" % self.dll_version ) - if self.dll_version not in [3, 4]: - # version 3: usual format, 512 bytes per sector - # version 4: large format, 4K per sector - self._raise_defect(DEFECT_INCORRECT, "incorrect DllVersion in OLE header") - log.debug( "Byte Order = %X (expected: FFFE)" % self.byte_order ) - if self.byte_order != 0xFFFE: - # For now only common little-endian documents are handled correctly - self._raise_defect(DEFECT_INCORRECT, "incorrect ByteOrder in OLE header") - # TODO: add big-endian support for documents created on Mac ? - # But according to [MS-CFB] ? v20140502, ByteOrder MUST be 0xFFFE. - self.sector_size = 2**self.sector_shift - log.debug( "Sector Size = %d bytes (expected: 512 or 4096)" % self.sector_size ) - if self.sector_size not in [512, 4096]: - self._raise_defect(DEFECT_INCORRECT, "incorrect sector_size in OLE header") - if (self.dll_version==3 and self.sector_size!=512) \ - or (self.dll_version==4 and self.sector_size!=4096): - self._raise_defect(DEFECT_INCORRECT, "sector_size does not match DllVersion in OLE header") - self.mini_sector_size = 2**self.mini_sector_shift - log.debug( "MiniFAT Sector Size = %d bytes (expected: 64)" % self.mini_sector_size ) - if self.mini_sector_size not in [64]: - self._raise_defect(DEFECT_INCORRECT, "incorrect mini_sector_size in OLE header") - if self.reserved1 != 0 or self.reserved2 != 0: - self._raise_defect(DEFECT_INCORRECT, "incorrect OLE header (non-null reserved bytes)") - log.debug( "Number of Directory sectors = %d" % self.num_dir_sectors ) - # Number of directory sectors (only allowed if DllVersion != 3) - if self.sector_size==512 and self.num_dir_sectors!=0: - self._raise_defect(DEFECT_INCORRECT, "incorrect number of directory sectors in OLE header") - log.debug( "Number of FAT sectors = %d" % self.num_fat_sectors ) - # num_fat_sectors = number of FAT sectors in the file - log.debug( "First Directory sector = %Xh" % self.first_dir_sector ) - # first_dir_sector = 1st sector containing the directory - log.debug( "Transaction Signature Number = %d" % self.transaction_signature_number ) - # Signature should be zero, BUT some implementations do not follow this - # rule => only a potential defect: - # (according to MS-CFB, may be != 0 for applications supporting file - # transactions) - if self.transaction_signature_number != 0: - self._raise_defect(DEFECT_POTENTIAL, "incorrect OLE header (transaction_signature_number>0)") - log.debug( "Mini Stream cutoff size = %Xh (expected: 1000h)" % self.mini_stream_cutoff_size ) - # MS-CFB: This integer field MUST be set to 0x00001000. This field - # specifies the maximum size of a user-defined data stream allocated - # from the mini FAT and mini stream, and that cutoff is 4096 bytes. - # Any user-defined data stream larger than or equal to this cutoff size - # must be allocated as normal sectors from the FAT. - if self.mini_stream_cutoff_size != 0x1000: - self._raise_defect(DEFECT_INCORRECT, "incorrect mini_stream_cutoff_size in OLE header") - # if no exception is raised, the cutoff size is fixed to 0x1000 - log.warning('Fixing the mini_stream_cutoff_size to 4096 (mandatory value) instead of %d' % - self.mini_stream_cutoff_size) - self.mini_stream_cutoff_size = 0x1000 - # TODO: check if these values are OK - log.debug( "First MiniFAT sector = %Xh" % self.first_mini_fat_sector ) - log.debug( "Number of MiniFAT sectors = %d" % self.num_mini_fat_sectors ) - log.debug( "First DIFAT sector = %Xh" % self.first_difat_sector ) - log.debug( "Number of DIFAT sectors = %d" % self.num_difat_sectors ) - - # calculate the number of sectors in the file - # (-1 because header doesn't count) - self.nb_sect = ( (filesize + self.sector_size-1) // self.sector_size) - 1 - log.debug( "Maximum number of sectors in the file: %d (%Xh)" % (self.nb_sect, self.nb_sect)) - #TODO: change this test, because an OLE file MAY contain other data - # after the last sector. - - # file clsid - self.header_clsid = _clsid(header[8:24]) - - #TODO: remove redundant attributes, and fix the code which uses them? - self.sectorsize = self.sector_size #1 << i16(header, 30) - self.minisectorsize = self.mini_sector_size #1 << i16(header, 32) - self.minisectorcutoff = self.mini_stream_cutoff_size # i32(header, 56) - - # check known streams for duplicate references (these are always in FAT, - # never in MiniFAT): - self._check_duplicate_stream(self.first_dir_sector) - # check MiniFAT only if it is not empty: - if self.num_mini_fat_sectors: - self._check_duplicate_stream(self.first_mini_fat_sector) - # check DIFAT only if it is not empty: - if self.num_difat_sectors: - self._check_duplicate_stream(self.first_difat_sector) - - # Load file allocation tables - self.loadfat(header) - # Load directory. This sets both the direntries list (ordered by sid) - # and the root (ordered by hierarchy) members. - self.loaddirectory(self.first_dir_sector) - self.ministream = None - self.minifatsect = self.first_mini_fat_sector - - - def close(self): - """ - close the OLE file, to release the file object - """ - self.fp.close() - - - def _check_duplicate_stream(self, first_sect, minifat=False): - """ - Checks if a stream has not been already referenced elsewhere. - This method should only be called once for each known stream, and only - if stream size is not null. - - :param first_sect: int, index of first sector of the stream in FAT - :param minifat: bool, if True, stream is located in the MiniFAT, else in the FAT - """ - if minifat: - log.debug('_check_duplicate_stream: sect=%Xh in MiniFAT' % first_sect) - used_streams = self._used_streams_minifat - else: - log.debug('_check_duplicate_stream: sect=%Xh in FAT' % first_sect) - # some values can be safely ignored (not a real stream): - if first_sect in (DIFSECT,FATSECT,ENDOFCHAIN,FREESECT): - return - used_streams = self._used_streams_fat - #TODO: would it be more efficient using a dict or hash values, instead - # of a list of long ? - if first_sect in used_streams: - self._raise_defect(DEFECT_INCORRECT, 'Stream referenced twice') - else: - used_streams.append(first_sect) - - - def dumpfat(self, fat, firstindex=0): - """ - Display a part of FAT in human-readable form for debugging purposes - """ - # dictionary to convert special FAT values in human-readable strings - VPL = 8 # values per line (8+1 * 8+1 = 81) - fatnames = { - FREESECT: "..free..", - ENDOFCHAIN: "[ END. ]", - FATSECT: "FATSECT ", - DIFSECT: "DIFSECT " - } - nbsect = len(fat) - nlines = (nbsect+VPL-1)//VPL - print("index", end=" ") - for i in range(VPL): - print("%8X" % i, end=" ") - print() - for l in range(nlines): - index = l*VPL - print("%6X:" % (firstindex+index), end=" ") - for i in range(index, index+VPL): - if i>=nbsect: - break - sect = fat[i] - aux = sect & 0xFFFFFFFF # JYTHON-WORKAROUND - if aux in fatnames: - name = fatnames[aux] - else: - if sect == i+1: - name = " --->" - else: - name = "%8X" % sect - print(name, end=" ") - print() - - - def dumpsect(self, sector, firstindex=0): - """ - Display a sector in a human-readable form, for debugging purposes - """ - VPL=8 # number of values per line (8+1 * 8+1 = 81) - tab = array.array(UINT32, sector) - if sys.byteorder == 'big': - tab.byteswap() - nbsect = len(tab) - nlines = (nbsect+VPL-1)//VPL - print("index", end=" ") - for i in range(VPL): - print("%8X" % i, end=" ") - print() - for l in range(nlines): - index = l*VPL - print("%6X:" % (firstindex+index), end=" ") - for i in range(index, index+VPL): - if i>=nbsect: - break - sect = tab[i] - name = "%8X" % sect - print(name, end=" ") - print() - - def sect2array(self, sect): - """ - convert a sector to an array of 32 bits unsigned integers, - swapping bytes on big endian CPUs such as PowerPC (old Macs) - """ - a = array.array(UINT32, sect) - # if CPU is big endian, swap bytes: - if sys.byteorder == 'big': - a.byteswap() - return a - - - def loadfat_sect(self, sect): - """ - Adds the indexes of the given sector to the FAT - - :param sect: string containing the first FAT sector, or array of long integers - :returns: index of last FAT sector. - """ - # a FAT sector is an array of ulong integers. - if isinstance(sect, array.array): - # if sect is already an array it is directly used - fat1 = sect - else: - # if it's a raw sector, it is parsed in an array - fat1 = self.sect2array(sect) - # Display the sector contents only if the logging level is debug: - if log.isEnabledFor(logging.DEBUG): - self.dumpsect(sect) - # The FAT is a sector chain starting at the first index of itself. - # initialize isect, just in case: - isect = None - for isect in fat1: - isect = isect & 0xFFFFFFFF # JYTHON-WORKAROUND - log.debug("isect = %X" % isect) - if isect == ENDOFCHAIN or isect == FREESECT: - # the end of the sector chain has been reached - log.debug("found end of sector chain") - break - # read the FAT sector - s = self.getsect(isect) - # parse it as an array of 32 bits integers, and add it to the - # global FAT array - nextfat = self.sect2array(s) - self.fat = self.fat + nextfat - return isect - - - def loadfat(self, header): - """ - Load the FAT table. - """ - # The 1st sector of the file contains sector numbers for the first 109 - # FAT sectors, right after the header which is 76 bytes long. - # (always 109, whatever the sector size: 512 bytes = 76+4*109) - # Additional sectors are described by DIF blocks - - log.debug('Loading the FAT table, starting with the 1st sector after the header') - sect = header[76:512] - log.debug( "len(sect)=%d, so %d integers" % (len(sect), len(sect)//4) ) - #fat = [] - # [PL] FAT is an array of 32 bits unsigned ints, it's more effective - # to use an array than a list in Python. - # It's initialized as empty first: - self.fat = array.array(UINT32) - self.loadfat_sect(sect) - #self.dumpfat(self.fat) -## for i in range(0, len(sect), 4): -## ix = i32(sect, i) -## #[PL] if ix == -2 or ix == -1: # ix == 0xFFFFFFFE or ix == 0xFFFFFFFF: -## if ix == 0xFFFFFFFE or ix == 0xFFFFFFFF: -## break -## s = self.getsect(ix) -## #fat = fat + [i32(s, i) for i in range(0, len(s), 4)] -## fat = fat + array.array(UINT32, s) - if self.num_difat_sectors != 0: - log.debug('DIFAT is used, because file size > 6.8MB.') - # [PL] There's a DIFAT because file is larger than 6.8MB - # some checks just in case: - if self.num_fat_sectors <= 109: - # there must be at least 109 blocks in header and the rest in - # DIFAT, so number of sectors must be >109. - self._raise_defect(DEFECT_INCORRECT, 'incorrect DIFAT, not enough sectors') - if self.first_difat_sector >= self.nb_sect: - # initial DIFAT block index must be valid - self._raise_defect(DEFECT_FATAL, 'incorrect DIFAT, first index out of range') - log.debug( "DIFAT analysis..." ) - # We compute the necessary number of DIFAT sectors : - # Number of pointers per DIFAT sector = (sectorsize/4)-1 - # (-1 because the last pointer is the next DIFAT sector number) - nb_difat_sectors = (self.sectorsize//4)-1 - # (if 512 bytes: each DIFAT sector = 127 pointers + 1 towards next DIFAT sector) - nb_difat = (self.num_fat_sectors-109 + nb_difat_sectors-1)//nb_difat_sectors - log.debug( "nb_difat = %d" % nb_difat ) - if self.num_difat_sectors != nb_difat: - raise IOError('incorrect DIFAT') - isect_difat = self.first_difat_sector - for i in iterrange(nb_difat): - log.debug( "DIFAT block %d, sector %X" % (i, isect_difat) ) - #TODO: check if corresponding FAT SID = DIFSECT - sector_difat = self.getsect(isect_difat) - difat = self.sect2array(sector_difat) - # Display the sector contents only if the logging level is debug: - if log.isEnabledFor(logging.DEBUG): - self.dumpsect(sector_difat) - self.loadfat_sect(difat[:nb_difat_sectors]) - # last DIFAT pointer is next DIFAT sector: - isect_difat = difat[nb_difat_sectors] - log.debug( "next DIFAT sector: %X" % isect_difat ) - # checks: - if isect_difat not in [ENDOFCHAIN, FREESECT]: - # last DIFAT pointer value must be ENDOFCHAIN or FREESECT - raise IOError('incorrect end of DIFAT') -## if len(self.fat) != self.num_fat_sectors: -## # FAT should contain num_fat_sectors blocks -## print("FAT length: %d instead of %d" % (len(self.fat), self.num_fat_sectors)) -## raise IOError('incorrect DIFAT') - else: - log.debug('No DIFAT, because file size < 6.8MB.') - # since FAT is read from fixed-size sectors, it may contain more values - # than the actual number of sectors in the file. - # Keep only the relevant sector indexes: - if len(self.fat) > self.nb_sect: - log.debug('len(fat)=%d, shrunk to nb_sect=%d' % (len(self.fat), self.nb_sect)) - self.fat = self.fat[:self.nb_sect] - log.debug('FAT references %d sectors / Maximum %d sectors in file' % (len(self.fat), self.nb_sect)) - # Display the FAT contents only if the logging level is debug: - if log.isEnabledFor(logging.DEBUG): - log.debug('\nFAT:') - self.dumpfat(self.fat) - - - def loadminifat(self): - """ - Load the MiniFAT table. - """ - # MiniFAT is stored in a standard sub-stream, pointed to by a header - # field. - # NOTE: there are two sizes to take into account for this stream: - # 1) Stream size is calculated according to the number of sectors - # declared in the OLE header. This allocated stream may be more than - # needed to store the actual sector indexes. - # (self.num_mini_fat_sectors is the number of sectors of size self.sector_size) - stream_size = self.num_mini_fat_sectors * self.sector_size - # 2) Actually used size is calculated by dividing the MiniStream size - # (given by root entry size) by the size of mini sectors, *4 for - # 32 bits indexes: - nb_minisectors = (self.root.size + self.mini_sector_size-1) // self.mini_sector_size - used_size = nb_minisectors * 4 - log.debug('loadminifat(): minifatsect=%d, nb FAT sectors=%d, used_size=%d, stream_size=%d, nb MiniSectors=%d' % - (self.minifatsect, self.num_mini_fat_sectors, used_size, stream_size, nb_minisectors)) - if used_size > stream_size: - # This is not really a problem, but may indicate a wrong implementation: - self._raise_defect(DEFECT_INCORRECT, 'OLE MiniStream is larger than MiniFAT') - # In any case, first read stream_size: - s = self._open(self.minifatsect, stream_size, force_FAT=True).read() - #[PL] Old code replaced by an array: - #self.minifat = [i32(s, i) for i in range(0, len(s), 4)] - self.minifat = self.sect2array(s) - # Then shrink the array to used size, to avoid indexes out of MiniStream: - log.debug('MiniFAT shrunk from %d to %d sectors' % (len(self.minifat), nb_minisectors)) - self.minifat = self.minifat[:nb_minisectors] - log.debug('loadminifat(): len=%d' % len(self.minifat)) - # Display the FAT contents only if the logging level is debug: - if log.isEnabledFor(logging.DEBUG): - log.debug('\nMiniFAT:') - self.dumpfat(self.minifat) - - def getsect(self, sect): - """ - Read given sector from file on disk. - - :param sect: int, sector index - :returns: a string containing the sector data. - """ - # From [MS-CFB]: A sector number can be converted into a byte offset - # into the file by using the following formula: - # (sector number + 1) x Sector Size. - # This implies that sector #0 of the file begins at byte offset Sector - # Size, not at 0. - - # [PL] the original code in PIL was wrong when sectors are 4KB instead of - # 512 bytes: - #self.fp.seek(512 + self.sectorsize * sect) - #[PL]: added safety checks: - #print("getsect(%X)" % sect) - try: - self.fp.seek(self.sectorsize * (sect+1)) - except: - log.debug('getsect(): sect=%X, seek=%d, filesize=%d' % - (sect, self.sectorsize*(sect+1), self._filesize)) - self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range') - sector = self.fp.read(self.sectorsize) - if len(sector) != self.sectorsize: - log.debug('getsect(): sect=%X, read=%d, sectorsize=%d' % - (sect, len(sector), self.sectorsize)) - self._raise_defect(DEFECT_FATAL, 'incomplete OLE sector') - return sector - - - def write_sect(self, sect, data, padding=b'\x00'): - """ - Write given sector to file on disk. - - :param sect: int, sector index - :param data: bytes, sector data - :param padding: single byte, padding character if data < sector size - """ - if not isinstance(data, bytes): - raise TypeError("write_sect: data must be a bytes string") - if not isinstance(padding, bytes) or len(padding)!=1: - raise TypeError("write_sect: padding must be a bytes string of 1 char") - #TODO: we could allow padding=None for no padding at all - try: - self.fp.seek(self.sectorsize * (sect+1)) - except: - log.debug('write_sect(): sect=%X, seek=%d, filesize=%d' % - (sect, self.sectorsize*(sect+1), self._filesize)) - self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range') - if len(data) < self.sectorsize: - # add padding - data += padding * (self.sectorsize - len(data)) - elif len(data) < self.sectorsize: - raise ValueError("Data is larger than sector size") - self.fp.write(data) - - - def loaddirectory(self, sect): - """ - Load the directory. - - :param sect: sector index of directory stream. - """ - log.debug('Loading the Directory:') - # The directory is stored in a standard - # substream, independent of its size. - - # open directory stream as a read-only file: - # (stream size is not known in advance) - self.directory_fp = self._open(sect) - - #[PL] to detect malformed documents and avoid DoS attacks, the maximum - # number of directory entries can be calculated: - max_entries = self.directory_fp.size // 128 - log.debug('loaddirectory: size=%d, max_entries=%d' % - (self.directory_fp.size, max_entries)) - - # Create list of directory entries - #self.direntries = [] - # We start with a list of "None" object - self.direntries = [None] * max_entries -## for sid in iterrange(max_entries): -## entry = fp.read(128) -## if not entry: -## break -## self.direntries.append(OleDirectoryEntry(entry, sid, self)) - # load root entry: - root_entry = self._load_direntry(0) - # Root entry is the first entry: - self.root = self.direntries[0] - # TODO: read ALL directory entries (ignore bad entries?) - # TODO: adapt build_storage_tree to avoid duplicate reads - # for i in range(1, max_entries): - # self._load_direntry(i) - # read and build all storage trees, starting from the root: - self.root.build_storage_tree() - - - def _load_direntry (self, sid): - """ - Load a directory entry from the directory. - This method should only be called once for each storage/stream when - loading the directory. - - :param sid: index of storage/stream in the directory. - :returns: a OleDirectoryEntry object - - :exception IOError: if the entry has always been referenced. - """ - # check if SID is OK: - if sid<0 or sid>=len(self.direntries): - self._raise_defect(DEFECT_FATAL, "OLE directory index out of range") - # check if entry was already referenced: - if self.direntries[sid] is not None: - self._raise_defect(DEFECT_INCORRECT, - "double reference for OLE stream/storage") - # if exception not raised, return the object - return self.direntries[sid] - self.directory_fp.seek(sid * 128) - entry = self.directory_fp.read(128) - self.direntries[sid] = OleDirectoryEntry(entry, sid, self) - return self.direntries[sid] - - - def dumpdirectory(self): - """ - Dump directory (for debugging only) - """ - self.root.dump() - - - def _open(self, start, size = UNKNOWN_SIZE, force_FAT=False): - """ - Open a stream, either in FAT or MiniFAT according to its size. - (openstream helper) - - :param start: index of first sector - :param size: size of stream (or nothing if size is unknown) - :param force_FAT: if False (default), stream will be opened in FAT or MiniFAT - according to size. If True, it will always be opened in FAT. - """ - log.debug('OleFileIO.open(): sect=%Xh, size=%d, force_FAT=%s' % - (start, size, str(force_FAT))) - # stream size is compared to the mini_stream_cutoff_size threshold: - if size < self.minisectorcutoff and not force_FAT: - # ministream object - if not self.ministream: - # load MiniFAT if it wasn't already done: - self.loadminifat() - # The first sector index of the miniFAT stream is stored in the - # root directory entry: - size_ministream = self.root.size - log.debug('Opening MiniStream: sect=%Xh, size=%d' % - (self.root.isectStart, size_ministream)) - self.ministream = self._open(self.root.isectStart, - size_ministream, force_FAT=True) - return OleStream(fp=self.ministream, sect=start, size=size, - offset=0, sectorsize=self.minisectorsize, - fat=self.minifat, filesize=self.ministream.size, - olefileio=self) - else: - # standard stream - return OleStream(fp=self.fp, sect=start, size=size, - offset=self.sectorsize, - sectorsize=self.sectorsize, fat=self.fat, - filesize=self._filesize, - olefileio=self) - - - def _list(self, files, prefix, node, streams=True, storages=False): - """ - listdir helper - - :param files: list of files to fill in - :param prefix: current location in storage tree (list of names) - :param node: current node (OleDirectoryEntry object) - :param streams: bool, include streams if True (True by default) - new in v0.26 - :param storages: bool, include storages if True (False by default) - new in v0.26 - (note: the root storage is never included) - """ - prefix = prefix + [node.name] - for entry in node.kids: - if entry.entry_type == STGTY_STORAGE: - # this is a storage - if storages: - # add it to the list - files.append(prefix[1:] + [entry.name]) - # check its kids - self._list(files, prefix, entry, streams, storages) - elif entry.entry_type == STGTY_STREAM: - # this is a stream - if streams: - # add it to the list - files.append(prefix[1:] + [entry.name]) - else: - self._raise_defect(DEFECT_INCORRECT, 'The directory tree contains an entry which is not a stream nor a storage.') - - - def listdir(self, streams=True, storages=False): - """ - Return a list of streams and/or storages stored in this file - - :param streams: bool, include streams if True (True by default) - new in v0.26 - :param storages: bool, include storages if True (False by default) - new in v0.26 - (note: the root storage is never included) - :returns: list of stream and/or storage paths - """ - files = [] - self._list(files, [], self.root, streams, storages) - return files - - - def _find(self, filename): - """ - Returns directory entry of given filename. (openstream helper) - Note: this method is case-insensitive. - - :param filename: path of stream in storage tree (except root entry), either: - - - a string using Unix path syntax, for example: - 'storage_1/storage_1.2/stream' - - or a list of storage filenames, path to the desired stream/storage. - Example: ['storage_1', 'storage_1.2', 'stream'] - - :returns: sid of requested filename - :exception IOError: if file not found - """ - - # if filename is a string instead of a list, split it on slashes to - # convert to a list: - if isinstance(filename, basestring): - filename = filename.split('/') - # walk across storage tree, following given path: - node = self.root - for name in filename: - for kid in node.kids: - if kid.name.lower() == name.lower(): - break - else: - raise IOError("file not found") - node = kid - return node.sid - - - def openstream(self, filename): - """ - Open a stream as a read-only file object (BytesIO). - Note: filename is case-insensitive. - - :param filename: path of stream in storage tree (except root entry), either: - - - a string using Unix path syntax, for example: - 'storage_1/storage_1.2/stream' - - or a list of storage filenames, path to the desired stream/storage. - Example: ['storage_1', 'storage_1.2', 'stream'] - - :returns: file object (read-only) - :exception IOError: if filename not found, or if this is not a stream. - """ - sid = self._find(filename) - entry = self.direntries[sid] - if entry.entry_type != STGTY_STREAM: - raise IOError("this file is not a stream") - return self._open(entry.isectStart, entry.size) - - - def write_stream(self, stream_name, data): - """ - Write a stream to disk. For now, it is only possible to replace an - existing stream by data of the same size. - - :param stream_name: path of stream in storage tree (except root entry), either: - - - a string using Unix path syntax, for example: - 'storage_1/storage_1.2/stream' - - or a list of storage filenames, path to the desired stream/storage. - Example: ['storage_1', 'storage_1.2', 'stream'] - - :param data: bytes, data to be written, must be the same size as the original - stream. - """ - if not isinstance(data, bytes): - raise TypeError("write_stream: data must be a bytes string") - sid = self._find(stream_name) - entry = self.direntries[sid] - if entry.entry_type != STGTY_STREAM: - raise IOError("this is not a stream") - size = entry.size - if size != len(data): - raise ValueError("write_stream: data must be the same size as the existing stream") - if size < self.minisectorcutoff: - raise NotImplementedError("Writing a stream in MiniFAT is not implemented yet") - sect = entry.isectStart - # number of sectors to write - nb_sectors = (size + (self.sectorsize-1)) // self.sectorsize - log.debug('nb_sectors = %d' % nb_sectors) - for i in range(nb_sectors): -## try: -## self.fp.seek(offset + self.sectorsize * sect) -## except: -## log.debug('sect=%d, seek=%d' % -## (sect, offset+self.sectorsize*sect)) -## raise IOError('OLE sector index out of range') - # extract one sector from data, the last one being smaller: - if i<(nb_sectors-1): - data_sector = data [i*self.sectorsize : (i+1)*self.sectorsize] - #TODO: comment this if it works - assert(len(data_sector)==self.sectorsize) - else: - data_sector = data [i*self.sectorsize:] - #TODO: comment this if it works - log.debug('write_stream: size=%d sectorsize=%d data_sector=%Xh size%%sectorsize=%d' - % (size, self.sectorsize, len(data_sector), size % self.sectorsize)) - assert(len(data_sector) % self.sectorsize==size % self.sectorsize) - self.write_sect(sect, data_sector) -## self.fp.write(data_sector) - # jump to next sector in the FAT: - try: - sect = self.fat[sect] - except IndexError: - # [PL] if pointer is out of the FAT an exception is raised - raise IOError('incorrect OLE FAT, sector index out of range') - #[PL] Last sector should be a "end of chain" marker: - if sect != ENDOFCHAIN: - raise IOError('incorrect last sector index in OLE stream') - - - def get_type(self, filename): - """ - Test if given filename exists as a stream or a storage in the OLE - container, and return its type. - - :param filename: path of stream in storage tree. (see openstream for syntax) - :returns: False if object does not exist, its entry type (>0) otherwise: - - - STGTY_STREAM: a stream - - STGTY_STORAGE: a storage - - STGTY_ROOT: the root entry - """ - try: - sid = self._find(filename) - entry = self.direntries[sid] - return entry.entry_type - except: - return False - - - def getclsid(self, filename): - """ - Return clsid of a stream/storage. - - :param filename: path of stream/storage in storage tree. (see openstream for - syntax) - :returns: Empty string if clsid is null, a printable representation of the clsid otherwise - - new in version 0.44 - """ - sid = self._find(filename) - entry = self.direntries[sid] - return entry.clsid - - - def getmtime(self, filename): - """ - Return modification time of a stream/storage. - - :param filename: path of stream/storage in storage tree. (see openstream for - syntax) - :returns: None if modification time is null, a python datetime object - otherwise (UTC timezone) - - new in version 0.26 - """ - sid = self._find(filename) - entry = self.direntries[sid] - return entry.getmtime() - - - def getctime(self, filename): - """ - Return creation time of a stream/storage. - - :param filename: path of stream/storage in storage tree. (see openstream for - syntax) - :returns: None if creation time is null, a python datetime object - otherwise (UTC timezone) - - new in version 0.26 - """ - sid = self._find(filename) - entry = self.direntries[sid] - return entry.getctime() - - - def exists(self, filename): - """ - Test if given filename exists as a stream or a storage in the OLE - container. - Note: filename is case-insensitive. - - :param filename: path of stream in storage tree. (see openstream for syntax) - :returns: True if object exist, else False. - """ - try: - sid = self._find(filename) - return True - except: - return False - - - def get_size(self, filename): - """ - Return size of a stream in the OLE container, in bytes. - - :param filename: path of stream in storage tree (see openstream for syntax) - :returns: size in bytes (long integer) - :exception IOError: if file not found - :exception TypeError: if this is not a stream. - """ - sid = self._find(filename) - entry = self.direntries[sid] - if entry.entry_type != STGTY_STREAM: - #TODO: Should it return zero instead of raising an exception ? - raise TypeError('object is not an OLE stream') - return entry.size - - - def get_rootentry_name(self): - """ - Return root entry name. Should usually be 'Root Entry' or 'R' in most - implementations. - """ - return self.root.name - - - def getproperties(self, filename, convert_time=False, no_conversion=None): - """ - Return properties described in substream. - - :param filename: path of stream in storage tree (see openstream for syntax) - :param convert_time: bool, if True timestamps will be converted to Python datetime - :param no_conversion: None or list of int, timestamps not to be converted - (for example total editing time is not a real timestamp) - - :returns: a dictionary of values indexed by id (integer) - """ - #REFERENCE: [MS-OLEPS] https://msdn.microsoft.com/en-us/library/dd942421.aspx - # make sure no_conversion is a list, just to simplify code below: - if no_conversion == None: - no_conversion = [] - # stream path as a string to report exceptions: - streampath = filename - if not isinstance(streampath, str): - streampath = '/'.join(streampath) - - fp = self.openstream(filename) - - data = {} - - try: - # header - s = fp.read(28) - clsid = _clsid(s[8:24]) - - # format id - s = fp.read(20) - fmtid = _clsid(s[:16]) - fp.seek(i32(s, 16)) - - # get section - s = b"****" + fp.read(i32(fp.read(4))-4) - # number of properties: - num_props = i32(s, 4) - except BaseException as exc: - # catch exception while parsing property header, and only raise - # a DEFECT_INCORRECT then return an empty dict, because this is not - # a fatal error when parsing the whole file - msg = 'Error while parsing properties header in stream %s: %s' % ( - repr(streampath), exc) - self._raise_defect(DEFECT_INCORRECT, msg, type(exc)) - return data - - # clamp num_props based on the data length - num_props = min(num_props, len(s) / 8) - - for i in iterrange(num_props): - property_id = 0 # just in case of an exception - try: - property_id = i32(s, 8+i*8) - offset = i32(s, 12+i*8) - property_type = i32(s, offset) - - log.debug('property id=%d: type=%d offset=%X' % (property_id, property_type, offset)) - - # test for common types first (should perhaps use - # a dictionary instead?) - - if property_type == VT_I2: # 16-bit signed integer - value = i16(s, offset+4) - if value >= 32768: - value = value - 65536 - elif property_type == VT_UI2: # 2-byte unsigned integer - value = i16(s, offset+4) - elif property_type in (VT_I4, VT_INT, VT_ERROR): - # VT_I4: 32-bit signed integer - # VT_ERROR: HRESULT, similar to 32-bit signed integer, - # see https://msdn.microsoft.com/en-us/library/cc230330.aspx - value = i32(s, offset+4) - elif property_type in (VT_UI4, VT_UINT): # 4-byte unsigned integer - value = i32(s, offset+4) # FIXME - elif property_type in (VT_BSTR, VT_LPSTR): - # CodePageString, see https://msdn.microsoft.com/en-us/library/dd942354.aspx - # size is a 32 bits integer, including the null terminator, and - # possibly trailing or embedded null chars - #TODO: if codepage is unicode, the string should be converted as such - count = i32(s, offset+4) - value = s[offset+8:offset+8+count-1] - # remove all null chars: - value = value.replace(b'\x00', b'') - elif property_type == VT_BLOB: - # binary large object (BLOB) - # see https://msdn.microsoft.com/en-us/library/dd942282.aspx - count = i32(s, offset+4) - value = s[offset+8:offset+8+count] - elif property_type == VT_LPWSTR: - # UnicodeString - # see https://msdn.microsoft.com/en-us/library/dd942313.aspx - # "the string should NOT contain embedded or additional trailing - # null characters." - count = i32(s, offset+4) - value = self._decode_utf16_str(s[offset+8:offset+8+count*2]) - elif property_type == VT_FILETIME: - value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32) - # FILETIME is a 64-bit int: "number of 100ns periods - # since Jan 1,1601". - if convert_time and property_id not in no_conversion: - log.debug('Converting property #%d to python datetime, value=%d=%fs' - %(property_id, value, float(value)/10000000)) - # convert FILETIME to Python datetime.datetime - # inspired from https://code.activestate.com/recipes/511425-filetime-to-datetime/ - _FILETIME_null_date = datetime.datetime(1601, 1, 1, 0, 0, 0) - log.debug('timedelta days=%d' % (value//(10*1000000*3600*24))) - value = _FILETIME_null_date + datetime.timedelta(microseconds=value//10) - else: - # legacy code kept for backward compatibility: returns a - # number of seconds since Jan 1,1601 - value = value // 10000000 # seconds - elif property_type == VT_UI1: # 1-byte unsigned integer - value = i8(s[offset+4]) - elif property_type == VT_CLSID: - value = _clsid(s[offset+4:offset+20]) - elif property_type == VT_CF: - # PropertyIdentifier or ClipboardData?? - # see https://msdn.microsoft.com/en-us/library/dd941945.aspx - count = i32(s, offset+4) - value = s[offset+8:offset+8+count] - elif property_type == VT_BOOL: - # VARIANT_BOOL, 16 bits bool, 0x0000=Fals, 0xFFFF=True - # see https://msdn.microsoft.com/en-us/library/cc237864.aspx - value = bool(i16(s, offset+4)) - else: - value = None # everything else yields "None" - log.debug('property id=%d: type=%d not implemented in parser yet' % (property_id, property_type)) - - # missing: VT_EMPTY, VT_NULL, VT_R4, VT_R8, VT_CY, VT_DATE, - # VT_DECIMAL, VT_I1, VT_I8, VT_UI8, - # see https://msdn.microsoft.com/en-us/library/dd942033.aspx - - # FIXME: add support for VT_VECTOR - # VT_VECTOR is a 32 uint giving the number of items, followed by - # the items in sequence. The VT_VECTOR value is combined with the - # type of items, e.g. VT_VECTOR|VT_BSTR - # see https://msdn.microsoft.com/en-us/library/dd942011.aspx - - #print("%08x" % property_id, repr(value), end=" ") - #print("(%s)" % VT[i32(s, offset) & 0xFFF]) - - data[property_id] = value - except BaseException as exc: - # catch exception while parsing each property, and only raise - # a DEFECT_INCORRECT, because parsing can go on - msg = 'Error while parsing property id %d in stream %s: %s' % ( - property_id, repr(streampath), exc) - self._raise_defect(DEFECT_INCORRECT, msg, type(exc)) - - return data - - def get_metadata(self): - """ - Parse standard properties streams, return an OleMetadata object - containing all the available metadata. - (also stored in the metadata attribute of the OleFileIO object) - - new in version 0.25 - """ - self.metadata = OleMetadata() - self.metadata.parse_properties(self) - return self.metadata - -# -# -------------------------------------------------------------------- -# This script can be used to dump the directory of any OLE2 structured -# storage file. - -if __name__ == "__main__": - - import sys, optparse - - DEFAULT_LOG_LEVEL = "warning" # Default log level - LOG_LEVELS = { - 'debug': logging.DEBUG, - 'info': logging.INFO, - 'warning': logging.WARNING, - 'error': logging.ERROR, - 'critical': logging.CRITICAL - } - - usage = 'usage: %prog [options] [filename2 ...]' - parser = optparse.OptionParser(usage=usage) - parser.add_option("-c", action="store_true", dest="check_streams", - help='check all streams (for debugging purposes)') - parser.add_option("-d", action="store_true", dest="debug_mode", - help='debug mode, shortcut for -l debug (displays a lot of debug information, for developers only)') - parser.add_option('-l', '--loglevel', dest="loglevel", action="store", default=DEFAULT_LOG_LEVEL, - help="logging level debug/info/warning/error/critical (default=%default)") - - (options, args) = parser.parse_args() - - print('olefile version %s %s - https://www.decalage.info/en/olefile\n' % (__version__, __date__)) - - # Print help if no arguments are passed - if len(args) == 0: - print(__doc__) - parser.print_help() - sys.exit() - - if options.debug_mode: - options.loglevel = 'debug' - - # setup logging to the console - logging.basicConfig(level=LOG_LEVELS[options.loglevel], format='%(levelname)-8s %(message)s') - - # also enable the module's logger: - enable_logging() - - for filename in args: - try: - ole = OleFileIO(filename)#, raise_defects=DEFECT_INCORRECT) - print("-" * 68) - print(filename) - print("-" * 68) - ole.dumpdirectory() - for streamname in ole.listdir(): - if streamname[-1][0] == "\005": - print("%r: properties" % streamname) - try: - props = ole.getproperties(streamname, convert_time=True) - props = sorted(props.items()) - for k, v in props: - #[PL]: avoid to display too large or binary values: - if isinstance(v, (basestring, bytes)): - if len(v) > 50: - v = v[:50] - if isinstance(v, bytes): - # quick and dirty binary check: - for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20, - 21,22,23,24,25,26,27,28,29,30,31): - if c in bytearray(v): - v = '(binary data)' - break - print(" ", k, v) - except: - log.exception('Error while parsing property stream %r' % streamname) - - if options.check_streams: - # Read all streams to check if there are errors: - print('\nChecking streams...') - for streamname in ole.listdir(): - # print name using repr() to convert binary chars to \xNN: - print('-', repr('/'.join(streamname)),'-', end=' ') - st_type = ole.get_type(streamname) - if st_type == STGTY_STREAM: - print('size %d' % ole.get_size(streamname)) - # just try to read stream in memory: - ole.openstream(streamname) - else: - print('NOT a stream : type=%d' % st_type) - print() - -## for streamname in ole.listdir(): -## # print name using repr() to convert binary chars to \xNN: -## print('-', repr('/'.join(streamname)),'-', end=' ') -## print(ole.getmtime(streamname)) -## print() - - print('Modification/Creation times of all directory entries:') - for entry in ole.direntries: - if entry is not None: - print('- %s: mtime=%s ctime=%s' % (entry.name, - entry.getmtime(), entry.getctime())) - print() - - # parse and display metadata: - try: - meta = ole.get_metadata() - meta.dump() - except: - log.exception('Error while parsing metadata') - print() - #[PL] Test a few new methods: - root = ole.get_rootentry_name() - print('Root entry name: "%s"' % root) - if ole.exists('worddocument'): - print("This is a Word document.") - print("type of stream 'WordDocument':", ole.get_type('worddocument')) - print("size :", ole.get_size('worddocument')) - if ole.exists('macros/vba'): - print("This document may contain VBA macros.") - - # print parsing issues: - print('\nNon-fatal issues raised during parsing:') - if ole.parsing_issues: - for exctype, msg in ole.parsing_issues: - print('- %s: %s' % (exctype.__name__, msg)) - else: - print('None') - except: - log.exception('Error while parsing file %r' % filename) - -# this code was developed while listening to The Wedding Present "Sea Monsters" diff --git a/oletools/thirdparty/tablestream/tablestream.py b/oletools/thirdparty/tablestream/tablestream.py index 3a7df4f..dcc82ab 100644 --- a/oletools/thirdparty/tablestream/tablestream.py +++ b/oletools/thirdparty/tablestream/tablestream.py @@ -19,7 +19,7 @@ License: BSD, see source code or documentation #=== LICENSE ================================================================== -# tablestream is copyright (c) 2015-2016 Philippe Lagadec (http://www.decalage.info) +# tablestream is copyright (c) 2015-2018 Philippe Lagadec (http://www.decalage.info) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, @@ -54,8 +54,9 @@ from __future__ import print_function # 2016-07-31 v0.06 PL: - handle newline characters properly in each cell # 2016-08-28 v0.07 PL: - support for both Python 2.6+ and 3.x # - all cells are converted to unicode +# 2018-09-22 v0.08 PL: - removed mention to oletools' thirdparty folder -__version__ = '0.07' +__version__ = '0.08' #------------------------------------------------------------------------------ # TODO: @@ -70,15 +71,6 @@ __version__ = '0.07' import textwrap import sys, os -# add the thirdparty subfolder to sys.path (absolute+normalized path): -_thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) -# print('_thismodule_dir = %r' % _thismodule_dir) -# assumption: this module is in a subfolder of thirdparty: -_thirdparty_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) -# print('_thirdparty_dir = %r' % _thirdparty_dir) -if not _thirdparty_dir in sys.path: - sys.path.insert(0, _thirdparty_dir) - import colorclass # On Windows, colorclass needs to be enabled: diff --git a/oletools/xls_parser.py b/oletools/xls_parser.py index 64e67a1..52575a7 100644 --- a/oletools/xls_parser.py +++ b/oletools/xls_parser.py @@ -5,7 +5,7 @@ Read storages, (sub-)streams, records from xls file # # === LICENSE ================================================================== -# xls_parser is copyright (c) 2014-2017 Philippe Lagadec (http://www.decalage.info) +# xls_parser is copyright (c) 2014-2018 Philippe Lagadec (http://www.decalage.info) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, @@ -86,14 +86,16 @@ def is_xls(filename): returns True if given file is an ole file and contains a Workbook stream todo: could further check that workbook stream starts with a globals - substream + substream. + See also: oleid.OleID.check_excel """ try: for stream in XlsFile(filename).iter_streams(): if isinstance(stream, WorkbookStream): return True except Exception: - return False + pass + return False def read_unicode(data, start_idx, n_chars): @@ -130,6 +132,8 @@ class XlsFile(record_base.OleRecordFile): @classmethod def stream_class_for_name(cls, stream_name): """ helper for iter_streams """ + if stream_name == 'Workbook': + return WorkbookStream return XlsStream diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..378be44 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pyparsing>=2.2.0 +olefile>=0.45 diff --git a/setup.py b/setup.py index 227b8a5..8b26df6 100644 --- a/setup.py +++ b/setup.py @@ -24,6 +24,10 @@ to install this package. # 2017-01-18 v0.51 PL: - added package zipfile27 (issue #121) # 2017-10-18 v0.52 PL: - added msodde # 2018-03-19 v0.52.3 PL: - added install_requires, removed thirdparty.pyparsing +# 2018-09-11 v0.54 PL: - olefile is now a dependency +# 2018-09-15 PL: - easygui is now a dependency +# 2018-09-22 PL: - colorclass is now a dependency +# 2018-10-27 PL: - fixed issue #359 (bug when importing log_helper) #--- TODO --------------------------------------------------------------------- @@ -43,7 +47,7 @@ import os, fnmatch #--- METADATA ----------------------------------------------------------------- name = "oletools" -version = '0.53' +version = '0.54dev4' desc = "Python tools to analyze security characteristics of MS Office and OLE files (also called Structured Storage, Compound File Binary Format or Compound Document File Format), for Malware Analysis and Incident Response #DFIR" long_desc = open('oletools/README.rst').read() author = "Philippe Lagadec" @@ -52,7 +56,7 @@ url = "http://www.decalage.info/python/oletools" license = "BSD" download_url = "https://github.com/decalage2/oletools/releases" -# see https://pypi.python.org/pypi?%3Aaction=list_classifiers +# see https://pypi.org/pypi?%3Aaction=list_classifiers classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", @@ -78,14 +82,12 @@ classifiers=[ packages=[ "oletools", "oletools.common", + "oletools.common.log_helper", 'oletools.thirdparty', - 'oletools.thirdparty.olefile', - 'oletools.thirdparty.easygui', 'oletools.thirdparty.xxxswf', 'oletools.thirdparty.prettytable', 'oletools.thirdparty.xglob', 'oletools.thirdparty.DridexUrlDecoder', - 'oletools.thirdparty.colorclass', 'oletools.thirdparty.tablestream', 'oletools.thirdparty.zipfile27', ] @@ -163,16 +165,9 @@ package_data={ + rglob('oletools/doc', 'doc', '*.md') + rglob('oletools/doc', 'doc', '*.png'), - 'oletools.thirdparty.olefile': [ - 'README.txt', - 'LICENSE.txt', - ], 'oletools.thirdparty.xglob': [ 'LICENSE.txt', ], - 'oletools.thirdparty.easygui': [ - 'LICENSE.txt', - ], 'oletools.thirdparty.xxxswf': [ 'LICENSE.txt', ], @@ -182,9 +177,6 @@ package_data={ 'oletools.thirdparty.DridexUrlDecoder': [ 'LICENSE.txt', ], - 'oletools.thirdparty.colorclass': [ - 'LICENSE.txt', - ], 'oletools.thirdparty.zipfile27': [ 'LICENSE.txt', ], @@ -287,6 +279,7 @@ entry_points = { 'rtfobj=oletools.rtfobj:main', 'oleobj=oletools.oleobj:main', 'msodde=oletools.msodde:main', + 'olefile=olefile.olefile:main', ], } @@ -320,7 +313,12 @@ def main(): entry_points=entry_points, test_suite="tests", # scripts=scripts, - install_requires=["pyparsing"], + install_requires=[ + "pyparsing>=2.2.0", + "olefile>=0.46", + "easygui", + 'colorclass', + ], ) diff --git a/oletools/thirdparty/easygui/__init__.py b/tests/common/__init__.py index e69de29..e69de29 100644 --- a/oletools/thirdparty/easygui/__init__.py +++ b/tests/common/__init__.py diff --git a/tests/json/__init__.py b/tests/common/log_helper/__init__.py index e69de29..e69de29 100644 --- a/tests/json/__init__.py +++ b/tests/common/log_helper/__init__.py diff --git a/tests/common/log_helper/log_helper_test_imported.py b/tests/common/log_helper/log_helper_test_imported.py new file mode 100644 index 0000000..b3777af --- /dev/null +++ b/tests/common/log_helper/log_helper_test_imported.py @@ -0,0 +1,23 @@ +""" +Dummy file that logs messages, meant to be imported +by the main test file +""" + +from oletools.common.log_helper import log_helper +import logging + +DEBUG_MESSAGE = 'imported: debug log' +INFO_MESSAGE = 'imported: info log' +WARNING_MESSAGE = 'imported: warning log' +ERROR_MESSAGE = 'imported: error log' +CRITICAL_MESSAGE = 'imported: critical log' + +logger = log_helper.get_or_create_silent_logger('test_imported', logging.ERROR) + + +def log(): + logger.debug(DEBUG_MESSAGE) + logger.info(INFO_MESSAGE) + logger.warning(WARNING_MESSAGE) + logger.error(ERROR_MESSAGE) + logger.critical(CRITICAL_MESSAGE) diff --git a/tests/common/log_helper/log_helper_test_main.py b/tests/common/log_helper/log_helper_test_main.py new file mode 100644 index 0000000..0f6057a --- /dev/null +++ b/tests/common/log_helper/log_helper_test_main.py @@ -0,0 +1,57 @@ +""" Test log_helpers """ + +import sys +from tests.common.log_helper import log_helper_test_imported +from oletools.common.log_helper import log_helper + +DEBUG_MESSAGE = 'main: debug log' +INFO_MESSAGE = 'main: info log' +WARNING_MESSAGE = 'main: warning log' +ERROR_MESSAGE = 'main: error log' +CRITICAL_MESSAGE = 'main: critical log' + +logger = log_helper.get_or_create_silent_logger('test_main') + + +def init_logging_and_log(args): + """ + Try to cover possible logging scenarios. For each scenario covered, here's the expected args and outcome: + - Log without enabling: [''] + * logging when being imported - should never print + - Log as JSON without enabling: ['as-json', ''] + * logging as JSON when being imported - should never print + - Enable and log: ['enable', ''] + * logging when being run as script - should log messages + - Enable and log as JSON: ['as-json', 'enable', ''] + * logging as JSON when being run as script - should log messages as JSON + - Enable, log as JSON and throw: ['enable', 'as-json', 'throw', ''] + * should produce JSON-compatible output, even after an unhandled exception + """ + + # the level should always be the last argument passed + level = args[-1] + use_json = 'as-json' in args + throw = 'throw' in args + + if 'enable' in args: + log_helper.enable_logging(use_json, level, stream=sys.stdout) + + _log() + + if throw: + raise Exception('An exception occurred before ending the logging') + + log_helper.end_logging() + + +def _log(): + logger.debug(DEBUG_MESSAGE) + logger.info(INFO_MESSAGE) + logger.warning(WARNING_MESSAGE) + logger.error(ERROR_MESSAGE) + logger.critical(CRITICAL_MESSAGE) + log_helper_test_imported.log() + + +if __name__ == '__main__': + init_logging_and_log(sys.argv[1:]) diff --git a/tests/common/log_helper/test_log_helper.py b/tests/common/log_helper/test_log_helper.py new file mode 100644 index 0000000..03dee68 --- /dev/null +++ b/tests/common/log_helper/test_log_helper.py @@ -0,0 +1,112 @@ +""" Test the log helper + +This tests the generic log helper. +Check if it handles imported modules correctly +and that the default silent logger won't log when nothing is enabled +""" + +import unittest +import sys +import json +import subprocess +from tests.common.log_helper import log_helper_test_main +from tests.common.log_helper import log_helper_test_imported +from os.path import dirname, join, relpath, abspath + +# this is the common base of "tests" and "oletools" dirs +ROOT_DIRECTORY = abspath(join(__file__, '..', '..', '..', '..')) +TEST_FILE = relpath(join(dirname(__file__), 'log_helper_test_main.py'), ROOT_DIRECTORY) +PYTHON_EXECUTABLE = sys.executable + +MAIN_LOG_MESSAGES = [ + log_helper_test_main.DEBUG_MESSAGE, + log_helper_test_main.INFO_MESSAGE, + log_helper_test_main.WARNING_MESSAGE, + log_helper_test_main.ERROR_MESSAGE, + log_helper_test_main.CRITICAL_MESSAGE +] + + +class TestLogHelper(unittest.TestCase): + def test_it_doesnt_log_when_not_enabled(self): + output = self._run_test(['debug']) + self.assertTrue(len(output) == 0) + + def test_it_doesnt_log_json_when_not_enabled(self): + output = self._run_test(['as-json', 'debug']) + self.assertTrue(len(output) == 0) + + def test_logs_when_enabled(self): + output = self._run_test(['enable', 'warning']) + + expected_messages = [ + log_helper_test_main.WARNING_MESSAGE, + log_helper_test_main.ERROR_MESSAGE, + log_helper_test_main.CRITICAL_MESSAGE, + log_helper_test_imported.WARNING_MESSAGE, + log_helper_test_imported.ERROR_MESSAGE, + log_helper_test_imported.CRITICAL_MESSAGE + ] + + for msg in expected_messages: + self.assertIn(msg, output) + + def test_logs_json_when_enabled(self): + output = self._run_test(['enable', 'as-json', 'critical']) + + self._assert_json_messages(output, [ + log_helper_test_main.CRITICAL_MESSAGE, + log_helper_test_imported.CRITICAL_MESSAGE + ]) + + def test_json_correct_on_exceptions(self): + """ + Test that even on unhandled exceptions our JSON is always correct + """ + output = self._run_test(['enable', 'as-json', 'throw', 'critical'], False) + self._assert_json_messages(output, [ + log_helper_test_main.CRITICAL_MESSAGE, + log_helper_test_imported.CRITICAL_MESSAGE + ]) + + def _assert_json_messages(self, output, messages): + try: + json_data = json.loads(output) + self.assertEquals(len(json_data), len(messages)) + + for i in range(len(messages)): + self.assertEquals(messages[i], json_data[i]['msg']) + except ValueError: + self.fail('Invalid json:\n' + output) + + self.assertNotEqual(len(json_data), 0, msg='Output was empty') + + def _run_test(self, args, should_succeed=True): + """ + Use subprocess to better simulate the real scenario and avoid + logging conflicts when running multiple tests (since logging depends on singletons, + we might get errors or false positives between sequential tests runs) + """ + child = subprocess.Popen( + [PYTHON_EXECUTABLE, TEST_FILE] + args, + shell=False, + env={'PYTHONPATH': ROOT_DIRECTORY}, + universal_newlines=True, + cwd=ROOT_DIRECTORY, + stdin=None, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + (output, output_err) = child.communicate() + + if not isinstance(output, str): + output = output.decode('utf-8') + + self.assertEquals(child.returncode == 0, should_succeed) + + return output.strip() + + +# just in case somebody calls this file as a script +if __name__ == '__main__': + unittest.main() diff --git a/tests/json/test_output.py b/tests/json/test_output.py deleted file mode 100644 index f1fd48b..0000000 --- a/tests/json/test_output.py +++ /dev/null @@ -1,99 +0,0 @@ -""" Test validity of json output - -Some scripts have a json output flag. Verify that at default log levels output -can be captured as-is and parsed by a json parser -- checking the return code -if desired. -""" - -import unittest -import sys -import json -import os -from os.path import join -from oletools import msodde -from tests.test_utils import OutputCapture, DATA_BASE_DIR - -if sys.version_info[0] <= 2: - from oletools import olevba -else: - from oletools import olevba3 as olevba - - -class TestValidJson(unittest.TestCase): - """ - Ensure that script output is valid json. - If check_return_code is True we also ignore the output - of runs that didn't succeed. - """ - - @staticmethod - def iter_test_files(): - """ Iterate over all test files in DATA_BASE_DIR """ - for dirpath, _, filenames in os.walk(DATA_BASE_DIR): - for filename in filenames: - yield join(dirpath, filename) - - def run_and_parse(self, program, args, print_output=False, check_return_code=True): - """ run single program with single file and parse output """ - with OutputCapture() as capturer: # capture stdout - try: - return_code = program(args) - except Exception: - return_code = 1 # would result in non-zero exit - except SystemExit as se: - return_code = se.code or 0 # se.code can be None - if check_return_code and return_code is not 0: - if print_output: - print('Command failed ({0}) -- not parsing output' - .format(return_code)) - return [] # no need to test - - self.assertNotEqual(return_code, None, - msg='self-test fail: return_code not set') - - # now test output - if print_output: - print(capturer.get_data()) - try: - json_data = json.loads(capturer.get_data()) - except ValueError: - self.fail('Invalid json:\n' + capturer.get_data()) - self.assertNotEqual(len(json_data), 0, msg='Output was empty') - return json_data - - def run_all_files(self, program, args_without_filename, print_output=False): - """ run test for a single program over all test files """ - n_files = 0 - for testfile in self.iter_test_files(): # loop over all input - args = args_without_filename + [testfile, ] - self.run_and_parse(program, args, print_output) - n_files += 1 - self.assertNotEqual(n_files, 0, - msg='self-test fail: No test files found') - - def test_msodde(self): - """ Test msodde.py """ - self.run_all_files(msodde.main, ['-j', ]) - - def test_olevba(self): - """ Test olevba.py with default args """ - self.run_all_files(olevba.main, ['-j', ]) - - def test_olevba_analysis(self): - """ Test olevba.py with -a """ - self.run_all_files(olevba.main, ['-j', '-a', ]) - - def test_olevba_recurse(self): - """ Test olevba.py with -r """ - json_data = self.run_and_parse(olevba.main, - ['-j', '-r', join(DATA_BASE_DIR, '*')], - check_return_code=False) - self.assertNotEqual(len(json_data), 0, - msg='olevba[3] returned non-zero or no output') - self.assertNotEqual(json_data[-1]['n_processed'], 0, - msg='self-test fail: No test files found!') - - -# just in case somebody calls this file as a script -if __name__ == '__main__': - unittest.main() diff --git a/tests/msodde/test_basic.py b/tests/msodde/test_basic.py index 1966a2f..3386462 100644 --- a/tests/msodde/test_basic.py +++ b/tests/msodde/test_basic.py @@ -10,15 +10,14 @@ from __future__ import print_function import unittest from oletools import msodde -from tests.test_utils import OutputCapture, DATA_BASE_DIR as BASE_DIR -import shlex +from tests.test_utils import DATA_BASE_DIR as BASE_DIR +import os from os.path import join from traceback import print_exc class TestReturnCode(unittest.TestCase): """ check return codes and exception behaviour (not text output) """ - def test_valid_doc(self): """ check that a valid doc file leads to 0 exit status """ for filename in ( @@ -57,89 +56,89 @@ class TestReturnCode(unittest.TestCase): """ check that text file argument leads to non-zero exit status """ self.do_test_validity(join(BASE_DIR, 'basic/text'), True) + def test_encrypted(self): + """ + check that encrypted files lead to non-zero exit status + + Currently, only the encryption applied by Office 2010 (CryptoApi RC4 + Encryption) is tested. + """ + CRYPT_DIR = join(BASE_DIR, 'encrypted') + ADD_ARGS = '', '-j', '-d', '-f', '-a' + for filename in os.listdir(CRYPT_DIR): + full_name = join(CRYPT_DIR, filename) + for args in ADD_ARGS: + self.do_test_validity(args + ' ' + full_name, True) + def do_test_validity(self, args, expect_error=False): """ helper for test_valid_doc[x] """ - args = shlex.split(args) - return_code = -1 have_exception = False try: - return_code = msodde.main(args) + msodde.process_file(args, msodde.FIELD_FILTER_BLACKLIST) except Exception: have_exception = True print_exc() except SystemExit as exc: # sys.exit() was called - return_code = exc.code + have_exception = True if exc.code is None: - return_code = 0 + have_exception = False - self.assertEqual(expect_error, have_exception or (return_code != 0), - msg='Args={0}, expect={1}, exc={2}, return={3}' - .format(args, expect_error, have_exception, - return_code)) + self.assertEqual(expect_error, have_exception, + msg='Args={0}, expect={1}, exc={2}' + .format(args, expect_error, have_exception)) class TestDdeLinks(unittest.TestCase): """ capture output of msodde and check dde-links are found correctly """ - def get_dde_from_output(self, capturer): + @staticmethod + def get_dde_from_output(output): """ helper to read dde links from captured output - - duplicate in tests/msodde/test_csv """ - have_start_line = False - result = [] - for line in capturer: - if not line.strip(): - continue # skip empty lines - if have_start_line: - result.append(line) - elif line == 'DDE Links:': - have_start_line = True - - self.assertTrue(have_start_line) # ensure output was complete - return result + return [o for o in output.splitlines()] def test_with_dde(self): """ check that dde links appear on stdout """ filename = 'dde-test-from-office2003.doc' - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', filename)]) - self.assertNotEqual(len(self.get_dde_from_output(capturer)), 0, + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST) + self.assertNotEqual(len(self.get_dde_from_output(output)), 0, msg='Found no dde links in output of ' + filename) def test_no_dde(self): """ check that no dde links appear on stdout """ filename = 'harmless-clean.doc' - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', filename)]) - self.assertEqual(len(self.get_dde_from_output(capturer)), 0, + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST) + self.assertEqual(len(self.get_dde_from_output(output)), 0, msg='Found dde links in output of ' + filename) def test_with_dde_utf16le(self): """ check that dde links appear on stdout """ filename = 'dde-test-from-office2013-utf_16le-korean.doc' - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', filename)]) - self.assertNotEqual(len(self.get_dde_from_output(capturer)), 0, + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST) + self.assertNotEqual(len(self.get_dde_from_output(output)), 0, msg='Found no dde links in output of ' + filename) def test_excel(self): """ check that dde links are found in excel 2007+ files """ expect = ['DDE-Link cmd /c calc.exe', ] for extn in 'xlsx', 'xlsm', 'xlsb': - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', 'dde-test.' + extn), ]) - self.assertEqual(expect, self.get_dde_from_output(capturer), + output = msodde.process_file( + join(BASE_DIR, 'msodde', 'dde-test.' + extn), msodde.FIELD_FILTER_BLACKLIST) + + self.assertEqual(expect, self.get_dde_from_output(output), msg='unexpected output for dde-test.{0}: {1}' - .format(extn, capturer.get_data())) + .format(extn, output)) def test_xml(self): """ check that dde in xml from word / excel is found """ for name_part in 'excel2003', 'word2003', 'word2007': filename = 'dde-in-' + name_part + '.xml' - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', filename), ]) - links = self.get_dde_from_output(capturer) + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST) + links = self.get_dde_from_output(output) self.assertEqual(len(links), 1, 'found {0} dde-links in {1}' .format(len(links), filename)) self.assertTrue('cmd' in links[0], 'no "cmd" in dde-link for {0}' @@ -150,16 +149,16 @@ class TestDdeLinks(unittest.TestCase): def test_clean_rtf_blacklist(self): """ find a lot of hyperlinks in rtf spec """ filename = 'RTF-Spec-1.7.rtf' - with OutputCapture() as capturer: - msodde.main([join(BASE_DIR, 'msodde', filename)]) - self.assertEqual(len(self.get_dde_from_output(capturer)), 1413) + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST) + self.assertEqual(len(self.get_dde_from_output(output)), 1413) def test_clean_rtf_ddeonly(self): """ find no dde links in rtf spec """ filename = 'RTF-Spec-1.7.rtf' - with OutputCapture() as capturer: - msodde.main(['-d', join(BASE_DIR, 'msodde', filename)]) - self.assertEqual(len(self.get_dde_from_output(capturer)), 0, + output = msodde.process_file( + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_DDE) + self.assertEqual(len(self.get_dde_from_output(output)), 0, msg='Found dde links in output of ' + filename) diff --git a/tests/msodde/test_csv.py b/tests/msodde/test_csv.py index ee46e07..92131b4 100644 --- a/tests/msodde/test_csv.py +++ b/tests/msodde/test_csv.py @@ -9,7 +9,7 @@ import os from os.path import join from oletools import msodde -from tests.test_utils import OutputCapture, DATA_BASE_DIR +from tests.test_utils import DATA_BASE_DIR class TestCSV(unittest.TestCase): @@ -49,7 +49,7 @@ class TestCSV(unittest.TestCase): sample = \ prefix.format(quote=quote, delim=delim) + \ - quote + sample_core + quote + \ + quote + sample_core + quote + delim + \ suffix.format(quote=quote, delim=delim) output = self.write_and_run(sample) n_links = len(self.get_dde_from_output(output)) @@ -69,11 +69,8 @@ class TestCSV(unittest.TestCase): def test_file(self): """ test simple small example file """ filename = join(DATA_BASE_DIR, 'msodde', 'dde-in-csv.csv') - with OutputCapture() as capturer: - capturer.reload_module(msodde) # re-create logger - ret_code = msodde.main([filename, ]) - self.assertEqual(ret_code, 0) - links = self.get_dde_from_output(capturer) + output = msodde.process_file(filename, msodde.FIELD_FILTER_BLACKLIST) + links = self.get_dde_from_output(output) self.assertEqual(len(links), 1) self.assertEqual(links[0], r"cmd '/k \..\..\..\Windows\System32\calc.exe'") @@ -91,12 +88,10 @@ class TestCSV(unittest.TestCase): if self.DO_DEBUG: args += ['-l', 'debug'] - with OutputCapture() as capturer: - capturer.reload_module(msodde) # re-create logger - ret_code = msodde.main(args) - self.assertEqual(ret_code, 0, 'checking sample resulted in ' - 'error:\n' + sample_text) - return capturer + processed_args = msodde.process_args(args) + + return msodde.process_file( + processed_args.filepath, processed_args.field_filter_mode) except Exception: raise @@ -111,25 +106,11 @@ class TestCSV(unittest.TestCase): os.remove(filename) filename = None # just in case - def get_dde_from_output(self, capturer): + @staticmethod + def get_dde_from_output(output): """ helper to read dde links from captured output - - duplicate in tests/msodde/test_basic """ - have_start_line = False - result = [] - for line in capturer: - if self.DO_DEBUG: - print('captured: ' + line) - if not line.strip(): - continue # skip empty lines - if have_start_line: - result.append(line) - elif line == 'DDE Links:': - have_start_line = True - - self.assertTrue(have_start_line) # ensure output was complete - return result + return [o for o in output.splitlines()] def test_regex(self): """ check that regex captures other ways to include dde commands diff --git a/tests/oleid/test_basic.py b/tests/oleid/test_basic.py new file mode 100644 index 0000000..e527fa2 --- /dev/null +++ b/tests/oleid/test_basic.py @@ -0,0 +1,155 @@ +""" +Test basic functionality of oleid + +Should work with python2 and python3! +""" + +import unittest +import os +from os.path import join, relpath, splitext +from oletools import oleid + +# Directory with test data, independent of current working directory +from tests.test_utils import DATA_BASE_DIR + + +class TestOleIDBasic(unittest.TestCase): + """Test basic functionality of OleID""" + + def test_all(self): + """Run all file in test-data through oleid and compare to known ouput""" + # this relies on order of indicators being constant, could relax that + # Also requires that files have the correct suffixes (no rtf in doc) + NON_OLE_SUFFIXES = ('.xml', '.csv', '.rtf', '') + NON_OLE_VALUES = (False, ) + WORD = b'Microsoft Office Word' + PPT = b'Microsoft Office PowerPoint' + EXCEL = b'Microsoft Excel' + CRYPT = (True, False, 'unknown', True, False, False, False, False, + False, False, 0) + OLE_VALUES = { + 'oleobj/sample_with_lnk_file.doc': (True, True, WORD, False, True, + False, False, False, False, + True, 0), + 'oleobj/embedded-simple-2007.xlsb': (False,), + 'oleobj/embedded-simple-2007.docm': (False,), + 'oleobj/embedded-simple-2007.xltx': (False,), + 'oleobj/embedded-simple-2007.xlam': (False,), + 'oleobj/embedded-simple-2007.dotm': (False,), + 'oleobj/sample_with_lnk_file.ppt': (True, True, PPT, False, False, + False, False, True, False, + False, 0), + 'oleobj/embedded-simple-2007.xlsx': (False,), + 'oleobj/embedded-simple-2007.xlsm': (False,), + 'oleobj/embedded-simple-2007.ppsx': (False,), + 'oleobj/embedded-simple-2007.pps': (True, True, PPT, False, False, + False, False, True, False, + False, 0), + 'oleobj/embedded-simple-2007.xla': (True, True, EXCEL, False, + False, False, True, False, + False, False, 0), + 'oleobj/sample_with_calc_embedded.doc': (True, True, WORD, False, + True, False, False, False, + False, True, 0), + 'oleobj/embedded-unicode-2007.docx': (False,), + 'oleobj/embedded-unicode.doc': (True, True, WORD, False, True, + False, False, False, False, True, + 0), + 'oleobj/embedded-simple-2007.doc': (True, True, WORD, False, True, + False, False, False, False, + True, 0), + 'oleobj/embedded-simple-2007.xls': (True, True, EXCEL, False, + False, False, True, False, + False, False, 0), + 'oleobj/embedded-simple-2007.dot': (True, True, WORD, False, True, + False, False, False, False, + True, 0), + 'oleobj/sample_with_lnk_to_calc.doc': (True, True, WORD, False, + True, False, False, False, + False, True, 0), + 'oleobj/embedded-simple-2007.ppt': (True, True, PPT, False, False, + False, False, True, False, + False, 0), + 'oleobj/sample_with_lnk_file.pps': (True, True, PPT, False, False, + False, False, True, False, + False, 0), + 'oleobj/embedded-simple-2007.pptx': (False,), + 'oleobj/embedded-simple-2007.ppsm': (False,), + 'oleobj/embedded-simple-2007.dotx': (False,), + 'oleobj/embedded-simple-2007.pptm': (False,), + 'oleobj/embedded-simple-2007.xlt': (True, True, EXCEL, False, + False, False, True, False, + False, False, 0), + 'oleobj/embedded-simple-2007.docx': (False,), + 'oleobj/embedded-simple-2007.potx': (False,), + 'oleobj/embedded-simple-2007.pot': (True, True, PPT, False, False, + False, False, True, False, + False, 0), + 'oleobj/embedded-simple-2007.xltm': (False,), + 'oleobj/embedded-simple-2007.potm': (False,), + 'encrypted/encrypted.xlsx': CRYPT, + 'encrypted/encrypted.docm': CRYPT, + 'encrypted/encrypted.docx': CRYPT, + 'encrypted/encrypted.pptm': CRYPT, + 'encrypted/encrypted.xlsb': CRYPT, + 'encrypted/encrypted.xls': (True, True, EXCEL, True, False, False, + True, False, False, False, 0), + 'encrypted/encrypted.ppt': (True, False, 'unknown', True, False, + False, False, True, False, False, 0), + 'encrypted/encrypted.pptx': CRYPT, + 'encrypted/encrypted.xlsm': CRYPT, + 'encrypted/encrypted.doc': (True, True, WORD, True, True, False, + False, False, False, False, 0), + 'msodde/harmless-clean.docm': (False,), + 'msodde/dde-in-csv.csv': (False,), + 'msodde/dde-test-from-office2013-utf_16le-korean.doc': + (True, True, WORD, False, True, False, False, False, False, + False, 0), + 'msodde/harmless-clean.doc': (True, True, WORD, False, True, False, + False, False, False, False, 0), + 'msodde/dde-test.docm': (False,), + 'msodde/dde-test.xlsb': (False,), + 'msodde/dde-test.xlsm': (False,), + 'msodde/dde-test.docx': (False,), + 'msodde/dde-test.xlsx': (False,), + 'msodde/dde-test-from-office2003.doc': (True, True, WORD, False, + True, False, False, False, + False, False, 0), + 'msodde/dde-test-from-office2016.doc': (True, True, WORD, False, + True, False, False, False, + False, False, 0), + 'msodde/harmless-clean.docx': (False,), + 'oleform/oleform-PR314.docm': (False,), + 'basic/encrypted.docx': CRYPT, + } + + indicator_names = [] + for base_dir, _, files in os.walk(DATA_BASE_DIR): + for filename in files: + full_path = join(base_dir, filename) + name = relpath(full_path, DATA_BASE_DIR) + values = tuple(indicator.value for indicator in + oleid.OleID(full_path).check()) + if len(indicator_names) < 2: # not initialized with ole yet + indicator_names = tuple(indicator.name for indicator in + oleid.OleID(full_path).check()) + suffix = splitext(filename)[1] + if suffix in NON_OLE_SUFFIXES: + self.assertEqual(values, NON_OLE_VALUES, + msg='For non-ole file {} expected {}, ' + 'not {}'.format(name, NON_OLE_VALUES, + values)) + continue + try: + self.assertEqual(values, OLE_VALUES[name], + msg='Wrong detail values for {}:\n' + ' Names {}\n Found {}\n Expect {}' + .format(name, indicator_names, values, + OLE_VALUES[name])) + except KeyError: + print('Should add oleid output for {} to {} ({})' + .format(name, __name__, values[3:])) + +# just in case somebody calls this file as a script +if __name__ == '__main__': + unittest.main() diff --git a/tests/oleobj/test_external_links.py b/tests/oleobj/test_external_links.py new file mode 100644 index 0000000..9c7e632 --- /dev/null +++ b/tests/oleobj/test_external_links.py @@ -0,0 +1,31 @@ +""" Test that oleobj detects external links in relationships files. +""" + +import unittest +import os +from os import path + +# Directory with test data, independent of current working directory +from tests.test_utils import DATA_BASE_DIR +from oletools import oleobj + +BASE_DIR = path.join(DATA_BASE_DIR, 'oleobj', 'external_link') + + +class TestExternalLinks(unittest.TestCase): + def test_external_links(self): + """ + loop through sample files asserting that external links are found + """ + + for dirpath, _, filenames in os.walk(BASE_DIR): + for filename in filenames: + file_path = path.join(dirpath, filename) + + ret_val = oleobj.main([file_path]) + self.assertEqual(ret_val, oleobj.RETURN_DID_DUMP) + + +# just in case somebody calls this file as a script +if __name__ == '__main__': + unittest.main() diff --git a/tests/olevba/__init__.py b/tests/olevba/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tests/olevba/__init__.py diff --git a/tests/olevba/test_basic.py b/tests/olevba/test_basic.py new file mode 100644 index 0000000..d319a12 --- /dev/null +++ b/tests/olevba/test_basic.py @@ -0,0 +1,45 @@ +""" +Test basic functionality of olevba[3] +""" + +import unittest +import sys +if sys.version_info.major <= 2: + from oletools import olevba +else: + from oletools import olevba3 as olevba +import os +from os.path import join + +# Directory with test data, independent of current working directory +from tests.test_utils import DATA_BASE_DIR + + +class TestOlevbaBasic(unittest.TestCase): + """Tests olevba basic functionality""" + + def test_crypt_return(self): + """ + Tests that encrypted files give a certain return code. + + Currently, only the encryption applied by Office 2010 (CryptoApi RC4 + Encryption) is tested. + """ + CRYPT_DIR = join(DATA_BASE_DIR, 'encrypted') + CRYPT_RETURN_CODE = 9 + ADD_ARGS = [], ['-d', ], ['-a', ], ['-j', ], ['-t', ] + for filename in os.listdir(CRYPT_DIR): + full_name = join(CRYPT_DIR, filename) + for args in ADD_ARGS: + try: + ret_code = olevba.main(args + [full_name, ]) + except SystemExit as se: + ret_code = se.code or 0 # se.code can be None + self.assertEqual(ret_code, CRYPT_RETURN_CODE, + msg='Wrong return code {} for args {}' + .format(ret_code, args + [filename, ])) + + +# just in case somebody calls this file as a script +if __name__ == '__main__': + unittest.main() diff --git a/tests/ooxml/test_basic.py b/tests/ooxml/test_basic.py index 1ab823f..440d08d 100644 --- a/tests/ooxml/test_basic.py +++ b/tests/ooxml/test_basic.py @@ -5,7 +5,7 @@ import unittest import os from os.path import join, splitext from tests.test_utils import DATA_BASE_DIR -from oletools.thirdparty.olefile import isOleFile +from olefile import isOleFile from oletools import ooxml import logging diff --git a/tests/test-data/encrypted/encrypted.doc b/tests/test-data/encrypted/encrypted.doc new file mode 100644 index 0000000..cf553d7 --- /dev/null +++ b/tests/test-data/encrypted/encrypted.doc diff --git a/tests/test-data/encrypted/encrypted.docm b/tests/test-data/encrypted/encrypted.docm new file mode 100644 index 0000000..92d608a --- /dev/null +++ b/tests/test-data/encrypted/encrypted.docm diff --git a/tests/test-data/encrypted/encrypted.docx b/tests/test-data/encrypted/encrypted.docx new file mode 100644 index 0000000..06d9e87 --- /dev/null +++ b/tests/test-data/encrypted/encrypted.docx diff --git a/tests/test-data/encrypted/encrypted.ppt b/tests/test-data/encrypted/encrypted.ppt new file mode 100644 index 0000000..8671044 --- /dev/null +++ b/tests/test-data/encrypted/encrypted.ppt diff --git a/tests/test-data/encrypted/encrypted.pptm b/tests/test-data/encrypted/encrypted.pptm new file mode 100644 index 0000000..f26e0ff --- /dev/null +++ b/tests/test-data/encrypted/encrypted.pptm diff --git a/tests/test-data/encrypted/encrypted.pptx b/tests/test-data/encrypted/encrypted.pptx new file mode 100644 index 0000000..108057e --- /dev/null +++ b/tests/test-data/encrypted/encrypted.pptx diff --git a/tests/test-data/encrypted/encrypted.xls b/tests/test-data/encrypted/encrypted.xls new file mode 100644 index 0000000..75d010a --- /dev/null +++ b/tests/test-data/encrypted/encrypted.xls diff --git a/tests/test-data/encrypted/encrypted.xlsb b/tests/test-data/encrypted/encrypted.xlsb new file mode 100644 index 0000000..10fa81e --- /dev/null +++ b/tests/test-data/encrypted/encrypted.xlsb diff --git a/tests/test-data/encrypted/encrypted.xlsm b/tests/test-data/encrypted/encrypted.xlsm new file mode 100644 index 0000000..e43e0b0 --- /dev/null +++ b/tests/test-data/encrypted/encrypted.xlsm diff --git a/tests/test-data/encrypted/encrypted.xlsx b/tests/test-data/encrypted/encrypted.xlsx new file mode 100644 index 0000000..1666857 --- /dev/null +++ b/tests/test-data/encrypted/encrypted.xlsx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docm new file mode 100644 index 0000000..ee1e169 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docx new file mode 100644 index 0000000..9f00bbd --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotm new file mode 100644 index 0000000..fe0c0ea --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotx new file mode 100644 index 0000000..a30ccf2 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potm new file mode 100644 index 0000000..aa29f11 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potx new file mode 100644 index 0000000..ebafc78 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsm new file mode 100644 index 0000000..22f7d97 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsx new file mode 100644 index 0000000..80e6a6e --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptm new file mode 100644 index 0000000..205a489 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptx new file mode 100644 index 0000000..2e1eba3 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptx diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsb b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsb new file mode 100644 index 0000000..19d6e66 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsb diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsm b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsm new file mode 100644 index 0000000..afb6f6d --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsm diff --git a/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsx b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsx new file mode 100644 index 0000000..00d5db7 --- /dev/null +++ b/tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsx diff --git a/tests/test_utils/__init__.py b/tests/test_utils/__init__.py index fca8642..c6671c7 100644 --- a/tests/test_utils/__init__.py +++ b/tests/test_utils/__init__.py @@ -1,5 +1,3 @@ -from .output_capture import OutputCapture - from os.path import dirname, join # Directory with test data, independent of current working directory diff --git a/tests/test_utils/output_capture.py b/tests/test_utils/output_capture.py deleted file mode 100644 index 0a6c6a2..0000000 --- a/tests/test_utils/output_capture.py +++ /dev/null @@ -1,83 +0,0 @@ -""" class OutputCapture to test what scripts print to stdout """ - -from __future__ import print_function -import sys -import logging - - -# python 2/3 version conflict: -if sys.version_info.major <= 2: - from StringIO import StringIO - # reload is a builtin -else: - from io import StringIO - if sys.version_info.minor < 4: - from imp import reload - else: - from importlib import reload - - -class OutputCapture: - """ context manager that captures stdout - - use as follows:: - - with OutputCapture() as capturer: - run_my_script(some_args) - - # either test line-by-line ... - for line in capturer: - some_test(line) - # ...or test all output in one go - some_test(capturer.get_data()) - - In order to solve issues with old logger instances still remembering closed - StringIO instances as "their" stdout, logging is shutdown and restarted - upon entering this Context Manager. This means that you may have to reload - your module, as well. - """ - - def __init__(self): - self.buffer = StringIO() - self.orig_stdout = None - self.data = None - - def __enter__(self): - # Avoid problems with old logger instances that still remember an old - # closed StringIO as their sys.stdout - logging.shutdown() - reload(logging) - - # replace sys.stdout with own buffer. - self.orig_stdout = sys.stdout - sys.stdout = self.buffer - return self - - def __exit__(self, exc_type, exc_value, traceback): - sys.stdout = self.orig_stdout # re-set to original - self.data = self.buffer.getvalue() - self.buffer.close() # close buffer - self.buffer = None - - if exc_type: # there has been an error - print('Got error during output capture!') - print('Print captured output and re-raise:') - for line in self.data.splitlines(): - print(line.rstrip()) # print output before re-raising - - def get_data(self): - """ retrieve all the captured data """ - if self.buffer is not None: - return self.buffer.getvalue() - elif self.data is not None: - return self.data - else: # should not be possible - raise RuntimeError('programming error or someone messed with data!') - - def __iter__(self): - for line in self.get_data().splitlines(): - yield line - - def reload_module(self, mod): - """ Wrapper around reload function for different python versions """ - return reload(mod)