Commit 91c68aab47398f6cfab50cf15b3979e04f7d4c35

Authored by kirk-sayre-work
2 parents 2d4ecbd7 33e52c57

Merge https://github.com/decalage2/oletools

Showing 106 changed files with 1581 additions and 8875 deletions
.github/ISSUE_TEMPLATE/bug_report.md 0 → 100644
  1 +---
  2 +name: Bug report
  3 +about: Create a bug report to help us fix issues
  4 +
  5 +---
  6 +
  7 +**Affected tool:**
  8 +olevba, mraptor, rtfobj, oleid, etc
  9 +
  10 +**Describe the bug**
  11 +A clear and concise description of what the bug is.
  12 +
  13 +**File/Malware sample to reproduce the bug**
  14 +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.
  15 +
  16 +**How To Reproduce the bug**
  17 +Steps to reproduce the behavior, including the full command line or the options you used.
  18 +
  19 +**Expected behavior**
  20 +A clear and concise description of what you expected to happen.
  21 +
  22 +**Console output / Screenshots**
  23 +If applicable, add screenshots to help explain your problem.
  24 +Use the option "-l debug" to add debugging information, if possible.
  25 +
  26 +**Version information:**
  27 + - OS: Windows/Linux/Mac/Other
  28 + - OS version: x.xx - 32/64 bits
  29 + - Python version: 2.7/3.6 - 32/64 bits
  30 + - oletools version:
  31 +
  32 +**Additional context**
  33 +Add any other context about the problem here.
... ...
.github/ISSUE_TEMPLATE/feature_request.md 0 → 100644
  1 +---
  2 +name: Feature request
  3 +about: Suggest an idea for this project
  4 +
  5 +---
  6 +
  7 +**Is your feature request related to a problem? Please describe.**
  8 +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
  9 +
  10 +**Describe the solution you'd like**
  11 +A clear and concise description of what you want to happen.
  12 +
  13 +**Describe alternatives you've considered**
  14 +A clear and concise description of any alternative solutions or features you've considered.
  15 +
  16 +**Additional context**
  17 +Add any other context or screenshots about the feature request here.
... ...
.travis.yml
1 1 language: python
2   -
3   -python:
4   - - "2.7"
5   - - "3.6"
6   - - "nightly"
7 2 cache: pip
  3 +sudo: false
  4 +
  5 +matrix:
  6 + include:
  7 + - python: 2.7
  8 + - python: 3.4
  9 + - python: 3.5
  10 + - python: 3.6
  11 + - python: 3.7
  12 + dist: xenial
  13 + sudo: yes
  14 + - python: nightly
  15 + dist: xenial
  16 + sudo: yes
  17 + - python: pypy
  18 + - python: pypy3
  19 +
8 20 script:
9 21 - python setup.py test
... ...
README.md
1 1 python-oletools
2 2 ===============
3   -[![PyPI](https://img.shields.io/pypi/v/oletools.svg)](https://pypi.python.org/pypi/oletools)
  3 +[![PyPI](https://img.shields.io/pypi/v/oletools.svg)](https://pypi.org/project/oletools/)
4 4 [![Build Status](https://travis-ci.org/decalage2/oletools.svg?branch=master)](https://travis-ci.org/decalage2/oletools)
  5 +[![Say Thanks!](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/decalage2)
5 6  
6 7 [oletools](http://www.decalage.info/python/oletools) is a package of python tools to analyze
7 8 [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/),
87 88 [dridex.malwareconfig.com](https://dridex.malwareconfig.com),
88 89 [Snake](https://github.com/countercept/snake),
89 90 [DARKSURGEON](https://github.com/cryps1s/DARKSURGEON),
90   -and probably [VirusTotal](https://www.virustotal.com).
  91 +[CAPE](https://github.com/ctxis/CAPE),
  92 +[AssemblyLine](https://www.cse-cst.gc.ca/en/assemblyline),
  93 +[malshare.io](https://malshare.io),
  94 +[Malware Repository Framework (MRF)](https://www.adlice.com/download/mrf/),
  95 +[malware-repo](https://github.com/Tigzy/malware-repo),
  96 +[Vba2Graph](https://github.com/MalwareCantFly/Vba2Graph),
  97 +[Strelka](https://github.com/target/strelka),
  98 +and probably [VirusTotal](https://www.virustotal.com).
  99 +And quite a few [other projects on GitHub](https://github.com/search?q=oletools&type=Repositories).
91 100 (Please [contact me]((http://decalage.info/contact)) if you have or know
92 101 a project using oletools)
93 102  
... ...
oletools/README.html
... ... @@ -17,7 +17,7 @@
17 17 </head>
18 18 <body>
19 19 <h1 id="python-oletools">python-oletools</h1>
20   -<p><a href="https://pypi.python.org/pypi/oletools"><img src="https://img.shields.io/pypi/v/oletools.svg" alt="PyPI" /></a> <a href="https://travis-ci.org/decalage2/oletools"><img src="https://travis-ci.org/decalage2/oletools.svg?branch=master" alt="Build Status" /></a></p>
  20 +<p><a href="https://pypi.org/project/oletools/"><img src="https://img.shields.io/pypi/v/oletools.svg" alt="PyPI" /></a> <a href="https://travis-ci.org/decalage2/oletools"><img src="https://travis-ci.org/decalage2/oletools.svg?branch=master" alt="Build Status" /></a></p>
21 21 <p><a href="http://www.decalage.info/python/oletools">oletools</a> is a package of python tools to analyze <a href="http://en.wikipedia.org/wiki/Compound_File_Binary_Format">Microsoft OLE2 files</a> (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 <a href="http://www.decalage.info/olefile">olefile</a> parser. See <a href="http://www.decalage.info/python/oletools" class="uri">http://www.decalage.info/python/oletools</a> for more info.</p>
22 22 <p><strong>Quick links:</strong> <a href="http://www.decalage.info/python/oletools">Home page</a> - <a href="https://github.com/decalage2/oletools/wiki/Install">Download/Install</a> - <a href="https://github.com/decalage2/oletools/wiki">Documentation</a> - <a href="https://github.com/decalage2/oletools/issues">Report Issues/Suggestions/Questions</a> - <a href="http://decalage.info/contact">Contact the Author</a> - <a href="https://github.com/decalage2/oletools">Repository</a> - <a href="https://twitter.com/decalage2">Updates on Twitter</a> <a href="https://github.com/decalage2/oletools/blob/master/cheatsheet/oletools_cheatsheet.pdf">Cheatsheet</a></p>
23 23 <p>Note: python-oletools is not related to OLETools published by BeCubed Software.</p>
... ...
oletools/README.rst
... ... @@ -240,6 +240,6 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
240 240 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
241 241  
242 242 .. |PyPI| image:: https://img.shields.io/pypi/v/oletools.svg
243   - :target: https://pypi.python.org/pypi/oletools
  243 + :target: https://pypi.org/project/oletools/
244 244 .. |Build Status| image:: https://travis-ci.org/decalage2/oletools.svg?branch=master
245 245 :target: https://travis-ci.org/decalage2/oletools
... ...
oletools/common/clsid.py
... ... @@ -43,7 +43,7 @@ http://www.decalage.info/python/oletools
43 43 # 2018-04-18 PL: - added known-bad CLSIDs from Cuckoo sandbox (issue #290)
44 44 # 2018-05-08 PL: - added more CLSIDs (issues #299, #304), merged and sorted
45 45  
46   -__version__ = '0.53'
  46 +__version__ = '0.54dev3'
47 47  
48 48  
49 49 # REFERENCES:
... ... @@ -80,12 +80,14 @@ KNOWN_CLSIDS = {
80 80 '00020900-0000-0000-C000-000000000046': 'Microsoft Word 6.0-7.0 Document (Word.Document.6)',
81 81 '00020906-0000-0000-C000-000000000046': 'Microsoft Word 97-2003 Document (Word.Document.8)',
82 82 '00020C01-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
  83 + '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
83 84 '00021700-0000-0000-C000-000000000046': 'Microsoft Equation 2.0 (Known Related to CVE-2017-11882 or CVE-2018-0802)',
84 85 '00022601-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
85 86 '00022602-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
86 87 '00022603-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
87 88 '0002CE02-0000-0000-C000-000000000046': 'Microsoft Equation 3.0 (Known Related to CVE-2017-11882 or CVE-2018-0802)',
88 89 '0002CE03-0000-0000-C000-000000000046': 'MathType Equation Object',
  90 + '0003000B-0000-0000-C000-000000000046': 'Microsoft Equation (Known Related to CVE-2017-11882 or CVE-2018-0802)',
89 91 '0003000C-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
90 92 '0003000D-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
91 93 '0003000E-0000-0000-C000-000000000046': 'OLE Package Object (may contain and run any file)',
... ...
oletools/common/errors.py 0 → 100644
  1 +"""
  2 +Errors used in several tools to avoid duplication
  3 +
  4 +.. codeauthor:: Intra2net AG <info@intra2net.com>
  5 +"""
  6 +
  7 +class FileIsEncryptedError(ValueError):
  8 + """Exception thrown if file is encrypted and cannot deal with it."""
  9 + # see also: same class in olevba[3] and record_base
  10 + def __init__(self, filename=None):
  11 + super(FileIsEncryptedError, self).__init__(
  12 + 'Office file {}is encrypted, not yet supported'
  13 + .format('' if filename is None else filename + ' '))
... ...
oletools/common/log_helper/__init__.py 0 → 100644
  1 +from . import log_helper as log_helper_
  2 +
  3 +log_helper = log_helper_.LogHelper()
  4 +
  5 +__all__ = ['log_helper']
... ...
oletools/common/log_helper/_json_formatter.py 0 → 100644
  1 +import logging
  2 +import json
  3 +
  4 +
  5 +class JsonFormatter(logging.Formatter):
  6 + """
  7 + Format every message to be logged as a JSON object
  8 + """
  9 + _is_first_line = True
  10 +
  11 + def format(self, record):
  12 + """
  13 + Since we don't buffer messages, we always prepend messages with a comma to make
  14 + the output JSON-compatible. The only exception is when printing the first line,
  15 + so we need to keep track of it.
  16 + """
  17 + json_dict = dict(msg=record.msg, level=record.levelname)
  18 + formatted_message = ' ' + json.dumps(json_dict)
  19 +
  20 + if self._is_first_line:
  21 + self._is_first_line = False
  22 + return formatted_message
  23 +
  24 + return ', ' + formatted_message
... ...
oletools/common/log_helper/_logger_adapter.py 0 → 100644
  1 +import logging
  2 +from . import _root_logger_wrapper
  3 +
  4 +
  5 +class OletoolsLoggerAdapter(logging.LoggerAdapter):
  6 + """
  7 + Adapter class for all loggers returned by the logging module.
  8 + """
  9 + _json_enabled = None
  10 +
  11 + def print_str(self, message):
  12 + """
  13 + This function replaces normal print() calls so we can format them as JSON
  14 + when needed or just print them right away otherwise.
  15 + """
  16 + if self._json_enabled and self._json_enabled():
  17 + # Messages from this function should always be printed,
  18 + # so when using JSON we log using the same level that set
  19 + self.log(_root_logger_wrapper.level(), message)
  20 + else:
  21 + print(message)
  22 +
  23 + def set_json_enabled_function(self, json_enabled):
  24 + """
  25 + Set a function to be called to check whether JSON output is enabled.
  26 + """
  27 + self._json_enabled = json_enabled
  28 +
  29 + def level(self):
  30 + return self.logger.level
... ...
oletools/common/log_helper/_root_logger_wrapper.py 0 → 100644
  1 +import logging
  2 +
  3 +
  4 +def is_logging_initialized():
  5 + """
  6 + We use the same strategy as the logging module when checking if
  7 + the logging was initialized - look for handlers in the root logger
  8 + """
  9 + return len(logging.root.handlers) > 0
  10 +
  11 +
  12 +def set_formatter(fmt):
  13 + """
  14 + Set the formatter to be used by every handler of the root logger.
  15 + """
  16 + if not is_logging_initialized():
  17 + return
  18 +
  19 + for handler in logging.root.handlers:
  20 + handler.setFormatter(fmt)
  21 +
  22 +
  23 +def level():
  24 + return logging.root.level
... ...
oletools/common/log_helper/log_helper.py 0 → 100644
  1 +"""
  2 +log_helper.py
  3 +
  4 +General logging helpers
  5 +
  6 +.. codeauthor:: Intra2net AG <info@intra2net>
  7 +"""
  8 +
  9 +# === LICENSE =================================================================
  10 +#
  11 +# Redistribution and use in source and binary forms, with or without
  12 +# modification, are permitted provided that the following conditions are met:
  13 +#
  14 +# * Redistributions of source code must retain the above copyright notice,
  15 +# this list of conditions and the following disclaimer.
  16 +# * Redistributions in binary form must reproduce the above copyright notice,
  17 +# this list of conditions and the following disclaimer in the documentation
  18 +# and/or other materials provided with the distribution.
  19 +#
  20 +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  21 +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22 +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23 +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  24 +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25 +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26 +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27 +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28 +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29 +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30 +# POSSIBILITY OF SUCH DAMAGE.
  31 +
  32 +# -----------------------------------------------------------------------------
  33 +# CHANGELOG:
  34 +# 2017-12-07 v0.01 CH: - first version
  35 +# 2018-02-05 v0.02 SA: - fixed log level selection and reformatted code
  36 +# 2018-02-06 v0.03 SA: - refactored code to deal with NullHandlers
  37 +# 2018-02-07 v0.04 SA: - fixed control of handlers propagation
  38 +# 2018-04-23 v0.05 SA: - refactored the whole logger to use an OOP approach
  39 +
  40 +# -----------------------------------------------------------------------------
  41 +# TODO:
  42 +
  43 +
  44 +from ._json_formatter import JsonFormatter
  45 +from ._logger_adapter import OletoolsLoggerAdapter
  46 +from . import _root_logger_wrapper
  47 +import logging
  48 +import sys
  49 +
  50 +
  51 +LOG_LEVELS = {
  52 + 'debug': logging.DEBUG,
  53 + 'info': logging.INFO,
  54 + 'warning': logging.WARNING,
  55 + 'error': logging.ERROR,
  56 + 'critical': logging.CRITICAL
  57 +}
  58 +
  59 +DEFAULT_LOGGER_NAME = 'oletools'
  60 +DEFAULT_MESSAGE_FORMAT = '%(levelname)-8s %(message)s'
  61 +
  62 +
  63 +class LogHelper:
  64 + def __init__(self):
  65 + self._all_names = set() # set so we do not have duplicates
  66 + self._use_json = False
  67 + self._is_enabled = False
  68 +
  69 + def get_or_create_silent_logger(self, name=DEFAULT_LOGGER_NAME, level=logging.CRITICAL + 1):
  70 + """
  71 + Get a logger or create one if it doesn't exist, setting a NullHandler
  72 + as the handler (to avoid printing to the console).
  73 + By default we also use a higher logging level so every message will
  74 + be ignored.
  75 + This will prevent oletools from logging unnecessarily when being imported
  76 + from external tools.
  77 + """
  78 + return self._get_or_create_logger(name, level, logging.NullHandler())
  79 +
  80 + def enable_logging(self, use_json, level, log_format=DEFAULT_MESSAGE_FORMAT, stream=None):
  81 + """
  82 + This function initializes the root logger and enables logging.
  83 + We set the level of the root logger to the one passed by calling logging.basicConfig.
  84 + We also set the level of every logger we created to 0 (logging.NOTSET), meaning that
  85 + the level of the root logger will be used to tell if messages should be logged.
  86 + Additionally, since our loggers use the NullHandler, they won't log anything themselves,
  87 + but due to having propagation enabled they will pass messages to the root logger,
  88 + which in turn will log to the stream set in this function.
  89 + Since the root logger is the one doing the work, when using JSON we set its formatter
  90 + so that every message logged is JSON-compatible.
  91 + """
  92 + if self._is_enabled:
  93 + raise ValueError('re-enabling logging. Not sure whether that is ok...')
  94 +
  95 + log_level = LOG_LEVELS[level]
  96 + logging.basicConfig(level=log_level, format=log_format, stream=stream)
  97 + self._is_enabled = True
  98 +
  99 + self._use_json = use_json
  100 + sys.excepthook = self._get_except_hook(sys.excepthook)
  101 +
  102 + # since there could be loggers already created we go through all of them
  103 + # and set their levels to 0 so they will use the root logger's level
  104 + for name in self._all_names:
  105 + logger = self.get_or_create_silent_logger(name)
  106 + self._set_logger_level(logger, logging.NOTSET)
  107 +
  108 + # add a JSON formatter to the root logger, which will be used by every logger
  109 + if self._use_json:
  110 + _root_logger_wrapper.set_formatter(JsonFormatter())
  111 + print('[')
  112 +
  113 + def end_logging(self):
  114 + """
  115 + Must be called at the end of the main function if the caller wants
  116 + json-compatible output
  117 + """
  118 + if not self._is_enabled:
  119 + return
  120 + self._is_enabled = False
  121 +
  122 + # end logging
  123 + self._all_names = set()
  124 + logging.shutdown()
  125 +
  126 + # end json list
  127 + if self._use_json:
  128 + print(']')
  129 + self._use_json = False
  130 +
  131 + def _get_except_hook(self, old_hook):
  132 + """
  133 + Global hook for exceptions so we can always end logging.
  134 + We wrap any hook currently set to avoid overwriting global hooks set by oletools.
  135 + Note that this is only called by enable_logging, which in turn is called by
  136 + the main() function in oletools' scripts. When scripts are being imported this
  137 + code won't execute and won't affect global hooks.
  138 + """
  139 + def hook(exctype, value, traceback):
  140 + self.end_logging()
  141 + old_hook(exctype, value, traceback)
  142 +
  143 + return hook
  144 +
  145 + def _get_or_create_logger(self, name, level, handler=None):
  146 + """
  147 + Get or create a new logger. This newly created logger will have the
  148 + handler and level that was passed, but if it already exists it's not changed.
  149 + We also wrap the logger in an adapter so we can easily extend its functionality.
  150 + """
  151 +
  152 + # logging.getLogger creates a logger if it doesn't exist,
  153 + # so we need to check before calling it
  154 + if handler and not self._log_exists(name):
  155 + logger = logging.getLogger(name)
  156 + logger.addHandler(handler)
  157 + self._set_logger_level(logger, level)
  158 + else:
  159 + logger = logging.getLogger(name)
  160 +
  161 + # Keep track of every logger we created so we can easily change
  162 + # their levels whenever needed
  163 + self._all_names.add(name)
  164 +
  165 + adapted_logger = OletoolsLoggerAdapter(logger, None)
  166 + adapted_logger.set_json_enabled_function(lambda: self._use_json)
  167 +
  168 + return adapted_logger
  169 +
  170 + @staticmethod
  171 + def _set_logger_level(logger, level):
  172 + """
  173 + If the logging is already initialized, we set the level of our logger
  174 + to 0, meaning that it will reuse the level of the root logger.
  175 + That means that if the root logger level changes, we will keep using
  176 + its level and not logging unnecessarily.
  177 + """
  178 +
  179 + # if this log was wrapped, unwrap it to set the level
  180 + if isinstance(logger, OletoolsLoggerAdapter):
  181 + logger = logger.logger
  182 +
  183 + if _root_logger_wrapper.is_logging_initialized():
  184 + logger.setLevel(logging.NOTSET)
  185 + else:
  186 + logger.setLevel(level)
  187 +
  188 + @staticmethod
  189 + def _log_exists(name):
  190 + """
  191 + We check the log manager instead of our global _all_names variable
  192 + since the logger could have been created outside of the helper
  193 + """
  194 + return name in logging.Logger.manager.loggerDict
... ...
oletools/ezhexviewer.py
... ... @@ -48,8 +48,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 48 # 2016-10-26 PL: - fixed to run on Python 2+3
49 49 # 2017-03-23 v0.51 PL: - fixed display of control characters (issue #151)
50 50 # 2017-04-26 PL: - fixed absolute imports (issue #141)
  51 +# 2018-09-15 v0.54 PL: - easygui is now a dependency
51 52  
52   -__version__ = '0.51'
  53 +__version__ = '0.54dev1'
53 54  
54 55 #-----------------------------------------------------------------------------
55 56 # TODO:
... ... @@ -71,7 +72,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
71 72 if not _parent_dir in sys.path:
72 73 sys.path.insert(0, _parent_dir)
73 74  
74   -from oletools.thirdparty.easygui import easygui
  75 +import easygui
75 76  
76 77 # === PYTHON 2+3 SUPPORT ======================================================
77 78  
... ...
oletools/mraptor_milter.py
... ... @@ -405,7 +405,7 @@ if __name__ == &quot;__main__&quot;:
405 405 daemon.start()
406 406  
407 407 # Using python-daemon - Does not work as-is, need to create the PID file
408   - # See https://pypi.python.org/pypi/python-daemon/
  408 + # See https://pypi.org/project/python-daemon/
409 409 # See PEP-3143: https://www.python.org/dev/peps/pep-3143/
410 410 # import daemon
411 411 # import lockfile
... ...
oletools/msodde.py
... ... @@ -11,6 +11,7 @@ Supported formats:
11 11 - RTF
12 12 - CSV (exported from / imported into Excel)
13 13 - XML (exported from Word 2003, Word 2007+, Excel 2003, (Excel 2007+?)
  14 +- raises an error if run with files encrypted using MS Crypto API RC4
14 15  
15 16 Author: Philippe Lagadec - http://www.decalage.info
16 17 License: BSD, see source code or documentation
... ... @@ -53,25 +54,17 @@ import argparse
53 54 import os
54 55 from os.path import abspath, dirname
55 56 import sys
56   -import json
57   -import logging
58 57 import re
59 58 import csv
60 59  
61   -# little hack to allow absolute imports even if oletools is not installed
62   -# Copied from olevba.py
63   -try:
64   - from oletools.thirdparty import olefile
65   -except ImportError:
66   - PARENT_DIR = dirname(dirname(abspath(__file__)))
67   - if PARENT_DIR not in sys.path:
68   - sys.path.insert(0, PARENT_DIR)
69   - del PARENT_DIR
70   - from oletools.thirdparty import olefile
  60 +import olefile
71 61  
72 62 from oletools import ooxml
73 63 from oletools import xls_parser
74 64 from oletools import rtfobj
  65 +from oletools import oleid
  66 +from oletools.common.log_helper import log_helper
  67 +from oletools.common.errors import FileIsEncryptedError
75 68  
76 69 # -----------------------------------------------------------------------------
77 70 # CHANGELOG:
... ... @@ -93,8 +86,10 @@ from oletools import rtfobj
93 86 # 2018-01-11 PL: - fixed issue #242 (apply unquote to fldSimple tags)
94 87 # 2018-01-10 CH: - add single-xml files (Word 2003/2007+ / Excel 2003)
95 88 # 2018-03-21 CH: - added detection for various CSV formulas (issue #259)
  89 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  90 +# 2018-10-25 CH: - detect encryption and raise error if detected
96 91  
97   -__version__ = '0.53'
  92 +__version__ = '0.54dev4'
98 93  
99 94 # -----------------------------------------------------------------------------
100 95 # TODO: field codes can be in headers/footers/comments - parse these
... ... @@ -220,63 +215,12 @@ THIS IS WORK IN PROGRESS - Check updates regularly!
220 215 Please report any issue at https://github.com/decalage2/oletools/issues
221 216 """ % __version__
222 217  
223   -BANNER_JSON = dict(type='meta', version=__version__, name='msodde',
224   - link='http://decalage.info/python/oletools',
225   - message='THIS IS WORK IN PROGRESS - Check updates regularly! '
226   - 'Please report any issue at '
227   - 'https://github.com/decalage2/oletools/issues')
228   -
229 218 # === LOGGING =================================================================
230 219  
231 220 DEFAULT_LOG_LEVEL = "warning" # Default log level
232   -LOG_LEVELS = {
233   - 'debug': logging.DEBUG,
234   - 'info': logging.INFO,
235   - 'warning': logging.WARNING,
236   - 'error': logging.ERROR,
237   - 'critical': logging.CRITICAL
238   -}
239   -
240   -
241   -class NullHandler(logging.Handler):
242   - """
243   - Log Handler without output, to avoid printing messages if logging is not
244   - configured by the main application.
245   - Python 2.7 has logging.NullHandler, but this is necessary for 2.6:
246   - see https://docs.python.org/2.6/library/logging.html#configuring-logging-for-a-library
247   - """
248   - def emit(self, record):
249   - pass
250   -
251   -
252   -def get_logger(name, level=logging.CRITICAL+1):
253   - """
254   - Create a suitable logger object for this module.
255   - The goal is not to change settings of the root logger, to avoid getting
256   - other modules' logs on the screen.
257   - If a logger exists with same name, reuse it. (Else it would have duplicate
258   - handlers and messages would be doubled.)
259   - The level is set to CRITICAL+1 by default, to avoid any logging.
260   - """
261   - # First, test if there is already a logger with the same name, else it
262   - # will generate duplicate messages (due to duplicate handlers):
263   - if name in logging.Logger.manager.loggerDict:
264   - # NOTE: another less intrusive but more "hackish" solution would be to
265   - # use getLogger then test if its effective level is not default.
266   - logger = logging.getLogger(name)
267   - # make sure level is OK:
268   - logger.setLevel(level)
269   - return logger
270   - # get a new logger:
271   - logger = logging.getLogger(name)
272   - # only add a NullHandler for this logger, it is up to the application
273   - # to configure its own logging:
274   - logger.addHandler(NullHandler())
275   - logger.setLevel(level)
276   - return logger
277 221  
278 222 # a global logger object used for debugging:
279   -log = get_logger('msodde')
  223 +logger = log_helper.get_or_create_silent_logger('msodde')
280 224  
281 225  
282 226 # === UNICODE IN PY2 =========================================================
... ... @@ -320,7 +264,7 @@ def ensure_stdout_handles_unicode():
320 264 encoding = 'utf8'
321 265  
322 266 # logging is probably not initialized yet, but just in case
323   - log.debug('wrapping sys.stdout with encoder using {0}'.format(encoding))
  267 + logger.debug('wrapping sys.stdout with encoder using {0}'.format(encoding))
324 268  
325 269 wrapper = codecs.getwriter(encoding)
326 270 sys.stdout = wrapper(sys.stdout)
... ... @@ -404,7 +348,7 @@ def process_doc_field(data):
404 348 """ check if field instructions start with DDE
405 349  
406 350 expects unicode input, returns unicode output (empty if not dde) """
407   - log.debug('processing field {0}'.format(data))
  351 + logger.debug('processing field {0}'.format(data))
408 352  
409 353 if data.lstrip().lower().startswith(u'dde'):
410 354 return data
... ... @@ -442,7 +386,7 @@ def process_doc_stream(stream):
442 386  
443 387 if char == OLE_FIELD_START:
444 388 if have_start and max_size_exceeded:
445   - log.debug('big field was not a field after all')
  389 + logger.debug('big field was not a field after all')
446 390 have_start = True
447 391 have_sep = False
448 392 max_size_exceeded = False
... ... @@ -454,7 +398,7 @@ def process_doc_stream(stream):
454 398 # now we are after start char but not at end yet
455 399 if char == OLE_FIELD_SEP:
456 400 if have_sep:
457   - log.debug('unexpected field: has multiple separators!')
  401 + logger.debug('unexpected field: has multiple separators!')
458 402 have_sep = True
459 403 elif char == OLE_FIELD_END:
460 404 # have complete field now, process it
... ... @@ -472,7 +416,7 @@ def process_doc_stream(stream):
472 416 if max_size_exceeded:
473 417 pass
474 418 elif len(field_contents) > OLE_FIELD_MAX_SIZE:
475   - log.debug('field exceeds max size of {0}. Ignore rest'
  419 + logger.debug('field exceeds max size of {0}. Ignore rest'
476 420 .format(OLE_FIELD_MAX_SIZE))
477 421 max_size_exceeded = True
478 422  
... ... @@ -490,25 +434,26 @@ def process_doc_stream(stream):
490 434 field_contents += u'?'
491 435  
492 436 if max_size_exceeded:
493   - log.debug('big field was not a field after all')
  437 + logger.debug('big field was not a field after all')
494 438  
495   - log.debug('Checked {0} characters, found {1} fields'
  439 + logger.debug('Checked {0} characters, found {1} fields'
496 440 .format(idx, len(result_parts)))
497 441  
498 442 return result_parts
499 443  
500 444  
501   -def process_doc(filepath):
  445 +def process_doc(ole):
502 446 """
503 447 find dde links in word ole (.doc/.dot) file
504 448  
  449 + Checks whether files is ppt and returns empty immediately in that case
  450 + (ppt files cannot contain DDE-links to my knowledge)
  451 +
505 452 like process_xml, returns a concatenated unicode string of dde links or
506 453 empty if none were found. dde-links will still begin with the dde[auto] key
507 454 word (possibly after some whitespace)
508 455 """
509   - log.debug('process_doc')
510   - ole = olefile.OleFileIO(filepath, path_encoding=None)
511   -
  456 + logger.debug('process_doc')
512 457 links = []
513 458 for sid, direntry in enumerate(ole.direntries):
514 459 is_orphan = direntry is None
... ... @@ -516,7 +461,7 @@ def process_doc(filepath):
516 461 # this direntry is not part of the tree --> unused or orphan
517 462 direntry = ole._load_direntry(sid)
518 463 is_stream = direntry.entry_type == olefile.STGTY_STREAM
519   - log.debug('direntry {:2d} {}: {}'
  464 + logger.debug('direntry {:2d} {}: {}'
520 465 .format(sid, '[orphan]' if is_orphan else direntry.name,
521 466 'is stream of size {}'.format(direntry.size)
522 467 if is_stream else
... ... @@ -601,7 +546,7 @@ def process_docx(filepath, field_filter_mode=None):
601 546 ddetext += unquote(elem.text)
602 547  
603 548 # apply field command filter
604   - log.debug('filtering with mode "{0}"'.format(field_filter_mode))
  549 + logger.debug('filtering with mode "{0}"'.format(field_filter_mode))
605 550 if field_filter_mode in (FIELD_FILTER_ALL, None):
606 551 clean_fields = all_fields
607 552 elif field_filter_mode == FIELD_FILTER_DDE:
... ... @@ -660,7 +605,7 @@ def field_is_blacklisted(contents):
660 605 index = FIELD_BLACKLIST_CMDS.index(words[0].lower())
661 606 except ValueError: # first word is no blacklisted command
662 607 return False
663   - log.debug('trying to match "{0}" to blacklist command {1}'
  608 + logger.debug('trying to match "{0}" to blacklist command {1}'
664 609 .format(contents, FIELD_BLACKLIST[index]))
665 610 _, nargs_required, nargs_optional, sw_with_arg, sw_solo, sw_format \
666 611 = FIELD_BLACKLIST[index]
... ... @@ -672,11 +617,11 @@ def field_is_blacklisted(contents):
672 617 break
673 618 nargs += 1
674 619 if nargs < nargs_required:
675   - log.debug('too few args: found {0}, but need at least {1} in "{2}"'
  620 + logger.debug('too few args: found {0}, but need at least {1} in "{2}"'
676 621 .format(nargs, nargs_required, contents))
677 622 return False
678 623 elif nargs > nargs_required + nargs_optional:
679   - log.debug('too many args: found {0}, but need at most {1}+{2} in "{3}"'
  624 + logger.debug('too many args: found {0}, but need at most {1}+{2} in "{3}"'
680 625 .format(nargs, nargs_required, nargs_optional, contents))
681 626 return False
682 627  
... ... @@ -686,14 +631,14 @@ def field_is_blacklisted(contents):
686 631 for word in words[1+nargs:]:
687 632 if expect_arg: # this is an argument for the last switch
688 633 if arg_choices and (word not in arg_choices):
689   - log.debug('Found invalid switch argument "{0}" in "{1}"'
  634 + logger.debug('Found invalid switch argument "{0}" in "{1}"'
690 635 .format(word, contents))
691 636 return False
692 637 expect_arg = False
693 638 arg_choices = [] # in general, do not enforce choices
694 639 continue # "no further questions, your honor"
695 640 elif not FIELD_SWITCH_REGEX.match(word):
696   - log.debug('expected switch, found "{0}" in "{1}"'
  641 + logger.debug('expected switch, found "{0}" in "{1}"'
697 642 .format(word, contents))
698 643 return False
699 644 # we want a switch and we got a valid one
... ... @@ -715,7 +660,7 @@ def field_is_blacklisted(contents):
715 660 if 'numeric' in sw_format:
716 661 arg_choices = [] # too many choices to list them here
717 662 else:
718   - log.debug('unexpected switch {0} in "{1}"'
  663 + logger.debug('unexpected switch {0} in "{1}"'
719 664 .format(switch, contents))
720 665 return False
721 666  
... ... @@ -741,11 +686,11 @@ def process_xlsx(filepath):
741 686 # binary parts, e.g. contained in .xlsb
742 687 for subfile, content_type, handle in parser.iter_non_xml():
743 688 try:
744   - logging.info('Parsing non-xml subfile {0} with content type {1}'
  689 + logger.info('Parsing non-xml subfile {0} with content type {1}'
745 690 .format(subfile, content_type))
746 691 for record in xls_parser.parse_xlsb_part(handle, content_type,
747 692 subfile):
748   - logging.debug('{0}: {1}'.format(subfile, record))
  693 + logger.debug('{0}: {1}'.format(subfile, record))
749 694 if isinstance(record, xls_parser.XlsbBeginSupBook) and \
750 695 record.link_type == \
751 696 xls_parser.XlsbBeginSupBook.LINK_TYPE_DDE:
... ... @@ -755,16 +700,16 @@ def process_xlsx(filepath):
755 700 if content_type.startswith('application/vnd.ms-excel.') or \
756 701 content_type.startswith('application/vnd.ms-office.'): # pylint: disable=bad-indentation
757 702 # should really be able to parse these either as xml or records
758   - log_func = logging.warning
  703 + log_func = logger.warning
759 704 elif content_type.startswith('image/') or content_type == \
760 705 'application/vnd.openxmlformats-officedocument.' + \
761 706 'spreadsheetml.printerSettings':
762 707 # understandable that these are not record-base
763   - log_func = logging.debug
  708 + log_func = logger.debug
764 709 else: # default
765   - log_func = logging.info
766   - log_func('Failed to parse {0} of content type {1}'
767   - .format(subfile, content_type))
  710 + log_func = logger.info
  711 + log_func('Failed to parse {0} of content type {1} ("{2}")'
  712 + .format(subfile, content_type, str(exc)))
768 713 # in any case: continue with next
769 714  
770 715 return u'\n'.join(dde_links)
... ... @@ -782,15 +727,15 @@ class RtfFieldParser(rtfobj.RtfParser):
782 727  
783 728 def open_destination(self, destination):
784 729 if destination.cword == b'fldinst':
785   - log.debug('*** Start field data at index %Xh' % destination.start)
  730 + logger.debug('*** Start field data at index %Xh' % destination.start)
786 731  
787 732 def close_destination(self, destination):
788 733 if destination.cword == b'fldinst':
789   - log.debug('*** Close field data at index %Xh' % self.index)
790   - log.debug('Field text: %r' % destination.data)
  734 + logger.debug('*** Close field data at index %Xh' % self.index)
  735 + logger.debug('Field text: %r' % destination.data)
791 736 # remove extra spaces and newline chars:
792 737 field_clean = destination.data.translate(None, b'\r\n').strip()
793   - log.debug('Cleaned Field text: %r' % field_clean)
  738 + logger.debug('Cleaned Field text: %r' % field_clean)
794 739 self.fields.append(field_clean)
795 740  
796 741 def control_symbol(self, matchobject):
... ... @@ -812,7 +757,7 @@ def process_rtf(file_handle, field_filter_mode=None):
812 757 rtfparser.parse()
813 758 all_fields = [field.decode('ascii') for field in rtfparser.fields]
814 759 # apply field command filter
815   - log.debug('found {1} fields, filtering with mode "{0}"'
  760 + logger.debug('found {1} fields, filtering with mode "{0}"'
816 761 .format(field_filter_mode, len(all_fields)))
817 762 if field_filter_mode in (FIELD_FILTER_ALL, None):
818 763 clean_fields = all_fields
... ... @@ -861,7 +806,7 @@ def process_csv(filepath):
861 806  
862 807 if is_small and not results:
863 808 # easy to mis-sniff small files. Try different delimiters
864   - log.debug('small file, no results; try all delimiters')
  809 + logger.debug('small file, no results; try all delimiters')
865 810 file_handle.seek(0)
866 811 other_delim = CSV_DELIMITERS.replace(dialect.delimiter, '')
867 812 for delim in other_delim:
... ... @@ -869,12 +814,12 @@ def process_csv(filepath):
869 814 file_handle.seek(0)
870 815 results, _ = process_csv_dialect(file_handle, delim)
871 816 except csv.Error: # e.g. sniffing fails
872   - log.debug('failed to csv-parse with delimiter {0!r}'
  817 + logger.debug('failed to csv-parse with delimiter {0!r}'
873 818 .format(delim))
874 819  
875 820 if is_small and not results:
876 821 # try whole file as single cell, since sniffing fails in this case
877   - log.debug('last attempt: take whole file as single unquoted cell')
  822 + logger.debug('last attempt: take whole file as single unquoted cell')
878 823 file_handle.seek(0)
879 824 match = CSV_DDE_FORMAT.match(file_handle.read(CSV_SMALL_THRESH))
880 825 if match:
... ... @@ -890,7 +835,7 @@ def process_csv_dialect(file_handle, delimiters):
890 835 dialect = csv.Sniffer().sniff(file_handle.read(CSV_SMALL_THRESH),
891 836 delimiters=delimiters)
892 837 dialect.strict = False # microsoft is never strict
893   - log.debug('sniffed csv dialect with delimiter {0!r} '
  838 + logger.debug('sniffed csv dialect with delimiter {0!r} '
894 839 'and quote char {1!r}'
895 840 .format(dialect.delimiter, dialect.quotechar))
896 841  
... ... @@ -932,7 +877,7 @@ def process_excel_xml(filepath):
932 877 break
933 878 if formula is None:
934 879 continue
935   - log.debug('found cell with formula {0}'.format(formula))
  880 + logger.debug('found cell with formula {0}'.format(formula))
936 881 match = re.match(XML_DDE_FORMAT, formula)
937 882 if match:
938 883 dde_links.append(u' '.join(match.groups()[:2]))
... ... @@ -942,40 +887,51 @@ def process_excel_xml(filepath):
942 887 def process_file(filepath, field_filter_mode=None):
943 888 """ decides which of the process_* functions to call """
944 889 if olefile.isOleFile(filepath):
945   - log.debug('Is OLE. Checking streams to see whether this is xls')
  890 + logger.debug('Is OLE. Checking streams to see whether this is xls')
946 891 if xls_parser.is_xls(filepath):
947   - log.debug('Process file as excel 2003 (xls)')
  892 + logger.debug('Process file as excel 2003 (xls)')
948 893 return process_xls(filepath)
  894 +
  895 + # encrypted files also look like ole, even if office 2007+ (xml-based)
  896 + # so check for encryption, first
  897 + ole = olefile.OleFileIO(filepath, path_encoding=None)
  898 + oid = oleid.OleID(ole)
  899 + if oid.check_encrypted().value:
  900 + log.debug('is encrypted - raise error')
  901 + raise FileIsEncryptedError(filepath)
  902 + elif oid.check_powerpoint().value:
  903 + log.debug('is ppt - cannot have DDE')
  904 + return u''
949 905 else:
950   - log.debug('Process file as word 2003 (doc)')
951   - return process_doc(filepath)
  906 + logger.debug('Process file as word 2003 (doc)')
  907 + return process_doc(ole)
952 908  
953 909 with open(filepath, 'rb') as file_handle:
954 910 if file_handle.read(4) == RTF_START:
955   - log.debug('Process file as rtf')
  911 + logger.debug('Process file as rtf')
956 912 return process_rtf(file_handle, field_filter_mode)
957 913  
958 914 try:
959 915 doctype = ooxml.get_type(filepath)
960   - log.debug('Detected file type: {0}'.format(doctype))
  916 + logger.debug('Detected file type: {0}'.format(doctype))
961 917 except Exception as exc:
962   - log.debug('Exception trying to xml-parse file: {0}'.format(exc))
  918 + logger.debug('Exception trying to xml-parse file: {0}'.format(exc))
963 919 doctype = None
964 920  
965 921 if doctype == ooxml.DOCTYPE_EXCEL:
966   - log.debug('Process file as excel 2007+ (xlsx)')
  922 + logger.debug('Process file as excel 2007+ (xlsx)')
967 923 return process_xlsx(filepath)
968 924 elif doctype in (ooxml.DOCTYPE_EXCEL_XML, ooxml.DOCTYPE_EXCEL_XML2003):
969   - log.debug('Process file as xml from excel 2003/2007+')
  925 + logger.debug('Process file as xml from excel 2003/2007+')
970 926 return process_excel_xml(filepath)
971 927 elif doctype in (ooxml.DOCTYPE_WORD_XML, ooxml.DOCTYPE_WORD_XML2003):
972   - log.debug('Process file as xml from word 2003/2007+')
  928 + logger.debug('Process file as xml from word 2003/2007+')
973 929 return process_docx(filepath)
974 930 elif doctype is None:
975   - log.debug('Process file as csv')
  931 + logger.debug('Process file as csv')
976 932 return process_csv(filepath)
977 933 else: # could be docx; if not: this is the old default code path
978   - log.debug('Process file as word 2007+ (docx)')
  934 + logger.debug('Process file as word 2007+ (docx)')
979 935 return process_docx(filepath, field_filter_mode)
980 936  
981 937  
... ... @@ -993,27 +949,14 @@ def main(cmd_line_args=None):
993 949 # Setup logging to the console:
994 950 # here we use stdout instead of stderr by default, so that the output
995 951 # can be redirected properly.
996   - logging.basicConfig(level=LOG_LEVELS[args.loglevel], stream=sys.stdout,
997   - format='%(levelname)-8s %(message)s')
998   - # enable logging in the modules:
999   - log.setLevel(logging.NOTSET)
1000   -
1001   - if args.json and args.loglevel.lower() == 'debug':
1002   - log.warning('Debug log output will not be json-compatible!')
  952 + log_helper.enable_logging(args.json, args.loglevel, stream=sys.stdout)
1003 953  
1004 954 if args.nounquote:
1005 955 global NO_QUOTES
1006 956 NO_QUOTES = True
1007 957  
1008   - if args.json:
1009   - jout = []
1010   - jout.append(BANNER_JSON)
1011   - else:
1012   - # print banner with version
1013   - print(BANNER)
1014   -
1015   - if not args.json:
1016   - print('Opening file: %s' % args.filepath)
  958 + logger.print_str(BANNER)
  959 + logger.print_str('Opening file: %s' % args.filepath)
1017 960  
1018 961 text = ''
1019 962 return_code = 1
... ... @@ -1021,22 +964,12 @@ def main(cmd_line_args=None):
1021 964 text = process_file(args.filepath, args.field_filter_mode)
1022 965 return_code = 0
1023 966 except Exception as exc:
1024   - if args.json:
1025   - jout.append(dict(type='error', error=type(exc).__name__,
1026   - message=str(exc)))
1027   - else:
1028   - raise # re-raise last known exception, keeping trace intact
1029   -
1030   - if args.json:
1031   - for line in text.splitlines():
1032   - if line.strip():
1033   - jout.append(dict(type='dde-link', link=line.strip()))
1034   - json.dump(jout, sys.stdout, check_circular=False, indent=4)
1035   - print() # add a newline after closing "]"
1036   - return return_code # required if we catch an exception in json-mode
1037   - else:
1038   - print ('DDE Links:')
1039   - print(text)
  967 + logger.exception(exc.message)
  968 +
  969 + logger.print_str('DDE Links:')
  970 + logger.print_str(text)
  971 +
  972 + log_helper.end_logging()
1040 973  
1041 974 return return_code
1042 975  
... ...
oletools/olebrowse.py
... ... @@ -41,8 +41,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 41 # 2012-09-17 v0.01 PL: - first version
42 42 # 2014-11-29 v0.02 PL: - use olefile instead of OleFileIO_PL
43 43 # 2017-04-26 v0.51 PL: - fixed absolute imports (issue #141)
  44 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
44 45  
45   -__version__ = '0.51'
  46 +__version__ = '0.54dev1'
46 47  
47 48 #------------------------------------------------------------------------------
48 49 # TODO:
... ... @@ -68,8 +69,8 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
68 69 if not _parent_dir in sys.path:
69 70 sys.path.insert(0, _parent_dir)
70 71  
71   -from oletools.thirdparty.easygui import easygui
72   -from oletools.thirdparty import olefile
  72 +import easygui
  73 +import olefile
73 74 from oletools import ezhexviewer
74 75  
75 76 ABOUT = '~ About olebrowse'
... ...
oletools/oledir.py
... ... @@ -50,8 +50,10 @@ from __future__ import print_function
50 50 # - added support for zip files and wildcards
51 51 # 2018-04-11 v0.53 PL: - added table displaying storage tree and CLSIDs
52 52 # 2018-04-13 PL: - moved KNOWN_CLSIDS to common.clsid
  53 +# 2018-08-28 v0.54 PL: - olefile is now a dependency
  54 +# 2018-10-06 - colorclass is now a dependency
53 55  
54   -__version__ = '0.53'
  56 +__version__ = '0.54dev1'
55 57  
56 58 #------------------------------------------------------------------------------
57 59 # TODO:
... ... @@ -62,6 +64,13 @@ __version__ = &#39;0.53&#39;
62 64  
63 65 import sys, os, optparse
64 66  
  67 +import olefile
  68 +import colorclass
  69 +
  70 +# On Windows, colorclass needs to be enabled:
  71 +if os.name == 'nt':
  72 + colorclass.Windows.enable(auto_colors=True)
  73 +
65 74 # IMPORTANT: it should be possible to run oletools directly as scripts
66 75 # in any directory without installing them with pip or setup.py.
67 76 # In that case, relative imports are NOT usable.
... ... @@ -74,20 +83,6 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
74 83 if not _parent_dir in sys.path:
75 84 sys.path.insert(0, _parent_dir)
76 85  
77   -# we also need the thirdparty dir for colorclass
78   -# TODO: remove colorclass from thirdparty, make it a dependency
79   -_thirdparty_dir = os.path.normpath(os.path.join(_thismodule_dir, 'thirdparty'))
80   -# print('_thirdparty_dir = %r' % _thirdparty_dir)
81   -if not _thirdparty_dir in sys.path:
82   - sys.path.insert(0, _thirdparty_dir)
83   -
84   -import colorclass
85   -
86   -# On Windows, colorclass needs to be enabled:
87   -if os.name == 'nt':
88   - colorclass.Windows.enable(auto_colors=True)
89   -
90   -from oletools.thirdparty import olefile
91 86 from oletools.thirdparty.tablestream import tablestream
92 87 from oletools.thirdparty.xglob import xglob
93 88 from oletools.common.clsid import KNOWN_CLSIDS
... ... @@ -236,6 +231,35 @@ def main():
236 231 # t.add_row((id, status, entry_type, name, left, right, child, hex(d.isectStart), d.size))
237 232 table.write_row((id, status, entry_type, name, left, right, child, '%X' % d.isectStart, d.size),
238 233 colors=(None, status_color, etype_color, None, None, None, None, None, None))
  234 +
  235 + table = tablestream.TableStream(column_width=[4, 28, 6, 38],
  236 + header_row=('id', 'Name', 'Size', 'CLSID'),
  237 + style=tablestream.TableStyleSlim)
  238 + rootname = ole.get_rootentry_name()
  239 + entry_id = 0
  240 + clsid = ole.root.clsid
  241 + clsid_text, clsid_color = clsid_display(clsid)
  242 + table.write_row((entry_id, rootname, '-', clsid_text),
  243 + colors=(None, 'cyan', None, clsid_color))
  244 + for entry in sorted(ole.listdir(storages=True)):
  245 + name = entry[-1]
  246 + # handle non-printable chars using repr(), remove quotes:
  247 + name = repr(name)[1:-1]
  248 + name_color = None
  249 + if ole.get_type(entry) in (olefile.STGTY_STORAGE, olefile.STGTY_ROOT):
  250 + name_color = 'cyan'
  251 + indented_name = ' '*(len(entry)-1) + name
  252 + entry_id = ole._find(entry)
  253 + try:
  254 + size = ole.get_size(entry)
  255 + except:
  256 + size = '-'
  257 + clsid = ole.getclsid(entry)
  258 + clsid_text, clsid_color = clsid_display(clsid)
  259 + table.write_row((entry_id, indented_name, size, clsid_text),
  260 + colors=(None, name_color, None, clsid_color))
  261 +
  262 +
239 263 ole.close()
240 264 # print t
241 265  
... ...
oletools/oleform.py
... ... @@ -114,8 +114,6 @@ class ExtendedStream(object):
114 114  
115 115 @classmethod
116 116 def open(cls, ole_file, path):
117   - # import oletools.thirdparty.olefile as olefile
118   - # olefile.enable_logging()
119 117 stream = ole_file.openstream(path)
120 118 # print('Opening OLE stream %r - size: %d' % (path, stream.size))
121 119 # print('declared size: %d' % ole_file.get_size(path))
... ...
oletools/oleid.py
... ... @@ -6,9 +6,8 @@ oleid is a script to analyze OLE files such as MS Office documents (e.g. Word,
6 6 Excel), to detect specific characteristics that could potentially indicate that
7 7 the file is suspicious or malicious, in terms of security (e.g. malware).
8 8 For example it can detect VBA macros, embedded Flash objects, fragmentation.
9   -The results can be displayed or returned as XML for further processing.
10   -
11   -Usage: oleid.py <file>
  9 +The results is displayed as ascii table (but could be returned or printed in
  10 +other formats like CSV, XML or JSON in future).
12 11  
13 12 oleid project website: http://www.decalage.info/python/oleid
14 13  
... ... @@ -21,8 +20,8 @@ http://www.decalage.info/python/oletools
21 20 # oleid is copyright (c) 2012-2018, Philippe Lagadec (http://www.decalage.info)
22 21 # All rights reserved.
23 22 #
24   -# Redistribution and use in source and binary forms, with or without modification,
25   -# are permitted provided that the following conditions are met:
  23 +# Redistribution and use in source and binary forms, with or without
  24 +# modification, are permitted provided that the following conditions are met:
26 25 #
27 26 # * Redistributions of source code must retain the above copyright notice, this
28 27 # list of conditions and the following disclaimer.
... ... @@ -30,16 +29,17 @@ http://www.decalage.info/python/oletools
30 29 # this list of conditions and the following disclaimer in the documentation
31 30 # and/or other materials provided with the distribution.
32 31 #
33   -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
34   -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
35   -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36   -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
37   -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38   -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
39   -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
41   -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
42   -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32 +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  33 +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  34 +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35 +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  36 +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  37 +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  38 +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  39 +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  40 +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41 +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  42 +# POSSIBILITY OF SUCH DAMAGE.
43 43  
44 44 # To improve Python 2+3 compatibility:
45 45 from __future__ import print_function
... ... @@ -55,8 +55,11 @@ from __future__ import print_function
55 55 # 2016-12-12 v0.51 PL: - fixed relative imports for Python 3 (issue #115)
56 56 # 2017-04-26 PL: - fixed absolute imports (issue #141)
57 57 # 2017-09-01 SA: - detect OpenXML encryption
  58 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  59 +# 2018-10-19 CH: - accept olefile as well as filename, return Indicators,
  60 +# improve encryption detection for ppt
58 61  
59   -__version__ = '0.53'
  62 +__version__ = '0.54dev4'
60 63  
61 64  
62 65 #------------------------------------------------------------------------------
... ... @@ -77,28 +80,27 @@ __version__ = &#39;0.53&#39;
77 80  
78 81 #=== IMPORTS =================================================================
79 82  
80   -import optparse, sys, os, re, zlib, struct
  83 +import argparse, sys, re, zlib, struct
  84 +from os.path import dirname, abspath
81 85  
82   -# IMPORTANT: it should be possible to run oletools directly as scripts
83   -# in any directory without installing them with pip or setup.py.
84   -# In that case, relative imports are NOT usable.
85   -# And to enable Python 2+3 compatibility, we need to use absolute imports,
86   -# so we add the oletools parent folder to sys.path (absolute+normalized path):
87   -_thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
88   -# print('_thismodule_dir = %r' % _thismodule_dir)
89   -_parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..'))
90   -# print('_parent_dir = %r' % _thirdparty_dir)
91   -if not _parent_dir in sys.path:
92   - sys.path.insert(0, _parent_dir)
  86 +# little hack to allow absolute imports even if oletools is not installed
  87 +# (required to run oletools directly as scripts in any directory).
  88 +try:
  89 + from oletools.thirdparty import prettytable
  90 +except ImportError:
  91 + PARENT_DIR = dirname(dirname(abspath(__file__)))
  92 + if PARENT_DIR not in sys.path:
  93 + sys.path.insert(0, PARENT_DIR)
  94 + del PARENT_DIR
  95 + from oletools.thirdparty import prettytable
93 96  
94   -from oletools.thirdparty import olefile
95   -from oletools.thirdparty.prettytable import prettytable
  97 +import olefile
96 98  
97 99  
98 100  
99 101 #=== FUNCTIONS ===============================================================
100 102  
101   -def detect_flash (data):
  103 +def detect_flash(data):
102 104 """
103 105 Detect Flash objects (SWF files) within a binary string of data
104 106 return a list of (start_index, length, compressed) tuples, or [] if nothing
... ... @@ -140,7 +142,7 @@ def detect_flash (data):
140 142 compressed_data = swf[8:]
141 143 try:
142 144 zlib.decompress(compressed_data)
143   - except:
  145 + except Exception:
144 146 continue
145 147 # else we don't check anything at this stage, we only assume it is a
146 148 # valid SWF. So there might be false positives for uncompressed SWF.
... ... @@ -151,9 +153,15 @@ def detect_flash (data):
151 153  
152 154 #=== CLASSES =================================================================
153 155  
154   -class Indicator (object):
  156 +class Indicator(object):
  157 + """
  158 + Piece of information of an :py:class:`OleID` object.
  159 +
  160 + Contains an ID, value, type, name and description. No other functionality.
  161 + """
155 162  
156   - def __init__(self, _id, value=None, _type=bool, name=None, description=None):
  163 + def __init__(self, _id, value=None, _type=bool, name=None,
  164 + description=None):
157 165 self.id = _id
158 166 self.value = value
159 167 self.type = _type
... ... @@ -163,21 +171,55 @@ class Indicator (object):
163 171 self.description = description
164 172  
165 173  
166   -class OleID:
  174 +class OleID(object):
  175 + """
  176 + Summary of information about an OLE file
167 177  
168   - def __init__(self, filename):
169   - self.filename = filename
  178 + Call :py:meth:`OleID.check` to gather all info on a given file or run one
  179 + of the `check_` functions to just get a specific piece of info.
  180 + """
  181 +
  182 + def __init__(self, input_file):
  183 + """
  184 + Create an OleID object
  185 +
  186 + This does not run any checks yet nor open the file.
  187 +
  188 + Can either give just a filename (as str), so OleID will check whether
  189 + that is a valid OLE file and create a :py:class:`olefile.OleFileIO`
  190 + object for it. Or you can give an already opened
  191 + :py:class:`olefile.OleFileIO` as argument to avoid re-opening (e.g. if
  192 + called from other oletools).
  193 +
  194 + If filename is given, only :py:meth:`OleID.check` opens the file. Other
  195 + functions will return None
  196 + """
  197 + if isinstance(input_file, olefile.OleFileIO):
  198 + self.ole = input_file
  199 + self.filename = None
  200 + else:
  201 + self.filename = input_file
  202 + self.ole = None
170 203 self.indicators = []
  204 + self.suminfo_data = None
171 205  
172 206 def check(self):
  207 + """
  208 + Open file and run all checks on it.
  209 +
  210 + :returns: list of all :py:class:`Indicator`s created
  211 + """
173 212 # check if it is actually an OLE file:
174 213 oleformat = Indicator('ole_format', True, name='OLE format')
175 214 self.indicators.append(oleformat)
176   - if not olefile.isOleFile(self.filename):
  215 + if self.ole:
  216 + oleformat.value = True
  217 + elif not olefile.isOleFile(self.filename):
177 218 oleformat.value = False
178 219 return self.indicators
179   - # parse file:
180   - self.ole = olefile.OleFileIO(self.filename)
  220 + else:
  221 + # parse file:
  222 + self.ole = olefile.OleFileIO(self.filename)
181 223 # checks:
182 224 self.check_properties()
183 225 self.check_encrypted()
... ... @@ -185,143 +227,274 @@ class OleID:
185 227 self.check_excel()
186 228 self.check_powerpoint()
187 229 self.check_visio()
188   - self.check_ObjectPool()
  230 + self.check_object_pool()
189 231 self.check_flash()
190 232 self.ole.close()
191 233 return self.indicators
192 234  
193   - def check_properties (self):
194   - suminfo = Indicator('has_suminfo', False, name='Has SummaryInformation stream')
  235 + def check_properties(self):
  236 + """
  237 + Read summary information required for other check_* functions
  238 +
  239 + :returns: 2 :py:class:`Indicator`s (for presence of summary info and
  240 + application name) or None if file was not opened
  241 + """
  242 + suminfo = Indicator('has_suminfo', False,
  243 + name='Has SummaryInformation stream')
195 244 self.indicators.append(suminfo)
196   - appname = Indicator('appname', 'unknown', _type=str, name='Application name')
  245 + appname = Indicator('appname', 'unknown', _type=str,
  246 + name='Application name')
197 247 self.indicators.append(appname)
198   - self.suminfo = {}
199   - # check stream SummaryInformation
  248 + if not self.ole:
  249 + return None, None
  250 + self.suminfo_data = {}
  251 + # check stream SummaryInformation (not present e.g. in encrypted ppt)
200 252 if self.ole.exists("\x05SummaryInformation"):
201 253 suminfo.value = True
202   - self.suminfo = self.ole.getproperties("\x05SummaryInformation")
  254 + self.suminfo_data = self.ole.getproperties("\x05SummaryInformation")
203 255 # check application name:
204   - appname.value = self.suminfo.get(0x12, 'unknown')
205   -
206   - def check_encrypted (self):
  256 + appname.value = self.suminfo_data.get(0x12, 'unknown')
  257 + return suminfo, appname
  258 +
  259 + def get_indicator(self, indicator_id):
  260 + """Helper function: returns an indicator if present (or None)"""
  261 + result = [indicator for indicator in self.indicators
  262 + if indicator.id == indicator_id]
  263 + if result:
  264 + return result[0]
  265 + else:
  266 + return None
  267 +
  268 + def check_encrypted(self):
  269 + """
  270 + Check whether this file is encrypted.
  271 +
  272 + Might call check_properties.
  273 +
  274 + :returns: :py:class:`Indicator` for encryption or None if file was not
  275 + opened
  276 + """
207 277 # we keep the pointer to the indicator, can be modified by other checks:
208   - self.encrypted = Indicator('encrypted', False, name='Encrypted')
209   - self.indicators.append(self.encrypted)
  278 + encrypted = Indicator('encrypted', False, name='Encrypted')
  279 + self.indicators.append(encrypted)
  280 + if not self.ole:
  281 + return None
210 282 # check if bit 1 of security field = 1:
211 283 # (this field may be missing for Powerpoint2000, for example)
212   - if 0x13 in self.suminfo:
213   - if self.suminfo[0x13] & 1:
214   - self.encrypted.value = True
  284 + if self.suminfo_data is None:
  285 + self.check_properties()
  286 + if 0x13 in self.suminfo_data:
  287 + if self.suminfo_data[0x13] & 1:
  288 + encrypted.value = True
215 289 # check if this is an OpenXML encrypted file
216 290 elif self.ole.exists('EncryptionInfo'):
217   - self.encrypted.value = True
218   -
219   - def check_word (self):
220   - word = Indicator('word', False, name='Word Document',
221   - description='Contains a WordDocument stream, very likely to be a Microsoft Word Document.')
  291 + encrypted.value = True
  292 + # or an encrypted ppt file
  293 + if self.ole.exists('EncryptedSummary') and \
  294 + not self.ole.exists('SummaryInformation'):
  295 + encrypted.value = True
  296 + return encrypted
  297 +
  298 + def check_word(self):
  299 + """
  300 + Check whether this file is a word document
  301 +
  302 + If this finds evidence of encryption, will correct/add encryption
  303 + indicator.
  304 +
  305 + :returns: 2 :py:class:`Indicator`s (for word and vba_macro) or None if
  306 + file was not opened
  307 + """
  308 + word = Indicator(
  309 + 'word', False, name='Word Document',
  310 + description='Contains a WordDocument stream, very likely to be a '
  311 + 'Microsoft Word Document.')
222 312 self.indicators.append(word)
223   - self.macros = Indicator('vba_macros', False, name='VBA Macros')
224   - self.indicators.append(self.macros)
  313 + macros = Indicator('vba_macros', False, name='VBA Macros')
  314 + self.indicators.append(macros)
  315 + if not self.ole:
  316 + return None, None
225 317 if self.ole.exists('WordDocument'):
226 318 word.value = True
227 319 # check for Word-specific encryption flag:
228   - s = self.ole.openstream(["WordDocument"])
229   - # pass header 10 bytes
230   - s.read(10)
231   - # read flag structure:
232   - temp16 = struct.unpack("H", s.read(2))[0]
233   - fEncrypted = (temp16 & 0x0100) >> 8
234   - if fEncrypted:
235   - self.encrypted.value = True
236   - s.close()
  320 + stream = None
  321 + try:
  322 + stream = self.ole.openstream(["WordDocument"])
  323 + # pass header 10 bytes
  324 + stream.read(10)
  325 + # read flag structure:
  326 + temp16 = struct.unpack("H", stream.read(2))[0]
  327 + f_encrypted = (temp16 & 0x0100) >> 8
  328 + if f_encrypted:
  329 + # correct encrypted indicator if present or add one
  330 + encrypt_ind = self.get_indicator('encrypted')
  331 + if encrypt_ind:
  332 + encrypt_ind.value = True
  333 + else:
  334 + self.indicators.append('encrypted', True, name='Encrypted')
  335 + except Exception:
  336 + raise
  337 + finally:
  338 + if stream is not None:
  339 + stream.close()
237 340 # check for VBA macros:
238 341 if self.ole.exists('Macros'):
239   - self.macros.value = True
  342 + macros.value = True
  343 + return word, macros
  344 +
  345 + def check_excel(self):
  346 + """
  347 + Check whether this file is an excel workbook.
  348 +
  349 + If this finds macros, will add/correct macro indicator.
240 350  
241   - def check_excel (self):
242   - excel = Indicator('excel', False, name='Excel Workbook',
243   - description='Contains a Workbook or Book stream, very likely to be a Microsoft Excel Workbook.')
  351 + see also: :py:func:`xls_parser.is_xls`
  352 +
  353 + :returns: :py:class:`Indicator` for excel or (None, None) if file was
  354 + not opened
  355 + """
  356 + excel = Indicator(
  357 + 'excel', False, name='Excel Workbook',
  358 + description='Contains a Workbook or Book stream, very likely to be '
  359 + 'a Microsoft Excel Workbook.')
244 360 self.indicators.append(excel)
  361 + if not self.ole:
  362 + return None
245 363 #self.macros = Indicator('vba_macros', False, name='VBA Macros')
246 364 #self.indicators.append(self.macros)
247 365 if self.ole.exists('Workbook') or self.ole.exists('Book'):
248 366 excel.value = True
249 367 # check for VBA macros:
250 368 if self.ole.exists('_VBA_PROJECT_CUR'):
251   - self.macros.value = True
252   -
253   - def check_powerpoint (self):
254   - ppt = Indicator('ppt', False, name='PowerPoint Presentation',
255   - description='Contains a PowerPoint Document stream, very likely to be a Microsoft PowerPoint Presentation.')
  369 + # correct macro indicator if present or add one
  370 + macro_ind = self.get_indicator('vba_macros')
  371 + if macro_ind:
  372 + macro_ind.value = True
  373 + else:
  374 + self.indicators.append('vba_macros', True,
  375 + name='VBA Macros')
  376 + return excel
  377 +
  378 + def check_powerpoint(self):
  379 + """
  380 + Check whether this file is a powerpoint presentation
  381 +
  382 + see also: :py:func:`ppt_record_parser.is_ppt`
  383 +
  384 + :returns: :py:class:`Indicator` for whether this is a powerpoint
  385 + presentation or not or None if file was not opened
  386 + """
  387 + ppt = Indicator(
  388 + 'ppt', False, name='PowerPoint Presentation',
  389 + description='Contains a PowerPoint Document stream, very likely to '
  390 + 'be a Microsoft PowerPoint Presentation.')
256 391 self.indicators.append(ppt)
  392 + if not self.ole:
  393 + return None
257 394 if self.ole.exists('PowerPoint Document'):
258 395 ppt.value = True
259   -
260   - def check_visio (self):
261   - visio = Indicator('visio', False, name='Visio Drawing',
262   - description='Contains a VisioDocument stream, very likely to be a Microsoft Visio Drawing.')
  396 + return ppt
  397 +
  398 + def check_visio(self):
  399 + """Check whether this file is a visio drawing"""
  400 + visio = Indicator(
  401 + 'visio', False, name='Visio Drawing',
  402 + description='Contains a VisioDocument stream, very likely to be a '
  403 + 'Microsoft Visio Drawing.')
263 404 self.indicators.append(visio)
  405 + if not self.ole:
  406 + return None
264 407 if self.ole.exists('VisioDocument'):
265 408 visio.value = True
  409 + return visio
  410 +
  411 + def check_object_pool(self):
  412 + """
  413 + Check whether this file contains an ObjectPool stream.
  414 +
  415 + Such a stream would be a strong indicator for embedded objects or files.
266 416  
267   - def check_ObjectPool (self):
268   - objpool = Indicator('ObjectPool', False, name='ObjectPool',
269   - description='Contains an ObjectPool stream, very likely to contain embedded OLE objects or files.')
  417 + :returns: :py:class:`Indicator` for ObjectPool stream or None if file
  418 + was not opened
  419 + """
  420 + objpool = Indicator(
  421 + 'ObjectPool', False, name='ObjectPool',
  422 + description='Contains an ObjectPool stream, very likely to contain '
  423 + 'embedded OLE objects or files.')
270 424 self.indicators.append(objpool)
  425 + if not self.ole:
  426 + return None
271 427 if self.ole.exists('ObjectPool'):
272 428 objpool.value = True
273   -
274   -
275   - def check_flash (self):
276   - flash = Indicator('flash', 0, _type=int, name='Flash objects',
277   - description='Number of embedded Flash objects (SWF files) detected in OLE streams. Not 100% accurate, there may be false positives.')
  429 + return objpool
  430 +
  431 + def check_flash(self):
  432 + """
  433 + Check whether this file contains flash objects
  434 +
  435 + :returns: :py:class:`Indicator` for count of flash objects or None if
  436 + file was not opened
  437 + """
  438 + flash = Indicator(
  439 + 'flash', 0, _type=int, name='Flash objects',
  440 + description='Number of embedded Flash objects (SWF files) detected '
  441 + 'in OLE streams. Not 100% accurate, there may be false '
  442 + 'positives.')
278 443 self.indicators.append(flash)
  444 + if not self.ole:
  445 + return None
279 446 for stream in self.ole.listdir():
280 447 data = self.ole.openstream(stream).read()
281 448 found = detect_flash(data)
282 449 # just add to the count of Flash objects:
283 450 flash.value += len(found)
284 451 #print stream, found
  452 + return flash
285 453  
286 454  
287 455 #=== MAIN =================================================================
288 456  
289 457 def main():
  458 + """Called when running this file as script. Shows all info on input file."""
290 459 # print banner with version
291   - print ('oleid %s - http://decalage.info/oletools' % __version__)
292   - print ('THIS IS WORK IN PROGRESS - Check updates regularly!')
293   - print ('Please report any issue at https://github.com/decalage2/oletools/issues')
294   - print ('')
  460 + print('oleid %s - http://decalage.info/oletools' % __version__)
  461 + print('THIS IS WORK IN PROGRESS - Check updates regularly!')
  462 + print('Please report any issue at '
  463 + 'https://github.com/decalage2/oletools/issues')
  464 + print('')
295 465  
296   - usage = 'usage: %prog [options] <file>'
297   - parser = optparse.OptionParser(usage=__doc__ + '\n' + usage)
298   -## 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')
  466 + parser = argparse.ArgumentParser(description=__doc__)
  467 + parser.add_argument('input', type=str, nargs='*', metavar='FILE',
  468 + help='Name of files to process')
  469 + # parser.add_argument('-o', '--ole', action='store_true', dest='ole',
  470 + # help='Parse an OLE file (e.g. Word, Excel) to look for '
  471 + # 'SWF in each stream')
299 472  
300   - (options, args) = parser.parse_args()
  473 + args = parser.parse_args()
301 474  
302 475 # Print help if no argurments are passed
303   - if len(args) == 0:
  476 + if len(args.input) == 0:
304 477 parser.print_help()
305 478 return
306 479  
307   - for filename in args:
  480 + for filename in args.input:
308 481 print('Filename:', filename)
309 482 oleid = OleID(filename)
310 483 indicators = oleid.check()
311 484  
312 485 #TODO: add description
313 486 #TODO: highlight suspicious indicators
314   - t = prettytable.PrettyTable(['Indicator', 'Value'])
315   - t.align = 'l'
316   - t.max_width = 39
317   - #t.border = False
  487 + table = prettytable.PrettyTable(['Indicator', 'Value'])
  488 + table.align = 'l'
  489 + table.max_width = 39
  490 + table.border = False
318 491  
319 492 for indicator in indicators:
320 493 #print '%s: %s' % (indicator.name, indicator.value)
321   - t.add_row((indicator.name, indicator.value))
  494 + table.add_row((indicator.name, indicator.value))
322 495  
323   - print(t)
324   - print ('')
  496 + print(table)
  497 + print('')
325 498  
326 499 if __name__ == '__main__':
327 500 main()
... ...
oletools/olemap.py
... ... @@ -13,7 +13,7 @@ http://www.decalage.info/python/oletools
13 13  
14 14 #=== LICENSE ==================================================================
15 15  
16   -# olemap is copyright (c) 2015-2017 Philippe Lagadec (http://www.decalage.info)
  16 +# olemap is copyright (c) 2015-2018 Philippe Lagadec (http://www.decalage.info)
17 17 # All rights reserved.
18 18 #
19 19 # Redistribution and use in source and binary forms, with or without modification,
... ... @@ -51,9 +51,9 @@ http://www.decalage.info/python/oletools
51 51 # 2017-03-22 PL: - added extra data detection, completed header display
52 52 # 2017-03-23 PL: - only display the header by default
53 53 # - added option --exdata to display extra data in hex
  54 +# 2018-08-28 v0.54 PL: - olefile is now a dependency
54 55  
55   -
56   -__version__ = '0.51'
  56 +__version__ = '0.54dev1'
57 57  
58 58 #------------------------------------------------------------------------------
59 59 # TODO:
... ... @@ -74,7 +74,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
74 74 if not _parent_dir in sys.path:
75 75 sys.path.insert(0, _parent_dir)
76 76  
77   -from oletools.thirdparty.olefile import olefile
  77 +import olefile
78 78 from oletools.thirdparty.tablestream import tablestream
79 79 from oletools.thirdparty.xglob import xglob
80 80 from oletools.ezhexviewer import hexdump3
... ...
oletools/olemeta.py
... ... @@ -15,7 +15,7 @@ http://www.decalage.info/python/oletools
15 15  
16 16 #=== LICENSE =================================================================
17 17  
18   -# olemeta is copyright (c) 2013-2017, Philippe Lagadec (http://www.decalage.info)
  18 +# olemeta is copyright (c) 2013-2018, Philippe Lagadec (http://www.decalage.info)
19 19 # All rights reserved.
20 20 #
21 21 # Redistribution and use in source and binary forms, with or without modification,
... ... @@ -49,8 +49,9 @@ http://www.decalage.info/python/oletools
49 49 # 2016-10-28 PL: - removed the UTF8 codec for console display
50 50 # 2017-04-26 v0.51 PL: - fixed absolute imports (issue #141)
51 51 # 2017-05-04 PL: - added optparse and xglob (issue #141)
  52 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
52 53  
53   -__version__ = '0.51'
  54 +__version__ = '0.54dev1'
54 55  
55 56 #------------------------------------------------------------------------------
56 57 # TODO:
... ... @@ -75,7 +76,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
75 76 if not _parent_dir in sys.path:
76 77 sys.path.insert(0, _parent_dir)
77 78  
78   -from oletools.thirdparty import olefile
  79 +import olefile
79 80 from oletools.thirdparty import xglob
80 81 from oletools.thirdparty.tablestream import tablestream
81 82  
... ...
oletools/oleobj.py
... ... @@ -50,7 +50,9 @@ import os
50 50 import re
51 51 import sys
52 52 import io
53   -from zipfile import is_zipfile, ZipFile
  53 +from zipfile import is_zipfile
  54 +
  55 +import olefile
54 56  
55 57 # IMPORTANT: it should be possible to run oletools directly as scripts
56 58 # in any directory without installing them with pip or setup.py.
... ... @@ -58,7 +60,7 @@ from zipfile import is_zipfile, ZipFile
58 60 # And to enable Python 2+3 compatibility, we need to use absolute imports,
59 61 # so we add the oletools parent folder to sys.path (absolute+normalized path):
60 62 try:
61   - from oletools.thirdparty import olefile
  63 + from oletools.thirdparty import xglob
62 64 except ImportError:
63 65 import os.path
64 66 PARENT_DIR = os.path.normpath(os.path.dirname(os.path.dirname(
... ... @@ -66,11 +68,11 @@ except ImportError:
66 68 if PARENT_DIR not in sys.path:
67 69 sys.path.insert(0, PARENT_DIR)
68 70 del PARENT_DIR
69   - from oletools.thirdparty import olefile
70   -from oletools.thirdparty import xglob
  71 + from oletools.thirdparty import xglob
  72 +
71 73 from oletools.ppt_record_parser import (is_ppt, PptFile,
72 74 PptRecordExOleVbaActiveXAtom)
73   -from oletools.ooxml import ZipSubFile
  75 +from oletools.ooxml import XmlParser
74 76  
75 77 # -----------------------------------------------------------------------------
76 78 # CHANGELOG:
... ... @@ -84,8 +86,10 @@ from oletools.ooxml import ZipSubFile
84 86 # 2018-01-18 v0.52 CH: - added support for zipped-xml-based types (docx, pptx,
85 87 # xlsx), and ppt
86 88 # 2018-03-27 PL: - fixed issue #274 in read_length_prefixed_string
  89 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  90 +# 2018-10-30 SA: - added detection of external links (PR #317)
87 91  
88   -__version__ = '0.52.4'
  92 +__version__ = '0.54dev4'
89 93  
90 94 # -----------------------------------------------------------------------------
91 95 # TODO:
... ... @@ -178,6 +182,7 @@ else:
178 182 NULL_CHAR = 0 # pylint: disable=redefined-variable-type
179 183 xrange = range # pylint: disable=redefined-builtin, invalid-name
180 184  
  185 +OOXML_RELATIONSHIP_TAG = '{http://schemas.openxmlformats.org/package/2006/relationships}Relationship'
181 186  
182 187 # === GLOBAL VARIABLES ========================================================
183 188  
... ... @@ -203,6 +208,24 @@ RETURN_ERR_ARGS = 2 # reserve for OptionParser.parse_args
203 208 RETURN_ERR_STREAM = 4 # error opening/parsing a stream
204 209 RETURN_ERR_DUMP = 8 # error dumping data from stream to file
205 210  
  211 +# Not sure if they can all be "External", but just in case
  212 +BLACKLISTED_RELATIONSHIP_TYPES = [
  213 + 'attachedTemplate',
  214 + 'externalLink',
  215 + 'externalLinkPath',
  216 + 'externalReference'
  217 + 'frame'
  218 + 'hyperlink',
  219 + 'officeDocument',
  220 + 'oleObject',
  221 + 'package',
  222 + 'slideUpdateUrl',
  223 + 'slideMaster',
  224 + 'slide',
  225 + 'slideUpdateInfo',
  226 + 'subDocument',
  227 + 'worksheet'
  228 +]
206 229  
207 230 # === FUNCTIONS ===============================================================
208 231  
... ... @@ -596,7 +619,7 @@ class FakeFile(io.RawIOBase):
596 619 return self.pos
597 620  
598 621  
599   -def find_ole(filename, data):
  622 +def find_ole(filename, data, xml_parser=None):
600 623 """ try to open somehow as zip/ole/rtf/... ; yield None if fail
601 624  
602 625 If data is given, filename is (mostly) ignored.
... ... @@ -628,34 +651,40 @@ def find_ole(filename, data):
628 651 log.info('is ole file: ' + filename)
629 652 ole = olefile.OleFileIO(arg_for_ole)
630 653 yield ole
631   - elif is_zipfile(arg_for_zip):
  654 + elif xml_parser is not None or is_zipfile(arg_for_zip):
  655 + # keep compatibility with 3rd-party code that calls this function
  656 + # directly without providing an XmlParser instance
  657 + if xml_parser is None:
  658 + xml_parser = XmlParser(arg_for_zip)
  659 + # force iteration so XmlParser.iter_non_xml() returns data
  660 + [x for x in xml_parser.iter_xml()]
  661 +
632 662 log.info('is zip file: ' + filename)
633   - zipper = ZipFile(arg_for_zip, 'r')
634   - for subfile in zipper.namelist():
635   - head = b''
  663 + # we looped through the XML files before, now we can
  664 + # iterate the non-XML files looking for ole objects
  665 + for subfile, _, file_handle in xml_parser.iter_non_xml():
636 666 try:
637   - with zipper.open(subfile) as file_handle:
638   - head = file_handle.read(len(olefile.MAGIC))
  667 + head = file_handle.read(len(olefile.MAGIC))
639 668 except RuntimeError:
640 669 log.error('zip is encrypted: ' + filename)
641 670 yield None
642 671 continue
643 672  
644 673 if head == olefile.MAGIC:
  674 + file_handle.seek(0)
645 675 log.info(' unzipping ole: ' + subfile)
646   - with ZipSubFile(zipper, subfile) as file_handle:
647   - try:
648   - ole = olefile.OleFileIO(file_handle)
649   - yield ole
650   - except IOError:
651   - log.warning('Error reading data from {0}/{1} or '
652   - 'interpreting it as OLE object'
653   - .format(filename, subfile))
654   - log.debug('', exc_info=True)
655   - finally:
656   - if ole is not None:
657   - ole.close()
658   - ole = None
  676 + try:
  677 + ole = olefile.OleFileIO(file_handle)
  678 + yield ole
  679 + except IOError:
  680 + log.warning('Error reading data from {0}/{1} or '
  681 + 'interpreting it as OLE object'
  682 + .format(filename, subfile))
  683 + log.debug('', exc_info=True)
  684 + finally:
  685 + if ole is not None:
  686 + ole.close()
  687 + ole = None
659 688 else:
660 689 log.debug('unzip skip: ' + subfile)
661 690 else:
... ... @@ -671,6 +700,22 @@ def find_ole(filename, data):
671 700 ole.close()
672 701  
673 702  
  703 +def find_external_relationships(xml_parser):
  704 + """ iterate XML files looking for relationships to external objects
  705 + """
  706 + for _, elem, _ in xml_parser.iter_xml(None, False, OOXML_RELATIONSHIP_TAG):
  707 + try:
  708 + if elem.attrib['TargetMode'] == 'External':
  709 + relationship_type = elem.attrib['Type'].rsplit('/', 1)[1]
  710 +
  711 + if relationship_type in BLACKLISTED_RELATIONSHIP_TYPES:
  712 + yield relationship_type, elem.attrib['Target']
  713 + except (AttributeError, KeyError):
  714 + # ignore missing attributes - Word won't detect
  715 + # external links anyway
  716 + pass
  717 +
  718 +
674 719 def process_file(filename, data, output_dir=None):
675 720 """ find embedded objects in given file
676 721  
... ... @@ -703,10 +748,19 @@ def process_file(filename, data, output_dir=None):
703 748 err_dumping = False
704 749 did_dump = False
705 750  
  751 + xml_parser = None
  752 + if is_zipfile(filename):
  753 + log.info('file is a OOXML file, looking for relationships with external links')
  754 + xml_parser = XmlParser(filename)
  755 + for relationship, target in find_external_relationships(xml_parser):
  756 + did_dump = True
  757 + print("Found relationship '%s' with external link %s" % (relationship, target))
  758 +
  759 +
706 760 # look for ole files inside file (e.g. unzip docx)
707 761 # have to finish work on every ole stream inside iteration, since handles
708 762 # are closed in find_ole
709   - for ole in find_ole(filename, data):
  763 + for ole in find_ole(filename, data, xml_parser):
710 764 if ole is None: # no ole file found
711 765 continue
712 766  
... ...
oletools/oletimes.py
... ... @@ -50,8 +50,9 @@ http://www.decalage.info/python/oletools
50 50 # 2016-09-05 PL: - added main entry point for setup.py
51 51 # 2017-05-03 v0.51 PL: - fixed absolute imports (issue #141)
52 52 # 2017-05-04 PL: - added optparse and xglob (issue #141)
  53 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
53 54  
54   -__version__ = '0.51'
  55 +__version__ = '0.54dev1'
55 56  
56 57 #------------------------------------------------------------------------------
57 58 # TODO:
... ... @@ -75,7 +76,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
75 76 if not _parent_dir in sys.path:
76 77 sys.path.insert(0, _parent_dir)
77 78  
78   -from oletools.thirdparty import olefile
  79 +import olefile
79 80 from oletools.thirdparty import xglob
80 81 from oletools.thirdparty.prettytable import prettytable
81 82  
... ...
oletools/olevba.py
... ... @@ -14,6 +14,7 @@ Supported formats:
14 14 - Word 2003 XML (.xml)
15 15 - Word/Excel Single File Web Page / MHTML (.mht)
16 16 - Publisher (.pub)
  17 +- raises an error if run with files encrypted using MS Crypto API RC4
17 18  
18 19 Author: Philippe Lagadec - http://www.decalage.info
19 20 License: BSD, see source code or documentation
... ... @@ -206,8 +207,11 @@ from __future__ import print_function
206 207 # 2018-03-19 PL: - removed pyparsing from the thirdparty subfolder
207 208 # 2018-04-15 v0.53 PL: - added support for Word/PowerPoint 2007+ XML (FlatOPC)
208 209 # (issue #283)
  210 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  211 +# 2018-10-08 PL: - replace backspace before printing to console (issue #358)
  212 +# 2018-10-25 CH: - detect encryption and raise error if detected
209 213  
210   -__version__ = '0.53.1'
  214 +__version__ = '0.54dev4'
211 215  
212 216 #------------------------------------------------------------------------------
213 217 # TODO:
... ... @@ -245,7 +249,10 @@ import sys
245 249 import os
246 250 import logging
247 251 import struct
248   -import cStringIO
  252 +try:
  253 + from cStringIO import StringIO
  254 +except ImportError:
  255 + from io import StringIO
249 256 import math
250 257 import zipfile
251 258 import re
... ... @@ -274,6 +281,12 @@ except ImportError:
274 281 + "see http://codespeak.net/lxml " \
275 282 + "or http://effbot.org/zone/element-index.htm")
276 283  
  284 +import colorclass
  285 +
  286 +# On Windows, colorclass needs to be enabled:
  287 +if os.name == 'nt':
  288 + colorclass.Windows.enable(auto_colors=True)
  289 +
277 290  
278 291 # IMPORTANT: it should be possible to run oletools directly as scripts
279 292 # 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, &#39;..&#39;))
287 300 if not _parent_dir in sys.path:
288 301 sys.path.insert(0, _parent_dir)
289 302  
290   -from oletools.thirdparty import olefile
  303 +import olefile
291 304 from oletools.thirdparty.prettytable import prettytable
292 305 from oletools.thirdparty.xglob import xglob, PathNotFoundException
293 306 from pyparsing import \
... ... @@ -298,6 +311,8 @@ from pyparsing import \
298 311 from oletools import ppt_parser
299 312 from oletools import oleform
300 313 from oletools import rtfobj
  314 +from oletools import oleid
  315 +from oletools.common.errors import FileIsEncryptedError
301 316  
302 317  
303 318 # monkeypatch email to fix issue #32:
... ... @@ -461,6 +476,7 @@ RETURN_OPEN_ERROR = 5
461 476 RETURN_PARSE_ERROR = 6
462 477 RETURN_SEVERAL_ERRS = 7
463 478 RETURN_UNEXPECTED = 8
  479 +RETURN_ENCRYPTED = 9
464 480  
465 481 # MAC codepages (from http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python)
466 482 MAC_CODEPAGES = {
... ... @@ -697,6 +713,12 @@ SUSPICIOUS_KEYWORDS = {
697 713 ('VBProject', 'VBComponents', 'CodeModule', 'AddFromString'),
698 714 }
699 715  
  716 +# Suspicious Keywords to be searched for directly as strings, without regex
  717 +SUSPICIOUS_KEYWORDS_NOREGEX = {
  718 + 'May use special characters such as backspace to obfuscate code when printed on the console':
  719 + ('\b',),
  720 +}
  721 +
700 722 # Regular Expression for a URL:
701 723 # http://en.wikipedia.org/wiki/Uniform_resource_locator
702 724 # 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):
1351 1373 else:
1352 1374 raise UnexpectedDataError(dir_path, name, expected, value)
1353 1375  
1354   - dir_stream = cStringIO.StringIO(decompress_stream(dir_compressed))
  1376 + dir_stream = StringIO(decompress_stream(dir_compressed))
1355 1377  
1356 1378 # PROJECTSYSKIND Record
1357 1379 projectsyskind_id = struct.unpack("<H", dir_stream.read(2))[0]
... ... @@ -1884,6 +1906,10 @@ def detect_suspicious(vba_code, obfuscation=None):
1884 1906 #if keyword.lower() in vba_code:
1885 1907 found_keyword = match.group()
1886 1908 results.append((found_keyword, description + obf_text))
  1909 + for description, keywords in SUSPICIOUS_KEYWORDS_NOREGEX.items():
  1910 + for keyword in keywords:
  1911 + if keyword.lower() in vba_code:
  1912 + results.append((keyword, description + obf_text))
1887 1913 return results
1888 1914  
1889 1915  
... ... @@ -2308,7 +2334,7 @@ class VBA_Parser(object):
2308 2334 _file = filename
2309 2335 else:
2310 2336 # file already read in memory, make it a file-like object for zipfile:
2311   - _file = cStringIO.StringIO(data)
  2337 + _file = StringIO(data)
2312 2338 #self.file = _file
2313 2339 self.ole_file = None
2314 2340 self.ole_subfiles = []
... ... @@ -2346,6 +2372,12 @@ class VBA_Parser(object):
2346 2372 # This looks like an OLE file
2347 2373 self.open_ole(_file)
2348 2374  
  2375 + # check whether file is encrypted (need to do this before try ppt)
  2376 + log.debug('Check encryption of ole file')
  2377 + crypt_indicator = oleid.OleID(self.ole_file).check_encrypted()
  2378 + if crypt_indicator.value:
  2379 + raise FileIsEncryptedError(filename)
  2380 +
2349 2381 # if this worked, try whether it is a ppt file (special ole file)
2350 2382 self.open_ppt()
2351 2383 if self.type is None and is_zipfile(_file):
... ... @@ -2821,7 +2853,7 @@ class VBA_Parser(object):
2821 2853 log.debug('%r...[much more data]...%r' % (data[:100], data[-50:]))
2822 2854 else:
2823 2855 log.debug(repr(data))
2824   - if 'Attribut' in data:
  2856 + if 'Attribut\x00' in data:
2825 2857 log.debug('Found VBA compressed code')
2826 2858 self.contains_macros = True
2827 2859 except IOError as exc:
... ... @@ -3218,6 +3250,16 @@ class VBA_Parser_CLI(VBA_Parser):
3218 3250 if vba_code_filtered.strip() == '':
3219 3251 print('(empty macro)')
3220 3252 else:
  3253 + # check if the VBA code contains special characters such as backspace (issue #358)
  3254 + if b'\x08' in vba_code_filtered:
  3255 + log.warning('The VBA code contains special characters such as backspace, that may be used for obfuscation.')
  3256 + if sys.stdout.isatty():
  3257 + # if the standard output is the console, we'll display colors
  3258 + backspace = colorclass.Color(b'{autored}\\x08{/red}')
  3259 + else:
  3260 + backspace = b'\\x08'
  3261 + # replace backspace by "\x08" for display
  3262 + vba_code_filtered = vba_code_filtered.replace(b'\x08', backspace)
3221 3263 print(vba_code_filtered)
3222 3264 for (subfilename, stream_path, form_string) in self.extract_form_strings():
3223 3265 print('-' * 79)
... ... @@ -3603,6 +3645,16 @@ def main(cmd_line_args=None):
3603 3645 % (filename, exc.orig_exc))
3604 3646 return_code = RETURN_PARSE_ERROR if return_code == 0 \
3605 3647 else RETURN_SEVERAL_ERRS
  3648 + except FileIsEncryptedError as exc:
  3649 + if options.output_mode in ('triage', 'unspecified'):
  3650 + print('%-12s %s - File is encrypted' % ('!ERROR', filename))
  3651 + elif options.output_mode == 'json':
  3652 + print_json(file=filename, type='error',
  3653 + error=type(exc).__name__, message=str(exc))
  3654 + else:
  3655 + log.exception('File %s is encrypted!' % (filename))
  3656 + return_code = RETURN_ENCRYPTED if return_code == 0 \
  3657 + else RETURN_SEVERAL_ERRS
3606 3658 # Here we do not close the vba_parser, because process_file may need it below.
3607 3659  
3608 3660 if options.output_mode == 'triage':
... ...
oletools/olevba3.py
... ... @@ -16,6 +16,7 @@ Supported formats:
16 16 - Word 2003 XML (.xml)
17 17 - Word/Excel Single File Web Page / MHTML (.mht)
18 18 - Publisher (.pub)
  19 +- raises an error if run with files encrypted using MS Crypto API RC4
19 20  
20 21 Author: Philippe Lagadec - http://www.decalage.info
21 22 License: BSD, see source code or documentation
... ... @@ -78,6 +79,7 @@ https://github.com/unixfreak0037/officeparser
78 79  
79 80 from __future__ import print_function
80 81  
  82 +
81 83 #------------------------------------------------------------------------------
82 84 # CHANGELOG:
83 85 # 2014-08-05 v0.01 PL: - first version based on officeparser code
... ... @@ -203,8 +205,12 @@ from __future__ import print_function
203 205 # 2018-03-19 PL: - removed pyparsing from the thirdparty subfolder
204 206 # 2018-05-13 v0.53 PL: - added support for Word/PowerPoint 2007+ XML (FlatOPC)
205 207 # (issue #283)
  208 +# 2018-06-11 v0.53.1 MHW: - fixed #320: chr instead of unichr on python 3
  209 +# 2018-06-12 MHW: - fixed #322: import reduce from functools
  210 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  211 +# 2018-10-25 CH: - detect encryption and raise error if detected
206 212  
207   -__version__ = '0.53.1'
  213 +__version__ = '0.54dev4'
208 214  
209 215 #------------------------------------------------------------------------------
210 216 # TODO:
... ... @@ -243,7 +249,6 @@ import os
243 249 import logging
244 250 import struct
245 251 from _io import StringIO,BytesIO
246   -from oletools import rtfobj
247 252 import math
248 253 import zipfile
249 254 import re
... ... @@ -254,6 +259,7 @@ import zlib
254 259 import email # for MHTML parsing
255 260 import string # for printable
256 261 import json # for json output mode (argument --json)
  262 +from functools import reduce
257 263  
258 264 # import lxml or ElementTree for XML parsing:
259 265 try:
... ... @@ -284,7 +290,7 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
284 290 if not _parent_dir in sys.path:
285 291 sys.path.insert(0, _parent_dir)
286 292  
287   -from oletools.thirdparty import olefile
  293 +import olefile
288 294 from oletools.thirdparty.prettytable import prettytable
289 295 from oletools.thirdparty.xglob import xglob, PathNotFoundException
290 296 from pyparsing import \
... ... @@ -293,6 +299,9 @@ from pyparsing import \
293 299 alphanums, alphas, hexnums,nums, opAssoc, srange, \
294 300 infixNotation, ParserElement
295 301 import oletools.ppt_parser as ppt_parser
  302 +from oletools import rtfobj
  303 +from oletools import oleid
  304 +from oletools.common.errors import FileIsEncryptedError
296 305  
297 306 # monkeypatch email to fix issue #32:
298 307 # allow header lines without ":"
... ... @@ -474,6 +483,7 @@ RETURN_OPEN_ERROR = 5
474 483 RETURN_PARSE_ERROR = 6
475 484 RETURN_SEVERAL_ERRS = 7
476 485 RETURN_UNEXPECTED = 8
  486 +RETURN_ENCRYPTED = 9
477 487  
478 488 # MAC codepages (from http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python)
479 489 MAC_CODEPAGES = {
... ... @@ -906,7 +916,7 @@ def vba_chr_tostr(t):
906 916 if i>=0 and i<=255:
907 917 return VbaExpressionString(chr(i))
908 918 else:
909   - return VbaExpressionString(unichr(i).encode('utf-8', 'backslashreplace'))
  919 + return VbaExpressionString(chr(i).encode('utf-8', 'backslashreplace'))
910 920 except ValueError:
911 921 log.exception('ERROR: incorrect parameter value for chr(): %r' % i)
912 922 return VbaExpressionString('Chr(%r)' % i)
... ... @@ -2355,6 +2365,12 @@ class VBA_Parser(object):
2355 2365 # This looks like an OLE file
2356 2366 self.open_ole(_file)
2357 2367  
  2368 + # check whether file is encrypted (need to do this before try ppt)
  2369 + log.debug('Check encryption of ole file')
  2370 + crypt_indicator = oleid.OleID(self.ole_file).check_encrypted()
  2371 + if crypt_indicator.value:
  2372 + raise FileIsEncryptedError(filename)
  2373 +
2358 2374 # if this worked, try whether it is a ppt file (special ole file)
2359 2375 self.open_ppt()
2360 2376 if self.type is None and is_zipfile(_file):
... ... @@ -2835,7 +2851,7 @@ class VBA_Parser(object):
2835 2851 log.debug('%r...[much more data]...%r' % (data[:100], data[-50:]))
2836 2852 else:
2837 2853 log.debug(repr(data))
2838   - if 'Attribut' in data.decode('utf-8', 'ignore'):
  2854 + if 'Attribut\x00' in data.decode('utf-8', 'ignore'):
2839 2855 log.debug('Found VBA compressed code')
2840 2856 self.contains_macros = True
2841 2857 except IOError as exc:
... ... @@ -3589,6 +3605,18 @@ def main(cmd_line_args=None):
3589 3605 % (filename, exc.orig_exc))
3590 3606 return_code = RETURN_PARSE_ERROR if return_code == 0 \
3591 3607 else RETURN_SEVERAL_ERRS
  3608 + except FileIsEncryptedError as exc:
  3609 + if options.output_mode in ('triage', 'unspecified'):
  3610 + print('%-12s %s - File is encrypted' % ('!ERROR', filename))
  3611 + elif options.output_mode == 'json':
  3612 + print_json(file=filename, type='error',
  3613 + error=type(exc).__name__, message=str(exc))
  3614 + else:
  3615 + log.exception('File %s is encrypted!' % (filename))
  3616 + return_code = RETURN_ENCRYPTED if return_code == 0 \
  3617 + else RETURN_SEVERAL_ERRS
  3618 + # Here we do not close the vba_parser, because process_file may need it below.
  3619 +
3592 3620 finally:
3593 3621 if vba_parser is not None:
3594 3622 vba_parser.close()
... ...
oletools/ooxml.py
... ... @@ -9,12 +9,14 @@ See also: Notes on Microsoft&#39;s implementation of ECMA-376: [MS-0E376]
9 9  
10 10 TODO: may have to tell apart single xml types: office2003 looks much different
11 11 than 2006+ --> DOCTYPE_*_XML2003
  12 +TODO: check what is duplicate here with oleid, maybe merge some day?
  13 +TODO: "xml2003" == "flatopc"?
12 14  
13 15 .. codeauthor:: Intra2net AG <info@intra2net>
14 16 """
15 17  
16 18 import sys
17   -import logging
  19 +from oletools.common.log_helper import log_helper
18 20 from zipfile import ZipFile, BadZipfile, is_zipfile
19 21 from os.path import splitext
20 22 import io
... ... @@ -27,6 +29,7 @@ try:
27 29 except ImportError:
28 30 import xml.etree.cElementTree as ET
29 31  
  32 +logger = log_helper.get_or_create_silent_logger('ooxml')
30 33  
31 34 #: subfiles that have to be part of every ooxml file
32 35 FILE_CONTENT_TYPES = '[Content_Types].xml'
... ... @@ -142,7 +145,7 @@ def get_type(filename):
142 145 is_xls = False
143 146 is_ppt = False
144 147 for _, elem, _ in parser.iter_xml(FILE_CONTENT_TYPES):
145   - logging.debug(u' ' + debug_str(elem))
  148 + logger.debug(u' ' + debug_str(elem))
146 149 try:
147 150 content_type = elem.attrib['ContentType']
148 151 except KeyError: # ContentType not an attr
... ... @@ -160,7 +163,7 @@ def get_type(filename):
160 163 if not is_doc and not is_xls and not is_ppt:
161 164 return DOCTYPE_NONE
162 165 else:
163   - logging.warning('Encountered contradictory content types')
  166 + logger.warning('Encountered contradictory content types')
164 167 return DOCTYPE_MIXED
165 168  
166 169  
... ... @@ -220,7 +223,7 @@ class ZipSubFile(object):
220 223 self.name = filename
221 224 if size is None:
222 225 self.size = container.getinfo(filename).file_size
223   - logging.debug('zip stream has size {0}'.format(self.size))
  226 + logger.debug('zip stream has size {0}'.format(self.size))
224 227 else:
225 228 self.size = size
226 229 if 'w' in mode.lower():
... ... @@ -484,10 +487,10 @@ class XmlParser(object):
484 487 want_tags = []
485 488 elif isstr(tags):
486 489 want_tags = [tags, ]
487   - logging.debug('looking for tags: {0}'.format(tags))
  490 + logger.debug('looking for tags: {0}'.format(tags))
488 491 else:
489 492 want_tags = tags
490   - logging.debug('looking for tags: {0}'.format(tags))
  493 + logger.debug('looking for tags: {0}'.format(tags))
491 494  
492 495 for subfile, handle in self.iter_files(subfiles):
493 496 events = ('start', 'end')
... ... @@ -499,7 +502,7 @@ class XmlParser(object):
499 502 continue
500 503 if event == 'start':
501 504 if elem.tag in want_tags:
502   - logging.debug('remember start of tag {0} at {1}'
  505 + logger.debug('remember start of tag {0} at {1}'
503 506 .format(elem.tag, depth))
504 507 inside_tags.append((elem.tag, depth))
505 508 depth += 1
... ... @@ -515,18 +518,18 @@ class XmlParser(object):
515 518 if inside_tags[-1] == curr_tag:
516 519 inside_tags.pop()
517 520 else:
518   - logging.error('found end for wanted tag {0} '
  521 + logger.error('found end for wanted tag {0} '
519 522 'but last start tag {1} does not'
520 523 ' match'.format(curr_tag,
521 524 inside_tags[-1]))
522 525 # try to recover: close all deeper tags
523 526 while inside_tags and \
524 527 inside_tags[-1][1] >= depth:
525   - logging.debug('recover: pop {0}'
  528 + logger.debug('recover: pop {0}'
526 529 .format(inside_tags[-1]))
527 530 inside_tags.pop()
528 531 except IndexError: # no inside_tag[-1]
529   - logging.error('found end of {0} at depth {1} but '
  532 + logger.error('found end of {0} at depth {1} but '
530 533 'no start event')
531 534 # yield element
532 535 if is_wanted or not want_tags:
... ... @@ -543,12 +546,12 @@ class XmlParser(object):
543 546 if subfile is None: # this is no zip subfile but single xml
544 547 raise BadOOXML(self.filename, 'is neither zip nor xml')
545 548 elif subfile.endswith('.xml'):
546   - logger = logging.warning
  549 + log = logger.warning
547 550 else:
548   - logger = logging.debug
549   - logger(' xml-parsing for {0} failed ({1}). '
550   - .format(subfile, err) +
551   - 'Run iter_non_xml to investigate.')
  551 + log = logger.debug
  552 + log(' xml-parsing for {0} failed ({1}). '
  553 + .format(subfile, err) +
  554 + 'Run iter_non_xml to investigate.')
552 555 assert(depth == 0)
553 556  
554 557 def get_content_types(self):
... ... @@ -571,14 +574,14 @@ class XmlParser(object):
571 574 if extension.startswith('.'):
572 575 extension = extension[1:]
573 576 defaults.append((extension, elem.attrib['ContentType']))
574   - logging.debug('found content type for extension {0[0]}: {0[1]}'
  577 + logger.debug('found content type for extension {0[0]}: {0[1]}'
575 578 .format(defaults[-1]))
576 579 elif elem.tag.endswith('Override'):
577 580 subfile = elem.attrib['PartName']
578 581 if subfile.startswith('/'):
579 582 subfile = subfile[1:]
580 583 files.append((subfile, elem.attrib['ContentType']))
581   - logging.debug('found content type for subfile {0[0]}: {0[1]}'
  584 + logger.debug('found content type for subfile {0[0]}: {0[1]}'
582 585 .format(files[-1]))
583 586 return dict(files), dict(defaults)
584 587  
... ... @@ -595,14 +598,14 @@ class XmlParser(object):
595 598 To handle binary parts of an xlsb file, use xls_parser.parse_xlsb_part
596 599 """
597 600 if not self.did_iter_all:
598   - logging.warning('Did not iterate through complete file. '
  601 + logger.warning('Did not iterate through complete file. '
599 602 'Should run iter_xml() without args, first.')
600 603 if not self.subfiles_no_xml:
601   - raise StopIteration()
  604 + return
602 605  
603 606 # case of single xml files (office 2003+)
604 607 if self.is_single_xml():
605   - raise StopIteration() # "return"
  608 + return
606 609  
607 610 content_types, content_defaults = self.get_content_types()
608 611  
... ... @@ -628,7 +631,7 @@ def test():
628 631  
629 632 see module doc for more info
630 633 """
631   - logging.basicConfig(level=logging.DEBUG)
  634 + log_helper.enable_logging(False, logger.DEBUG)
632 635 if len(sys.argv) != 2:
633 636 print(u'To test this code, give me a single file as arg')
634 637 return 2
... ... @@ -641,12 +644,15 @@ def test():
641 644 for subfile, elem, depth in parser.iter_xml():
642 645 if depth < 4:
643 646 print(u'{0} {1}{2}'.format(subfile, ' ' * depth, debug_str(elem)))
644   - for index, (subfile, content_type) in enumerate(parser.iter_non_xml()):
  647 + for index, (subfile, content_type, _) in enumerate(parser.iter_non_xml()):
645 648 print(u'Non-XML subfile: {0} of type {1}'
646 649 .format(subfile, content_type or u'unknown'))
647 650 if index > 100:
648 651 print(u'...')
649 652 break
  653 +
  654 + log_helper.end_logging()
  655 +
650 656 return 0
651 657  
652 658  
... ...
oletools/ppt_parser.py
... ... @@ -41,8 +41,9 @@ file structure and will replace this module some time soon!
41 41 # 2016-09-13 PL: - fixed olefile import for Python 2+3
42 42 # - fixed format strings for Python 2.6 (issue #75)
43 43 # 2017-04-23 v0.51 PL: - fixed absolute imports and issue #101
  44 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
44 45  
45   -__version__ = '0.51'
  46 +__version__ = '0.54dev1'
46 47  
47 48  
48 49 # --- IMPORTS ------------------------------------------------------------------
... ... @@ -66,11 +67,41 @@ _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, &#39;..&#39;))
66 67 if not _parent_dir in sys.path:
67 68 sys.path.insert(0, _parent_dir)
68 69  
69   -from oletools.thirdparty.olefile import olefile
  70 +import olefile
  71 +
  72 +
  73 +# TODO: this is a temporary fix until all logging features are unified in oletools
  74 +def get_logger(name, level=logging.CRITICAL+1):
  75 + """
  76 + Create a suitable logger object for this module.
  77 + The goal is not to change settings of the root logger, to avoid getting
  78 + other modules' logs on the screen.
  79 + If a logger exists with same name, reuse it. (Else it would have duplicate
  80 + handlers and messages would be doubled.)
  81 + The level is set to CRITICAL+1 by default, to avoid any logging.
  82 + """
  83 + # First, test if there is already a logger with the same name, else it
  84 + # will generate duplicate messages (due to duplicate handlers):
  85 + if name in logging.Logger.manager.loggerDict:
  86 + #NOTE: another less intrusive but more "hackish" solution would be to
  87 + # use getLogger then test if its effective level is not default.
  88 + logger = logging.getLogger(name)
  89 + # make sure level is OK:
  90 + logger.setLevel(level)
  91 + return logger
  92 + # get a new logger:
  93 + logger = logging.getLogger(name)
  94 + # only add a NullHandler for this logger, it is up to the application
  95 + # to configure its own logging:
  96 + logger.addHandler(logging.NullHandler())
  97 + logger.setLevel(level)
  98 + return logger
  99 +
  100 +
70 101  
71 102  
72 103 # a global logger object used for debugging:
73   -log = olefile.get_logger('ppt')
  104 +log = get_logger('ppt')
74 105  
75 106  
76 107 def enable_logging():
... ...
oletools/ppt_record_parser.py
... ... @@ -63,6 +63,7 @@ except ImportError:
63 63 sys.path.insert(0, PARENT_DIR)
64 64 del PARENT_DIR
65 65 from oletools import record_base
  66 +from oletools.common.errors import FileIsEncryptedError
66 67  
67 68  
68 69 # types of relevant records (there are much more than listed here)
... ... @@ -147,13 +148,17 @@ def is_ppt(filename):
147 148  
148 149 Param filename can be anything that OleFileIO constructor accepts: name of
149 150 file or file data or data stream.
  151 +
  152 + see also: oleid.OleID.check_powerpoint
150 153 """
151 154 have_current_user = False
152 155 have_user_edit = False
153 156 have_persist_dir = False
154 157 have_document_container = False
  158 + ppt_file = None
155 159 try:
156   - for stream in PptFile(filename).iter_streams():
  160 + ppt_file = PptFile(filename)
  161 + for stream in ppt_file.iter_streams():
157 162 if stream.name == 'Current User':
158 163 for record in stream.iter_records():
159 164 if isinstance(record, PptRecordCurrentUser):
... ... @@ -176,6 +181,11 @@ def is_ppt(filename):
176 181 return True
177 182 else: # ignore other streams/storages since they are optional
178 183 continue
  184 + except FileIsEncryptedError:
  185 + assert ppt_file is not None, \
  186 + 'Encryption error should not be raised from just opening OLE file.'
  187 + # just rely on stream names, copied from oleid
  188 + return ppt_file.exists('PowerPoint Document')
179 189 except Exception:
180 190 pass
181 191 return False
... ...
oletools/pyxswf.py
... ... @@ -57,8 +57,9 @@ http://www.decalage.info/python/oletools
57 57 # 2016-09-06 v0.50 PL: - updated to match the rtfobj API
58 58 # 2016-10-25 PL: - fixed print for Python 3
59 59 # 2016-11-01 PL: - replaced StringIO by BytesIO for Python 3
  60 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
60 61  
61   -__version__ = '0.50'
  62 +__version__ = '0.54dev1'
62 63  
63 64 #------------------------------------------------------------------------------
64 65 # TODO:
... ... @@ -78,7 +79,7 @@ import optparse, sys, os
78 79 from . import rtfobj
79 80 from io import BytesIO
80 81 from .thirdparty.xxxswf import xxxswf
81   -from .thirdparty import olefile
  82 +import olefile
82 83  
83 84  
84 85 #=== MAIN =================================================================
... ...
oletools/record_base.py
... ... @@ -36,11 +36,15 @@ from __future__ import print_function
36 36 # -----------------------------------------------------------------------------
37 37 # CHANGELOG:
38 38 # 2017-11-30 v0.01 CH: - first version based on xls_parser
  39 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  40 +
  41 +__version__ = '0.54dev1'
39 42  
40 43 # -----------------------------------------------------------------------------
41 44 # TODO:
42 45 # - read DocumentSummaryInformation first to get more info about streams
43 46 # (maybe content type or so; identify streams that are never record-based)
  47 +# Or use oleid to avoid same functionality in several files
44 48 # - think about integrating this with olefile itself
45 49  
46 50 # -----------------------------------------------------------------------------
... ... @@ -57,17 +61,19 @@ import os.path
57 61 from io import SEEK_CUR
58 62 import logging
59 63  
  64 +import olefile
  65 +
60 66 try:
61   - from oletools.thirdparty import olefile
  67 + from oletools.common.errors import FileIsEncryptedError
62 68 except ImportError:
63 69 # little hack to allow absolute imports even if oletools is not installed.
64   - # Copied from olevba.py
65 70 PARENT_DIR = os.path.normpath(os.path.dirname(os.path.dirname(
66 71 os.path.abspath(__file__))))
67 72 if PARENT_DIR not in sys.path:
68 73 sys.path.insert(0, PARENT_DIR)
69 74 del PARENT_DIR
70   - from oletools.thirdparty import olefile
  75 + from oletools.common.errors import FileIsEncryptedError
  76 +from oletools import oleid
71 77  
72 78  
73 79 ###############################################################################
... ... @@ -118,6 +124,12 @@ class OleRecordFile(olefile.OleFileIO):
118 124 Subclass of OleFileIO!
119 125 """
120 126  
  127 + def open(self, filename, *args, **kwargs):
  128 + """Call OleFileIO.open, raise error if is encrypted."""
  129 + #super(OleRecordFile, self).open(filename, *args, **kwargs)
  130 + OleFileIO.open(self, filename, *args, **kwargs)
  131 + self.is_encrypted = oleid.OleID(self).check_encrypted().value
  132 +
121 133 @classmethod
122 134 def stream_class_for_name(cls, stream_name):
123 135 """ helper for iter_streams, must be overwritten in subclasses
... ... @@ -149,7 +161,8 @@ class OleRecordFile(olefile.OleFileIO):
149 161 stream = clz(self._open(direntry.isectStart, direntry.size),
150 162 direntry.size,
151 163 None if is_orphan else direntry.name,
152   - direntry.entry_type)
  164 + direntry.entry_type,
  165 + self.is_encrypted)
153 166 yield stream
154 167 stream.close()
155 168  
... ... @@ -162,13 +175,14 @@ class OleRecordStream(object):
162 175 abstract base class
163 176 """
164 177  
165   - def __init__(self, stream, size, name, stream_type):
  178 + def __init__(self, stream, size, name, stream_type, is_encrypted=False):
166 179 self.stream = stream
167 180 self.size = size
168 181 self.name = name
169 182 if stream_type not in ENTRY_TYPE2STR:
170 183 raise ValueError('Unknown stream type: {0}'.format(stream_type))
171 184 self.stream_type = stream_type
  185 + self.is_encrypted = is_encrypted
172 186  
173 187 def read_record_head(self):
174 188 """ read first few bytes of record to determine size and type
... ... @@ -197,6 +211,9 @@ class OleRecordStream(object):
197 211  
198 212 Stream must be positioned at start of records (e.g. start of stream).
199 213 """
  214 + if self.is_encrypted:
  215 + raise FileIsEncryptedError()
  216 +
200 217 while True:
201 218 # unpacking as in olevba._extract_vba
202 219 pos = self.stream.tell()
... ... @@ -241,6 +258,8 @@ class OleSummaryInformationStream(OleRecordStream):
241 258  
242 259 Do nothing so far. OleFileIO reads quite some info from this. For more info
243 260 see [MS-OSHARED] 2.3.3 and [MS-OLEPS] 2.21 and references therein.
  261 +
  262 + See also: info read in oleid.py.
244 263 """
245 264 def iter_records(self, fill_data=False):
246 265 """ yields nothing, stops at once """
... ...
oletools/rtfobj.py
... ... @@ -85,8 +85,11 @@ http://www.decalage.info/python/oletools
85 85 # 2018-04-30 PL: - handle "\'" obfuscation trick - issue #281
86 86 # 2018-05-10 PL: - fixed issues #303 #307: several destination cwords were incorrect
87 87 # 2018-05-17 PL: - fixed issue #273: bytes constants instead of str
  88 +# 2018-05-31 v0.53.1 PP: - fixed issue #316: whitespace after \bin on Python 3
  89 +# 2018-06-22 v0.53.2 PL: - fixed issue #327: added "\pnaiu" & "\pnaiud"
  90 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
88 91  
89   -__version__ = '0.53'
  92 +__version__ = '0.54dev1'
90 93  
91 94 # ------------------------------------------------------------------------------
92 95 # TODO:
... ... @@ -119,7 +122,7 @@ if not _parent_dir in sys.path:
119 122 from oletools.thirdparty.xglob import xglob
120 123 from oletools.thirdparty.tablestream import tablestream
121 124 from oletools import oleobj
122   -from oletools.thirdparty.olefile import olefile
  125 +import olefile
123 126 from oletools.common import clsid
124 127  
125 128 # === LOGGING =================================================================
... ... @@ -302,6 +305,8 @@ DESTINATION_CONTROL_WORDS = frozenset((
302 305 b"xmlattrname", b"xmlattrvalue", b"xmlclose", b"xmlname", b"xmlnstbl", b"xmlopen",
303 306 # added for issue #292: https://github.com/decalage2/oletools/issues/292
304 307 b"margSz",
  308 + # added for issue #327:
  309 + b"pnaiu", b"pnaiud",
305 310  
306 311 # It seems \private should not be treated as a destination (issue #178)
307 312 # Same for \pxe (issue #196)
... ... @@ -578,7 +583,7 @@ class RtfParser(object):
578 583 # it should be treated as a null length:
579 584 binlen=0
580 585 # ignore optional space after \bin
581   - if self.data[self.index] == ' ':
  586 + if ord(self.data[self.index:self.index + 1]) == ord(' '):
582 587 log.debug('\\bin: ignoring whitespace before data')
583 588 self.index += 1
584 589 log.debug('\\bin: reading %d bytes of binary data' % binlen)
... ... @@ -717,7 +722,7 @@ class RtfObjParser(RtfParser):
717 722 def control_symbol(self, matchobject):
718 723 # log.debug('control symbol %r at index %Xh' % (matchobject.group(), self.index))
719 724 symbol = matchobject.group()[1:2]
720   - if symbol == "'":
  725 + if symbol == b"'":
721 726 # read the two hex digits following "\'" - which can be any characters, not just hex digits
722 727 # (because within an objdata destination, they are simply ignored)
723 728 hexdigits = self.data[self.index+2:self.index+4]
... ...
oletools/thirdparty/colorclass/LICENSE.txt deleted
1   -The MIT License (MIT)
2   -
3   -Copyright (c) 2014 Robpol86
4   -
5   -Permission is hereby granted, free of charge, to any person obtaining a copy
6   -of this software and associated documentation files (the "Software"), to deal
7   -in the Software without restriction, including without limitation the rights
8   -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9   -copies of the Software, and to permit persons to whom the Software is
10   -furnished to do so, subject to the following conditions:
11   -
12   -The above copyright notice and this permission notice shall be included in all
13   -copies or substantial portions of the Software.
14   -
15   -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16   -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17   -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18   -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19   -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20   -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21   -SOFTWARE.
oletools/thirdparty/colorclass/__init__.py deleted
1   -"""Colorful worry-free console applications for Linux, Mac OS X, and Windows.
2   -
3   -Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called.
4   -
5   -Gives you expected and sane results from methods like len() and .capitalize().
6   -
7   -https://github.com/Robpol86/colorclass
8   -https://pypi.python.org/pypi/colorclass
9   -"""
10   -
11   -from colorclass.codes import list_tags # noqa
12   -from colorclass.color import Color # noqa
13   -from colorclass.toggles import disable_all_colors # noqa
14   -from colorclass.toggles import disable_if_no_tty # noqa
15   -from colorclass.toggles import enable_all_colors # noqa
16   -from colorclass.toggles import is_enabled # noqa
17   -from colorclass.toggles import is_light # noqa
18   -from colorclass.toggles import set_dark_background # noqa
19   -from colorclass.toggles import set_light_background # noqa
20   -from colorclass.windows import Windows # noqa
21   -
22   -
23   -__all__ = (
24   - 'Color',
25   - 'disable_all_colors',
26   - 'enable_all_colors',
27   - 'is_enabled',
28   - 'is_light',
29   - 'list_tags',
30   - 'set_dark_background',
31   - 'set_light_background',
32   - 'Windows',
33   -)
34   -
35   -
36   -__author__ = '@Robpol86'
37   -__license__ = 'MIT'
38   -__version__ = '2.2.0'
oletools/thirdparty/colorclass/__main__.py deleted
1   -"""Called by "python -m". Allows package to be used as a script.
2   -
3   -Example usage:
4   -echo "{red}Red{/red}" |python -m colorclass
5   -"""
6   -
7   -from __future__ import print_function
8   -
9   -import fileinput
10   -import os
11   -
12   -from colorclass.color import Color
13   -from colorclass.toggles import disable_all_colors
14   -from colorclass.toggles import enable_all_colors
15   -from colorclass.toggles import set_dark_background
16   -from colorclass.toggles import set_light_background
17   -from colorclass.windows import Windows
18   -
19   -TRUTHY = ('true', '1', 'yes', 'on')
20   -
21   -
22   -if __name__ == '__main__':
23   - if os.environ.get('COLOR_ENABLE', '').lower() in TRUTHY:
24   - enable_all_colors()
25   - elif os.environ.get('COLOR_DISABLE', '').lower() in TRUTHY:
26   - disable_all_colors()
27   - if os.environ.get('COLOR_LIGHT', '').lower() in TRUTHY:
28   - set_light_background()
29   - elif os.environ.get('COLOR_DARK', '').lower() in TRUTHY:
30   - set_dark_background()
31   - Windows.enable()
32   - for LINE in fileinput.input():
33   - print(Color(LINE))
oletools/thirdparty/colorclass/codes.py deleted
1   -"""Handles mapping between color names and ANSI codes and determining auto color codes."""
2   -
3   -import sys
4   -from collections import Mapping
5   -
6   -BASE_CODES = {
7   - '/all': 0, 'b': 1, 'f': 2, 'i': 3, 'u': 4, 'flash': 5, 'outline': 6, 'negative': 7, 'invis': 8, 'strike': 9,
8   - '/b': 22, '/f': 22, '/i': 23, '/u': 24, '/flash': 25, '/outline': 26, '/negative': 27, '/invis': 28,
9   - '/strike': 29, '/fg': 39, '/bg': 49,
10   -
11   - 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37,
12   -
13   - 'bgblack': 40, 'bgred': 41, 'bggreen': 42, 'bgyellow': 43, 'bgblue': 44, 'bgmagenta': 45, 'bgcyan': 46,
14   - 'bgwhite': 47,
15   -
16   - 'hiblack': 90, 'hired': 91, 'higreen': 92, 'hiyellow': 93, 'hiblue': 94, 'himagenta': 95, 'hicyan': 96,
17   - 'hiwhite': 97,
18   -
19   - 'hibgblack': 100, 'hibgred': 101, 'hibggreen': 102, 'hibgyellow': 103, 'hibgblue': 104, 'hibgmagenta': 105,
20   - 'hibgcyan': 106, 'hibgwhite': 107,
21   -
22   - 'autored': None, 'autoblack': None, 'automagenta': None, 'autowhite': None, 'autoblue': None, 'autoyellow': None,
23   - 'autogreen': None, 'autocyan': None,
24   -
25   - 'autobgred': None, 'autobgblack': None, 'autobgmagenta': None, 'autobgwhite': None, 'autobgblue': None,
26   - 'autobgyellow': None, 'autobggreen': None, 'autobgcyan': None,
27   -
28   - '/black': 39, '/red': 39, '/green': 39, '/yellow': 39, '/blue': 39, '/magenta': 39, '/cyan': 39, '/white': 39,
29   - '/hiblack': 39, '/hired': 39, '/higreen': 39, '/hiyellow': 39, '/hiblue': 39, '/himagenta': 39, '/hicyan': 39,
30   - '/hiwhite': 39,
31   -
32   - '/bgblack': 49, '/bgred': 49, '/bggreen': 49, '/bgyellow': 49, '/bgblue': 49, '/bgmagenta': 49, '/bgcyan': 49,
33   - '/bgwhite': 49, '/hibgblack': 49, '/hibgred': 49, '/hibggreen': 49, '/hibgyellow': 49, '/hibgblue': 49,
34   - '/hibgmagenta': 49, '/hibgcyan': 49, '/hibgwhite': 49,
35   -
36   - '/autored': 39, '/autoblack': 39, '/automagenta': 39, '/autowhite': 39, '/autoblue': 39, '/autoyellow': 39,
37   - '/autogreen': 39, '/autocyan': 39,
38   -
39   - '/autobgred': 49, '/autobgblack': 49, '/autobgmagenta': 49, '/autobgwhite': 49, '/autobgblue': 49,
40   - '/autobgyellow': 49, '/autobggreen': 49, '/autobgcyan': 49,
41   -}
42   -
43   -
44   -class ANSICodeMapping(Mapping):
45   - """Read-only dictionary, resolves closing tags and automatic colors. Iterates only used color tags.
46   -
47   - :cvar bool DISABLE_COLORS: Disable colors (strip color codes).
48   - :cvar bool LIGHT_BACKGROUND: Use low intensity color codes.
49   - """
50   -
51   - DISABLE_COLORS = False
52   - LIGHT_BACKGROUND = False
53   -
54   - def __init__(self, value_markup):
55   - """Constructor.
56   -
57   - :param str value_markup: String with {color} tags.
58   - """
59   - self.whitelist = [k for k in BASE_CODES if '{' + k + '}' in value_markup]
60   -
61   - def __getitem__(self, item):
62   - """Return value for key or None if colors are disabled.
63   -
64   - :param str item: Key.
65   -
66   - :return: Color code integer.
67   - :rtype: int
68   - """
69   - if item not in self.whitelist:
70   - raise KeyError(item)
71   - if self.DISABLE_COLORS:
72   - return None
73   - return getattr(self, item, BASE_CODES[item])
74   -
75   - def __iter__(self):
76   - """Iterate dictionary."""
77   - return iter(self.whitelist)
78   -
79   - def __len__(self):
80   - """Dictionary length."""
81   - return len(self.whitelist)
82   -
83   - @classmethod
84   - def disable_all_colors(cls):
85   - """Disable all colors. Strips any color tags or codes."""
86   - cls.DISABLE_COLORS = True
87   -
88   - @classmethod
89   - def enable_all_colors(cls):
90   - """Enable all colors. Strips any color tags or codes."""
91   - cls.DISABLE_COLORS = False
92   -
93   - @classmethod
94   - def disable_if_no_tty(cls):
95   - """Disable all colors only if there is no TTY available.
96   -
97   - :return: True if colors are disabled, False if stderr or stdout is a TTY.
98   - :rtype: bool
99   - """
100   - if sys.stdout.isatty() or sys.stderr.isatty():
101   - return False
102   - cls.disable_all_colors()
103   - return True
104   -
105   - @classmethod
106   - def set_dark_background(cls):
107   - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
108   - cls.LIGHT_BACKGROUND = False
109   -
110   - @classmethod
111   - def set_light_background(cls):
112   - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
113   - cls.LIGHT_BACKGROUND = True
114   -
115   - @property
116   - def autoblack(self):
117   - """Return automatic black foreground color depending on background color."""
118   - return BASE_CODES['black' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblack']
119   -
120   - @property
121   - def autored(self):
122   - """Return automatic red foreground color depending on background color."""
123   - return BASE_CODES['red' if ANSICodeMapping.LIGHT_BACKGROUND else 'hired']
124   -
125   - @property
126   - def autogreen(self):
127   - """Return automatic green foreground color depending on background color."""
128   - return BASE_CODES['green' if ANSICodeMapping.LIGHT_BACKGROUND else 'higreen']
129   -
130   - @property
131   - def autoyellow(self):
132   - """Return automatic yellow foreground color depending on background color."""
133   - return BASE_CODES['yellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiyellow']
134   -
135   - @property
136   - def autoblue(self):
137   - """Return automatic blue foreground color depending on background color."""
138   - return BASE_CODES['blue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblue']
139   -
140   - @property
141   - def automagenta(self):
142   - """Return automatic magenta foreground color depending on background color."""
143   - return BASE_CODES['magenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'himagenta']
144   -
145   - @property
146   - def autocyan(self):
147   - """Return automatic cyan foreground color depending on background color."""
148   - return BASE_CODES['cyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hicyan']
149   -
150   - @property
151   - def autowhite(self):
152   - """Return automatic white foreground color depending on background color."""
153   - return BASE_CODES['white' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiwhite']
154   -
155   - @property
156   - def autobgblack(self):
157   - """Return automatic black background color depending on background color."""
158   - return BASE_CODES['bgblack' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblack']
159   -
160   - @property
161   - def autobgred(self):
162   - """Return automatic red background color depending on background color."""
163   - return BASE_CODES['bgred' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgred']
164   -
165   - @property
166   - def autobggreen(self):
167   - """Return automatic green background color depending on background color."""
168   - return BASE_CODES['bggreen' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibggreen']
169   -
170   - @property
171   - def autobgyellow(self):
172   - """Return automatic yellow background color depending on background color."""
173   - return BASE_CODES['bgyellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgyellow']
174   -
175   - @property
176   - def autobgblue(self):
177   - """Return automatic blue background color depending on background color."""
178   - return BASE_CODES['bgblue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblue']
179   -
180   - @property
181   - def autobgmagenta(self):
182   - """Return automatic magenta background color depending on background color."""
183   - return BASE_CODES['bgmagenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgmagenta']
184   -
185   - @property
186   - def autobgcyan(self):
187   - """Return automatic cyan background color depending on background color."""
188   - return BASE_CODES['bgcyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgcyan']
189   -
190   - @property
191   - def autobgwhite(self):
192   - """Return automatic white background color depending on background color."""
193   - return BASE_CODES['bgwhite' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgwhite']
194   -
195   -
196   -def list_tags():
197   - """List the available tags.
198   -
199   - :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value.
200   - :rtype: list
201   - """
202   - # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].
203   - reverse_dict = dict()
204   - for tag, ansi in sorted(BASE_CODES.items()):
205   - if tag.startswith('/'):
206   - reverse_dict[tag] = [ansi, None, None]
207   - else:
208   - reverse_dict['/' + tag][1:] = [tag, ansi]
209   -
210   - # Collapse
211   - four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()]
212   -
213   - # Sort.
214   - def sorter(four_item):
215   - """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors.
216   -
217   - :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value]
218   -
219   - :return Sorting weight.
220   - :rtype: int
221   - """
222   - if not four_item[2]: # /all /fg /bg
223   - return four_item[3] - 200
224   - if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors
225   - return four_item[2] - 100
226   - return four_item[2]
227   - four_item_tuples.sort(key=sorter)
228   -
229   - return four_item_tuples
oletools/thirdparty/colorclass/color.py deleted
1   -"""Color class used by library users."""
2   -
3   -from colorclass.core import ColorStr
4   -
5   -
6   -class Color(ColorStr):
7   - """Unicode (str in Python3) subclass with ANSI terminal text color support.
8   -
9   - Example syntax: Color('{red}Sample Text{/red}')
10   -
11   - Example without parsing logic: Color('{red}Sample Text{/red}', keep_tags=True)
12   -
13   - For a list of codes, call: colorclass.list_tags()
14   - """
15   -
16   - @classmethod
17   - def colorize(cls, color, string, auto=False):
18   - """Color-code entire string using specified color.
19   -
20   - :param str color: Color of string.
21   - :param str string: String to colorize.
22   - :param bool auto: Enable auto-color (dark/light terminal).
23   -
24   - :return: Class instance for colorized string.
25   - :rtype: Color
26   - """
27   - tag = '{0}{1}'.format('auto' if auto else '', color)
28   - return cls('{%s}%s{/%s}' % (tag, string, tag))
29   -
30   - @classmethod
31   - def black(cls, string, auto=False):
32   - """Color-code entire string.
33   -
34   - :param str string: String to colorize.
35   - :param bool auto: Enable auto-color (dark/light terminal).
36   -
37   - :return: Class instance for colorized string.
38   - :rtype: Color
39   - """
40   - return cls.colorize('black', string, auto=auto)
41   -
42   - @classmethod
43   - def bgblack(cls, string, auto=False):
44   - """Color-code entire string.
45   -
46   - :param str string: String to colorize.
47   - :param bool auto: Enable auto-color (dark/light terminal).
48   -
49   - :return: Class instance for colorized string.
50   - :rtype: Color
51   - """
52   - return cls.colorize('bgblack', string, auto=auto)
53   -
54   - @classmethod
55   - def red(cls, string, auto=False):
56   - """Color-code entire string.
57   -
58   - :param str string: String to colorize.
59   - :param bool auto: Enable auto-color (dark/light terminal).
60   -
61   - :return: Class instance for colorized string.
62   - :rtype: Color
63   - """
64   - return cls.colorize('red', string, auto=auto)
65   -
66   - @classmethod
67   - def bgred(cls, string, auto=False):
68   - """Color-code entire string.
69   -
70   - :param str string: String to colorize.
71   - :param bool auto: Enable auto-color (dark/light terminal).
72   -
73   - :return: Class instance for colorized string.
74   - :rtype: Color
75   - """
76   - return cls.colorize('bgred', string, auto=auto)
77   -
78   - @classmethod
79   - def green(cls, string, auto=False):
80   - """Color-code entire string.
81   -
82   - :param str string: String to colorize.
83   - :param bool auto: Enable auto-color (dark/light terminal).
84   -
85   - :return: Class instance for colorized string.
86   - :rtype: Color
87   - """
88   - return cls.colorize('green', string, auto=auto)
89   -
90   - @classmethod
91   - def bggreen(cls, string, auto=False):
92   - """Color-code entire string.
93   -
94   - :param str string: String to colorize.
95   - :param bool auto: Enable auto-color (dark/light terminal).
96   -
97   - :return: Class instance for colorized string.
98   - :rtype: Color
99   - """
100   - return cls.colorize('bggreen', string, auto=auto)
101   -
102   - @classmethod
103   - def yellow(cls, string, auto=False):
104   - """Color-code entire string.
105   -
106   - :param str string: String to colorize.
107   - :param bool auto: Enable auto-color (dark/light terminal).
108   -
109   - :return: Class instance for colorized string.
110   - :rtype: Color
111   - """
112   - return cls.colorize('yellow', string, auto=auto)
113   -
114   - @classmethod
115   - def bgyellow(cls, string, auto=False):
116   - """Color-code entire string.
117   -
118   - :param str string: String to colorize.
119   - :param bool auto: Enable auto-color (dark/light terminal).
120   -
121   - :return: Class instance for colorized string.
122   - :rtype: Color
123   - """
124   - return cls.colorize('bgyellow', string, auto=auto)
125   -
126   - @classmethod
127   - def blue(cls, string, auto=False):
128   - """Color-code entire string.
129   -
130   - :param str string: String to colorize.
131   - :param bool auto: Enable auto-color (dark/light terminal).
132   -
133   - :return: Class instance for colorized string.
134   - :rtype: Color
135   - """
136   - return cls.colorize('blue', string, auto=auto)
137   -
138   - @classmethod
139   - def bgblue(cls, string, auto=False):
140   - """Color-code entire string.
141   -
142   - :param str string: String to colorize.
143   - :param bool auto: Enable auto-color (dark/light terminal).
144   -
145   - :return: Class instance for colorized string.
146   - :rtype: Color
147   - """
148   - return cls.colorize('bgblue', string, auto=auto)
149   -
150   - @classmethod
151   - def magenta(cls, string, auto=False):
152   - """Color-code entire string.
153   -
154   - :param str string: String to colorize.
155   - :param bool auto: Enable auto-color (dark/light terminal).
156   -
157   - :return: Class instance for colorized string.
158   - :rtype: Color
159   - """
160   - return cls.colorize('magenta', string, auto=auto)
161   -
162   - @classmethod
163   - def bgmagenta(cls, string, auto=False):
164   - """Color-code entire string.
165   -
166   - :param str string: String to colorize.
167   - :param bool auto: Enable auto-color (dark/light terminal).
168   -
169   - :return: Class instance for colorized string.
170   - :rtype: Color
171   - """
172   - return cls.colorize('bgmagenta', string, auto=auto)
173   -
174   - @classmethod
175   - def cyan(cls, string, auto=False):
176   - """Color-code entire string.
177   -
178   - :param str string: String to colorize.
179   - :param bool auto: Enable auto-color (dark/light terminal).
180   -
181   - :return: Class instance for colorized string.
182   - :rtype: Color
183   - """
184   - return cls.colorize('cyan', string, auto=auto)
185   -
186   - @classmethod
187   - def bgcyan(cls, string, auto=False):
188   - """Color-code entire string.
189   -
190   - :param str string: String to colorize.
191   - :param bool auto: Enable auto-color (dark/light terminal).
192   -
193   - :return: Class instance for colorized string.
194   - :rtype: Color
195   - """
196   - return cls.colorize('bgcyan', string, auto=auto)
197   -
198   - @classmethod
199   - def white(cls, string, auto=False):
200   - """Color-code entire string.
201   -
202   - :param str string: String to colorize.
203   - :param bool auto: Enable auto-color (dark/light terminal).
204   -
205   - :return: Class instance for colorized string.
206   - :rtype: Color
207   - """
208   - return cls.colorize('white', string, auto=auto)
209   -
210   - @classmethod
211   - def bgwhite(cls, string, auto=False):
212   - """Color-code entire string.
213   -
214   - :param str string: String to colorize.
215   - :param bool auto: Enable auto-color (dark/light terminal).
216   -
217   - :return: Class instance for colorized string.
218   - :rtype: Color
219   - """
220   - return cls.colorize('bgwhite', string, auto=auto)
oletools/thirdparty/colorclass/core.py deleted
1   -"""String subclass that handles ANSI color codes."""
2   -
3   -from colorclass.codes import ANSICodeMapping
4   -from colorclass.parse import parse_input, RE_SPLIT
5   -from colorclass.search import build_color_index, find_char_color
6   -
7   -PARENT_CLASS = type(u'')
8   -
9   -
10   -def apply_text(incoming, func):
11   - """Call `func` on text portions of incoming color string.
12   -
13   - :param iter incoming: Incoming string/ColorStr/string-like object to iterate.
14   - :param func: Function to call with string portion as first and only parameter.
15   -
16   - :return: Modified string, same class type as incoming string.
17   - """
18   - split = RE_SPLIT.split(incoming)
19   - for i, item in enumerate(split):
20   - if not item or RE_SPLIT.match(item):
21   - continue
22   - split[i] = func(item)
23   - return incoming.__class__().join(split)
24   -
25   -
26   -class ColorBytes(bytes):
27   - """Str (bytes in Python3) subclass, .decode() overridden to return unicode (str in Python3) subclass instance."""
28   -
29   - def __new__(cls, *args, **kwargs):
30   - """Save original class so decode() returns an instance of it."""
31   - original_class = kwargs.pop('original_class')
32   - combined_args = [cls] + list(args)
33   - instance = bytes.__new__(*combined_args, **kwargs)
34   - instance.original_class = original_class
35   - return instance
36   -
37   - def decode(self, encoding='utf-8', errors='strict'):
38   - """Decode using the codec registered for encoding. Default encoding is 'utf-8'.
39   -
40   - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
41   - raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
42   - registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
43   -
44   - :param str encoding: Codec.
45   - :param str errors: Error handling scheme.
46   - """
47   - original_class = getattr(self, 'original_class')
48   - return original_class(super(ColorBytes, self).decode(encoding, errors))
49   -
50   -
51   -class ColorStr(PARENT_CLASS):
52   - """Core color class."""
53   -
54   - def __new__(cls, *args, **kwargs):
55   - """Parse color markup and instantiate."""
56   - keep_tags = kwargs.pop('keep_tags', False)
57   -
58   - # Parse string.
59   - value_markup = args[0] if args else PARENT_CLASS() # e.g. '{red}test{/red}'
60   - value_colors, value_no_colors = parse_input(value_markup, ANSICodeMapping.DISABLE_COLORS, keep_tags)
61   - color_index = build_color_index(value_colors)
62   -
63   - # Instantiate.
64   - color_args = [cls, value_colors] + list(args[1:])
65   - instance = PARENT_CLASS.__new__(*color_args, **kwargs)
66   -
67   - # Add additional attributes and return.
68   - instance.value_colors = value_colors
69   - instance.value_no_colors = value_no_colors
70   - instance.has_colors = value_colors != value_no_colors
71   - instance.color_index = color_index
72   - return instance
73   -
74   - def __add__(self, other):
75   - """Concatenate."""
76   - return self.__class__(self.value_colors + other, keep_tags=True)
77   -
78   - def __getitem__(self, item):
79   - """Retrieve character."""
80   - try:
81   - color_pos = self.color_index[int(item)]
82   - except TypeError: # slice
83   - return super(ColorStr, self).__getitem__(item)
84   - return self.__class__(find_char_color(self.value_colors, color_pos), keep_tags=True)
85   -
86   - def __iter__(self):
87   - """Yield one color-coded character at a time."""
88   - for color_pos in self.color_index:
89   - yield self.__class__(find_char_color(self.value_colors, color_pos))
90   -
91   - def __len__(self):
92   - """Length of string without color codes (what users expect)."""
93   - return self.value_no_colors.__len__()
94   -
95   - def __mod__(self, other):
96   - """String substitution (like printf)."""
97   - return self.__class__(self.value_colors % other, keep_tags=True)
98   -
99   - def __mul__(self, other):
100   - """Multiply string."""
101   - return self.__class__(self.value_colors * other, keep_tags=True)
102   -
103   - def __repr__(self):
104   - """Representation of a class instance (like datetime.datetime.now())."""
105   - return '{name}({value})'.format(name=self.__class__.__name__, value=repr(self.value_colors))
106   -
107   - def capitalize(self):
108   - """Return a copy of the string with only its first character capitalized."""
109   - return apply_text(self, lambda s: s.capitalize())
110   -
111   - def center(self, width, fillchar=None):
112   - """Return centered in a string of length width. Padding is done using the specified fill character or space.
113   -
114   - :param int width: Length of output string.
115   - :param str fillchar: Use this character instead of spaces.
116   - """
117   - if fillchar is not None:
118   - result = self.value_no_colors.center(width, fillchar)
119   - else:
120   - result = self.value_no_colors.center(width)
121   - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True)
122   -
123   - def count(self, sub, start=0, end=-1):
124   - """Return the number of non-overlapping occurrences of substring sub in string[start:end].
125   -
126   - Optional arguments start and end are interpreted as in slice notation.
127   -
128   - :param str sub: Substring to search.
129   - :param int start: Beginning position.
130   - :param int end: Stop comparison at this position.
131   - """
132   - return self.value_no_colors.count(sub, start, end)
133   -
134   - def endswith(self, suffix, start=0, end=None):
135   - """Return True if ends with the specified suffix, False otherwise.
136   -
137   - With optional start, test beginning at that position. With optional end, stop comparing at that position.
138   - suffix can also be a tuple of strings to try.
139   -
140   - :param str suffix: Suffix to search.
141   - :param int start: Beginning position.
142   - :param int end: Stop comparison at this position.
143   - """
144   - args = [suffix, start] + ([] if end is None else [end])
145   - return self.value_no_colors.endswith(*args)
146   -
147   - def encode(self, encoding=None, errors='strict'):
148   - """Encode using the codec registered for encoding. encoding defaults to the default encoding.
149   -
150   - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
151   - raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any
152   - other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors.
153   -
154   - :param str encoding: Codec.
155   - :param str errors: Error handling scheme.
156   - """
157   - return ColorBytes(super(ColorStr, self).encode(encoding, errors), original_class=self.__class__)
158   -
159   - def decode(self, encoding=None, errors='strict'):
160   - """Decode using the codec registered for encoding. encoding defaults to the default encoding.
161   -
162   - errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors
163   - raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name
164   - registered with codecs.register_error that is able to handle UnicodeDecodeErrors.
165   -
166   - :param str encoding: Codec.
167   - :param str errors: Error handling scheme.
168   - """
169   - return self.__class__(super(ColorStr, self).decode(encoding, errors), keep_tags=True)
170   -
171   - def find(self, sub, start=None, end=None):
172   - """Return the lowest index where substring sub is found, such that sub is contained within string[start:end].
173   -
174   - Optional arguments start and end are interpreted as in slice notation.
175   -
176   - :param str sub: Substring to search.
177   - :param int start: Beginning position.
178   - :param int end: Stop comparison at this position.
179   - """
180   - return self.value_no_colors.find(sub, start, end)
181   -
182   - def format(self, *args, **kwargs):
183   - """Return a formatted version, using substitutions from args and kwargs.
184   -
185   - The substitutions are identified by braces ('{' and '}').
186   - """
187   - return self.__class__(super(ColorStr, self).format(*args, **kwargs), keep_tags=True)
188   -
189   - def index(self, sub, start=None, end=None):
190   - """Like S.find() but raise ValueError when the substring is not found.
191   -
192   - :param str sub: Substring to search.
193   - :param int start: Beginning position.
194   - :param int end: Stop comparison at this position.
195   - """
196   - return self.value_no_colors.index(sub, start, end)
197   -
198   - def isalnum(self):
199   - """Return True if all characters in string are alphanumeric and there is at least one character in it."""
200   - return self.value_no_colors.isalnum()
201   -
202   - def isalpha(self):
203   - """Return True if all characters in string are alphabetic and there is at least one character in it."""
204   - return self.value_no_colors.isalpha()
205   -
206   - def isdecimal(self):
207   - """Return True if there are only decimal characters in string, False otherwise."""
208   - return self.value_no_colors.isdecimal()
209   -
210   - def isdigit(self):
211   - """Return True if all characters in string are digits and there is at least one character in it."""
212   - return self.value_no_colors.isdigit()
213   -
214   - def isnumeric(self):
215   - """Return True if there are only numeric characters in string, False otherwise."""
216   - return self.value_no_colors.isnumeric()
217   -
218   - def isspace(self):
219   - """Return True if all characters in string are whitespace and there is at least one character in it."""
220   - return self.value_no_colors.isspace()
221   -
222   - def istitle(self):
223   - """Return True if string is a titlecased string and there is at least one character in it.
224   -
225   - That is uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return
226   - False otherwise.
227   - """
228   - return self.value_no_colors.istitle()
229   -
230   - def isupper(self):
231   - """Return True if all cased characters are uppercase and there is at least one cased character in it."""
232   - return self.value_no_colors.isupper()
233   -
234   - def join(self, iterable):
235   - """Return a string which is the concatenation of the strings in the iterable.
236   -
237   - :param iterable: Join items in this iterable.
238   - """
239   - return self.__class__(super(ColorStr, self).join(iterable), keep_tags=True)
240   -
241   - def ljust(self, width, fillchar=None):
242   - """Return left-justified string of length width. Padding is done using the specified fill character or space.
243   -
244   - :param int width: Length of output string.
245   - :param str fillchar: Use this character instead of spaces.
246   - """
247   - if fillchar is not None:
248   - result = self.value_no_colors.ljust(width, fillchar)
249   - else:
250   - result = self.value_no_colors.ljust(width)
251   - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True)
252   -
253   - def rfind(self, sub, start=None, end=None):
254   - """Return the highest index where substring sub is found, such that sub is contained within string[start:end].
255   -
256   - Optional arguments start and end are interpreted as in slice notation.
257   -
258   - :param str sub: Substring to search.
259   - :param int start: Beginning position.
260   - :param int end: Stop comparison at this position.
261   - """
262   - return self.value_no_colors.rfind(sub, start, end)
263   -
264   - def rindex(self, sub, start=None, end=None):
265   - """Like .rfind() but raise ValueError when the substring is not found.
266   -
267   - :param str sub: Substring to search.
268   - :param int start: Beginning position.
269   - :param int end: Stop comparison at this position.
270   - """
271   - return self.value_no_colors.rindex(sub, start, end)
272   -
273   - def rjust(self, width, fillchar=None):
274   - """Return right-justified string of length width. Padding is done using the specified fill character or space.
275   -
276   - :param int width: Length of output string.
277   - :param str fillchar: Use this character instead of spaces.
278   - """
279   - if fillchar is not None:
280   - result = self.value_no_colors.rjust(width, fillchar)
281   - else:
282   - result = self.value_no_colors.rjust(width)
283   - return self.__class__(result.replace(self.value_no_colors, self.value_colors), keep_tags=True)
284   -
285   - def splitlines(self, keepends=False):
286   - """Return a list of the lines in the string, breaking at line boundaries.
287   -
288   - Line breaks are not included in the resulting list unless keepends is given and True.
289   -
290   - :param bool keepends: Include linebreaks.
291   - """
292   - return [self.__class__(l) for l in self.value_colors.splitlines(keepends)]
293   -
294   - def startswith(self, prefix, start=0, end=-1):
295   - """Return True if string starts with the specified prefix, False otherwise.
296   -
297   - With optional start, test beginning at that position. With optional end, stop comparing at that position. prefix
298   - can also be a tuple of strings to try.
299   -
300   - :param str prefix: Prefix to search.
301   - :param int start: Beginning position.
302   - :param int end: Stop comparison at this position.
303   - """
304   - return self.value_no_colors.startswith(prefix, start, end)
305   -
306   - def swapcase(self):
307   - """Return a copy of the string with uppercase characters converted to lowercase and vice versa."""
308   - return apply_text(self, lambda s: s.swapcase())
309   -
310   - def title(self):
311   - """Return a titlecased version of the string.
312   -
313   - That is words start with uppercase characters, all remaining cased characters have lowercase.
314   - """
315   - return apply_text(self, lambda s: s.title())
316   -
317   - def translate(self, table):
318   - """Return a copy of the string, where all characters have been mapped through the given translation table.
319   -
320   - Table must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None. Unmapped characters are left
321   - untouched. Characters mapped to None are deleted.
322   -
323   - :param table: Translation table.
324   - """
325   - return apply_text(self, lambda s: s.translate(table))
326   -
327   - def upper(self):
328   - """Return a copy of the string converted to uppercase."""
329   - return apply_text(self, lambda s: s.upper())
330   -
331   - def zfill(self, width):
332   - """Pad a numeric string with zeros on the left, to fill a field of the specified width.
333   -
334   - The string is never truncated.
335   -
336   - :param int width: Length of output string.
337   - """
338   - if not self.value_no_colors:
339   - result = self.value_no_colors.zfill(width)
340   - else:
341   - result = self.value_colors.replace(self.value_no_colors, self.value_no_colors.zfill(width))
342   - return self.__class__(result, keep_tags=True)
oletools/thirdparty/colorclass/parse.py deleted
1   -"""Parse color markup tags into ANSI escape sequences."""
2   -
3   -import re
4   -
5   -from colorclass.codes import ANSICodeMapping, BASE_CODES
6   -
7   -CODE_GROUPS = (
8   - tuple(set(str(i) for i in BASE_CODES.values() if i and (40 <= i <= 49 or 100 <= i <= 109))), # bg colors
9   - tuple(set(str(i) for i in BASE_CODES.values() if i and (30 <= i <= 39 or 90 <= i <= 99))), # fg colors
10   - ('1', '22'), ('2', '22'), ('3', '23'), ('4', '24'), ('5', '25'), ('6', '26'), ('7', '27'), ('8', '28'), ('9', '29'),
11   -)
12   -RE_ANSI = re.compile(r'(\033\[([\d;]+)m)')
13   -RE_COMBINE = re.compile(r'\033\[([\d;]+)m\033\[([\d;]+)m')
14   -RE_SPLIT = re.compile(r'(\033\[[\d;]+m)')
15   -
16   -
17   -def prune_overridden(ansi_string):
18   - """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes.
19   -
20   - :param str ansi_string: Incoming ansi_string with ANSI color codes.
21   -
22   - :return: Color string with pruned color sequences.
23   - :rtype: str
24   - """
25   - multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes.
26   -
27   - for escape, codes in multi_seqs:
28   - r_codes = list(reversed(codes.split(';')))
29   -
30   - # Nuke everything before {/all}.
31   - try:
32   - r_codes = r_codes[:r_codes.index('0') + 1]
33   - except ValueError:
34   - pass
35   -
36   - # Thin out groups.
37   - for group in CODE_GROUPS:
38   - for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]):
39   - r_codes.pop(pos)
40   -
41   - # Done.
42   - reduced_codes = ';'.join(sorted(r_codes, key=int))
43   - if codes != reduced_codes:
44   - ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm')
45   -
46   - return ansi_string
47   -
48   -
49   -def parse_input(tagged_string, disable_colors, keep_tags):
50   - """Perform the actual conversion of tags to ANSI escaped codes.
51   -
52   - Provides a version of the input without any colors for len() and other methods.
53   -
54   - :param str tagged_string: The input unicode value.
55   - :param bool disable_colors: Strip all colors in both outputs.
56   - :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences.
57   -
58   - :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors.
59   - :rtype: tuple
60   - """
61   - codes = ANSICodeMapping(tagged_string)
62   - output_colors = getattr(tagged_string, 'value_colors', tagged_string)
63   -
64   - # Convert: '{b}{red}' -> '\033[1m\033[31m'
65   - if not keep_tags:
66   - for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()):
67   - output_colors = output_colors.replace(tag, replacement)
68   -
69   - # Strip colors.
70   - output_no_colors = RE_ANSI.sub('', output_colors)
71   - if disable_colors:
72   - return output_no_colors, output_no_colors
73   -
74   - # Combine: '\033[1m\033[31m' -> '\033[1;31m'
75   - while True:
76   - simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors)
77   - if simplified == output_colors:
78   - break
79   - output_colors = simplified
80   -
81   - # Prune: '\033[31;32;33;34;35m' -> '\033[35m'
82   - output_colors = prune_overridden(output_colors)
83   -
84   - # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST'
85   - previous_escape = None
86   - segments = list()
87   - for item in (i for i in RE_SPLIT.split(output_colors) if i):
88   - if RE_SPLIT.match(item):
89   - if item != previous_escape:
90   - segments.append(item)
91   - previous_escape = item
92   - else:
93   - segments.append(item)
94   - output_colors = ''.join(segments)
95   -
96   - return output_colors, output_no_colors
oletools/thirdparty/colorclass/search.py deleted
1   -"""Determine color of characters that may or may not be adjacent to ANSI escape sequences."""
2   -
3   -from colorclass.parse import RE_SPLIT
4   -
5   -
6   -def build_color_index(ansi_string):
7   - """Build an index between visible characters and a string with invisible color codes.
8   -
9   - :param str ansi_string: String with color codes (ANSI escape sequences).
10   -
11   - :return: Position of visible characters in color string (indexes match non-color string).
12   - :rtype: tuple
13   - """
14   - mapping = list()
15   - color_offset = 0
16   - for item in (i for i in RE_SPLIT.split(ansi_string) if i):
17   - if RE_SPLIT.match(item):
18   - color_offset += len(item)
19   - else:
20   - for _ in range(len(item)):
21   - mapping.append(color_offset)
22   - color_offset += 1
23   - return tuple(mapping)
24   -
25   -
26   -def find_char_color(ansi_string, pos):
27   - """Determine what color a character is in the string.
28   -
29   - :param str ansi_string: String with color codes (ANSI escape sequences).
30   - :param int pos: Position of the character in the ansi_string.
31   -
32   - :return: Character along with all surrounding color codes.
33   - :rtype: str
34   - """
35   - result = list()
36   - position = 0 # Set to None when character is found.
37   - for item in (i for i in RE_SPLIT.split(ansi_string) if i):
38   - if RE_SPLIT.match(item):
39   - result.append(item)
40   - if position is not None:
41   - position += len(item)
42   - elif position is not None:
43   - for char in item:
44   - if position == pos:
45   - result.append(char)
46   - position = None
47   - break
48   - position += 1
49   - return ''.join(result)
oletools/thirdparty/colorclass/toggles.py deleted
1   -"""Convenience functions to enable/disable features."""
2   -
3   -from colorclass.codes import ANSICodeMapping
4   -
5   -
6   -def disable_all_colors():
7   - """Disable all colors. Strip any color tags or codes."""
8   - ANSICodeMapping.disable_all_colors()
9   -
10   -
11   -def enable_all_colors():
12   - """Enable colors."""
13   - ANSICodeMapping.enable_all_colors()
14   -
15   -
16   -def disable_if_no_tty():
17   - """Disable all colors if there is no TTY available.
18   -
19   - :return: True if colors are disabled, False if stderr or stdout is a TTY.
20   - :rtype: bool
21   - """
22   - return ANSICodeMapping.disable_if_no_tty()
23   -
24   -
25   -def is_enabled():
26   - """Are colors enabled."""
27   - return not ANSICodeMapping.DISABLE_COLORS
28   -
29   -
30   -def set_light_background():
31   - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
32   - ANSICodeMapping.set_light_background()
33   -
34   -
35   -def set_dark_background():
36   - """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
37   - ANSICodeMapping.set_dark_background()
38   -
39   -
40   -def is_light():
41   - """Are background colors for light backgrounds."""
42   - return ANSICodeMapping.LIGHT_BACKGROUND
oletools/thirdparty/colorclass/windows.py deleted
1   -"""Windows console screen buffer handlers."""
2   -
3   -from __future__ import print_function
4   -
5   -import atexit
6   -import ctypes
7   -import re
8   -import sys
9   -
10   -from colorclass.codes import ANSICodeMapping, BASE_CODES
11   -from colorclass.core import RE_SPLIT
12   -
13   -ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
14   -INVALID_HANDLE_VALUE = -1
15   -IS_WINDOWS = sys.platform == 'win32'
16   -RE_NUMBER_SEARCH = re.compile(r'\033\[([\d;]+)m')
17   -STD_ERROR_HANDLE = -12
18   -STD_OUTPUT_HANDLE = -11
19   -WINDOWS_CODES = {
20   - '/all': -33, '/fg': -39, '/bg': -49,
21   -
22   - 'black': 0, 'red': 4, 'green': 2, 'yellow': 6, 'blue': 1, 'magenta': 5, 'cyan': 3, 'white': 7,
23   -
24   - 'bgblack': -8, 'bgred': 64, 'bggreen': 32, 'bgyellow': 96, 'bgblue': 16, 'bgmagenta': 80, 'bgcyan': 48,
25   - 'bgwhite': 112,
26   -
27   - 'hiblack': 8, 'hired': 12, 'higreen': 10, 'hiyellow': 14, 'hiblue': 9, 'himagenta': 13, 'hicyan': 11, 'hiwhite': 15,
28   -
29   - 'hibgblack': 128, 'hibgred': 192, 'hibggreen': 160, 'hibgyellow': 224, 'hibgblue': 144, 'hibgmagenta': 208,
30   - 'hibgcyan': 176, 'hibgwhite': 240,
31   -
32   - '/black': -39, '/red': -39, '/green': -39, '/yellow': -39, '/blue': -39, '/magenta': -39, '/cyan': -39,
33   - '/white': -39, '/hiblack': -39, '/hired': -39, '/higreen': -39, '/hiyellow': -39, '/hiblue': -39, '/himagenta': -39,
34   - '/hicyan': -39, '/hiwhite': -39,
35   -
36   - '/bgblack': -49, '/bgred': -49, '/bggreen': -49, '/bgyellow': -49, '/bgblue': -49, '/bgmagenta': -49,
37   - '/bgcyan': -49, '/bgwhite': -49, '/hibgblack': -49, '/hibgred': -49, '/hibggreen': -49, '/hibgyellow': -49,
38   - '/hibgblue': -49, '/hibgmagenta': -49, '/hibgcyan': -49, '/hibgwhite': -49,
39   -}
40   -
41   -
42   -class COORD(ctypes.Structure):
43   - """COORD structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682119."""
44   -
45   - _fields_ = [
46   - ('X', ctypes.c_short),
47   - ('Y', ctypes.c_short),
48   - ]
49   -
50   -
51   -class SmallRECT(ctypes.Structure):
52   - """SMALL_RECT structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms686311."""
53   -
54   - _fields_ = [
55   - ('Left', ctypes.c_short),
56   - ('Top', ctypes.c_short),
57   - ('Right', ctypes.c_short),
58   - ('Bottom', ctypes.c_short),
59   - ]
60   -
61   -
62   -class ConsoleScreenBufferInfo(ctypes.Structure):
63   - """CONSOLE_SCREEN_BUFFER_INFO structure. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093."""
64   -
65   - _fields_ = [
66   - ('dwSize', COORD),
67   - ('dwCursorPosition', COORD),
68   - ('wAttributes', ctypes.c_ushort),
69   - ('srWindow', SmallRECT),
70   - ('dwMaximumWindowSize', COORD)
71   - ]
72   -
73   -
74   -def init_kernel32(kernel32=None):
75   - """Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.
76   -
77   - 1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of
78   - kernel32 to prevent overriding (or being overwritten by) user's own changes to ctypes.windll.kernel32.
79   - 2. While we're doing all this we might as well get the handles to STDOUT and STDERR streams.
80   - 3. If either stream has already been replaced set return value to INVALID_HANDLE_VALUE to indicate it shouldn't be
81   - replaced.
82   -
83   - :raise AttributeError: When called on a non-Windows platform.
84   -
85   - :param kernel32: Optional mock kernel32 object. For testing.
86   -
87   - :return: Loaded kernel32 instance, stderr handle (int), stdout handle (int).
88   - :rtype: tuple
89   - """
90   - if not kernel32:
91   - kernel32 = ctypes.LibraryLoader(ctypes.WinDLL).kernel32 # Load our own instance. Unique memory address.
92   - kernel32.GetStdHandle.argtypes = [ctypes.c_ulong]
93   - kernel32.GetStdHandle.restype = ctypes.c_void_p
94   - kernel32.GetConsoleScreenBufferInfo.argtypes = [
95   - ctypes.c_void_p,
96   - ctypes.POINTER(ConsoleScreenBufferInfo),
97   - ]
98   - kernel32.GetConsoleScreenBufferInfo.restype = ctypes.c_long
99   -
100   - # Get handles.
101   - if hasattr(sys.stderr, '_original_stream'):
102   - stderr = INVALID_HANDLE_VALUE
103   - else:
104   - stderr = kernel32.GetStdHandle(STD_ERROR_HANDLE)
105   - if hasattr(sys.stdout, '_original_stream'):
106   - stdout = INVALID_HANDLE_VALUE
107   - else:
108   - stdout = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
109   -
110   - return kernel32, stderr, stdout
111   -
112   -
113   -def get_console_info(kernel32, handle):
114   - """Get information about this current console window.
115   -
116   - http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
117   - https://code.google.com/p/colorama/issues/detail?id=47
118   - https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
119   -
120   - Windows 10 Insider since around February 2016 finally introduced support for ANSI colors. No need to replace stdout
121   - and stderr streams to intercept colors and issue multiple SetConsoleTextAttribute() calls for these consoles.
122   -
123   - :raise OSError: When GetConsoleScreenBufferInfo or GetConsoleMode API calls fail.
124   -
125   - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
126   - :param int handle: stderr or stdout handle.
127   -
128   - :return: Foreground and background colors (integers) as well as native ANSI support (bool).
129   - :rtype: tuple
130   - """
131   - # Query Win32 API.
132   - csbi = ConsoleScreenBufferInfo() # Populated by GetConsoleScreenBufferInfo.
133   - lpcsbi = ctypes.byref(csbi)
134   - dword = ctypes.c_ulong() # Populated by GetConsoleMode.
135   - lpdword = ctypes.byref(dword)
136   - if not kernel32.GetConsoleScreenBufferInfo(handle, lpcsbi) or not kernel32.GetConsoleMode(handle, lpdword):
137   - raise ctypes.WinError()
138   -
139   - # Parse data.
140   - # buffer_width = int(csbi.dwSize.X - 1)
141   - # buffer_height = int(csbi.dwSize.Y)
142   - # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left)
143   - # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top)
144   - fg_color = csbi.wAttributes % 16
145   - bg_color = csbi.wAttributes & 240
146   - native_ansi = bool(dword.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
147   -
148   - return fg_color, bg_color, native_ansi
149   -
150   -
151   -def bg_color_native_ansi(kernel32, stderr, stdout):
152   - """Get background color and if console supports ANSI colors natively for both streams.
153   -
154   - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
155   - :param int stderr: stderr handle.
156   - :param int stdout: stdout handle.
157   -
158   - :return: Background color (int) and native ANSI support (bool).
159   - :rtype: tuple
160   - """
161   - try:
162   - if stderr == INVALID_HANDLE_VALUE:
163   - raise OSError
164   - bg_color, native_ansi = get_console_info(kernel32, stderr)[1:]
165   - except OSError:
166   - try:
167   - if stdout == INVALID_HANDLE_VALUE:
168   - raise OSError
169   - bg_color, native_ansi = get_console_info(kernel32, stdout)[1:]
170   - except OSError:
171   - bg_color, native_ansi = WINDOWS_CODES['black'], False
172   - return bg_color, native_ansi
173   -
174   -
175   -class WindowsStream(object):
176   - """Replacement stream which overrides sys.stdout or sys.stderr. When writing or printing, ANSI codes are converted.
177   -
178   - ANSI (Linux/Unix) color codes are converted into win32 system calls, changing the next character's color before
179   - printing it. Resources referenced:
180   - https://github.com/tartley/colorama
181   - http://www.cplusplus.com/articles/2ywTURfi/
182   - http://thomasfischer.biz/python-and-windows-terminal-colors/
183   - http://stackoverflow.com/questions/17125440/c-win32-console-color
184   - http://www.tysos.org/svn/trunk/mono/corlib/System/WindowsConsoleDriver.cs
185   - http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
186   - http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088#_win32_character_attributes
187   -
188   - :cvar list ALL_BG_CODES: List of bg Windows codes. Used to determine if requested color is foreground or background.
189   - :cvar dict COMPILED_CODES: Translation dict. Keys are ANSI codes (values of BASE_CODES), values are Windows codes.
190   - :ivar int default_fg: Foreground Windows color code at the time of instantiation.
191   - :ivar int default_bg: Background Windows color code at the time of instantiation.
192   - """
193   -
194   - ALL_BG_CODES = [v for k, v in WINDOWS_CODES.items() if k.startswith('bg') or k.startswith('hibg')]
195   - COMPILED_CODES = dict((v, WINDOWS_CODES[k]) for k, v in BASE_CODES.items() if k in WINDOWS_CODES)
196   -
197   - def __init__(self, kernel32, stream_handle, original_stream):
198   - """Constructor.
199   -
200   - :param ctypes.windll.kernel32 kernel32: Loaded kernel32 instance.
201   - :param int stream_handle: stderr or stdout handle.
202   - :param original_stream: sys.stderr or sys.stdout before being overridden by this class' instance.
203   - """
204   - self._kernel32 = kernel32
205   - self._stream_handle = stream_handle
206   - self._original_stream = original_stream
207   - self.default_fg, self.default_bg = self.colors
208   -
209   - def __getattr__(self, item):
210   - """If an attribute/function/etc is not defined in this function, retrieve the one from the original stream.
211   -
212   - Fixes ipython arrow key presses.
213   - """
214   - return getattr(self._original_stream, item)
215   -
216   - @property
217   - def colors(self):
218   - """Return the current foreground and background colors."""
219   - try:
220   - return get_console_info(self._kernel32, self._stream_handle)[:2]
221   - except OSError:
222   - return WINDOWS_CODES['white'], WINDOWS_CODES['black']
223   -
224   - @colors.setter
225   - def colors(self, color_code):
226   - """Change the foreground and background colors for subsequently printed characters.
227   -
228   - None resets colors to their original values (when class was instantiated).
229   -
230   - Since setting a color requires including both foreground and background codes (merged), setting just the
231   - foreground color resets the background color to black, and vice versa.
232   -
233   - This function first gets the current background and foreground colors, merges in the requested color code, and
234   - sets the result.
235   -
236   - However if we need to remove just the foreground color but leave the background color the same (or vice versa)
237   - such as when {/red} is used, we must merge the default foreground color with the current background color. This
238   - is the reason for those negative values.
239   -
240   - :param int color_code: Color code from WINDOWS_CODES.
241   - """
242   - if color_code is None:
243   - color_code = WINDOWS_CODES['/all']
244   -
245   - # Get current color code.
246   - current_fg, current_bg = self.colors
247   -
248   - # Handle special negative codes. Also determine the final color code.
249   - if color_code == WINDOWS_CODES['/fg']:
250   - final_color_code = self.default_fg | current_bg # Reset the foreground only.
251   - elif color_code == WINDOWS_CODES['/bg']:
252   - final_color_code = current_fg | self.default_bg # Reset the background only.
253   - elif color_code == WINDOWS_CODES['/all']:
254   - final_color_code = self.default_fg | self.default_bg # Reset both.
255   - elif color_code == WINDOWS_CODES['bgblack']:
256   - final_color_code = current_fg # Black background.
257   - else:
258   - new_is_bg = color_code in self.ALL_BG_CODES
259   - final_color_code = color_code | (current_fg if new_is_bg else current_bg)
260   -
261   - # Set new code.
262   - self._kernel32.SetConsoleTextAttribute(self._stream_handle, final_color_code)
263   -
264   - def write(self, p_str):
265   - """Write to stream.
266   -
267   - :param str p_str: string to print.
268   - """
269   - for segment in RE_SPLIT.split(p_str):
270   - if not segment:
271   - # Empty string. p_str probably starts with colors so the first item is always ''.
272   - continue
273   - if not RE_SPLIT.match(segment):
274   - # No color codes, print regular text.
275   - print(segment, file=self._original_stream, end='')
276   - self._original_stream.flush()
277   - continue
278   - for color_code in (int(c) for c in RE_NUMBER_SEARCH.findall(segment)[0].split(';')):
279   - if color_code in self.COMPILED_CODES:
280   - self.colors = self.COMPILED_CODES[color_code]
281   -
282   -
283   -class Windows(object):
284   - """Enable and disable Windows support for ANSI color character codes.
285   -
286   - Call static method Windows.enable() to enable color support for the remainder of the process' lifetime.
287   -
288   - This class is also a context manager. You can do this:
289   - with Windows():
290   - print(Color('{autored}Test{/autored}'))
291   -
292   - Or this:
293   - with Windows(auto_colors=True):
294   - print(Color('{autored}Test{/autored}'))
295   - """
296   -
297   - @classmethod
298   - def disable(cls):
299   - """Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.
300   -
301   - :return: If streams restored successfully.
302   - :rtype: bool
303   - """
304   - # Skip if not on Windows.
305   - if not IS_WINDOWS:
306   - return False
307   -
308   - # Restore default colors.
309   - if hasattr(sys.stderr, '_original_stream'):
310   - getattr(sys, 'stderr').color = None
311   - if hasattr(sys.stdout, '_original_stream'):
312   - getattr(sys, 'stdout').color = None
313   -
314   - # Restore original streams.
315   - changed = False
316   - if hasattr(sys.stderr, '_original_stream'):
317   - changed = True
318   - sys.stderr = getattr(sys.stderr, '_original_stream')
319   - if hasattr(sys.stdout, '_original_stream'):
320   - changed = True
321   - sys.stdout = getattr(sys.stdout, '_original_stream')
322   -
323   - return changed
324   -
325   - @staticmethod
326   - def is_enabled():
327   - """Return True if either stderr or stdout has colors enabled."""
328   - return hasattr(sys.stderr, '_original_stream') or hasattr(sys.stdout, '_original_stream')
329   -
330   - @classmethod
331   - def enable(cls, auto_colors=False, reset_atexit=False):
332   - """Enable color text with print() or sys.stdout.write() (stderr too).
333   -
334   - :param bool auto_colors: Automatically selects dark or light colors based on current terminal's background
335   - color. Only works with {autored} and related tags.
336   - :param bool reset_atexit: Resets original colors upon Python exit (in case you forget to reset it yourself with
337   - a closing tag). Does nothing on native ANSI consoles.
338   -
339   - :return: If streams replaced successfully.
340   - :rtype: bool
341   - """
342   - if not IS_WINDOWS:
343   - return False # Windows only.
344   -
345   - # Get values from init_kernel32().
346   - kernel32, stderr, stdout = init_kernel32()
347   - if stderr == INVALID_HANDLE_VALUE and stdout == INVALID_HANDLE_VALUE:
348   - return False # No valid handles, nothing to do.
349   -
350   - # Get console info.
351   - bg_color, native_ansi = bg_color_native_ansi(kernel32, stderr, stdout)
352   -
353   - # Set auto colors:
354   - if auto_colors:
355   - if bg_color in (112, 96, 240, 176, 224, 208, 160):
356   - ANSICodeMapping.set_light_background()
357   - else:
358   - ANSICodeMapping.set_dark_background()
359   -
360   - # Don't replace streams if ANSI codes are natively supported.
361   - if native_ansi:
362   - return False
363   -
364   - # Reset on exit if requested.
365   - if reset_atexit:
366   - atexit.register(cls.disable)
367   -
368   - # Overwrite stream references.
369   - if stderr != INVALID_HANDLE_VALUE:
370   - sys.stderr.flush()
371   - sys.stderr = WindowsStream(kernel32, stderr, sys.stderr)
372   - if stdout != INVALID_HANDLE_VALUE:
373   - sys.stdout.flush()
374   - sys.stdout = WindowsStream(kernel32, stdout, sys.stdout)
375   -
376   - return True
377   -
378   - def __init__(self, auto_colors=False):
379   - """Constructor."""
380   - self.auto_colors = auto_colors
381   -
382   - def __enter__(self):
383   - """Context manager, enables colors on Windows."""
384   - self.enable(auto_colors=self.auto_colors)
385   -
386   - def __exit__(self, *_):
387   - """Context manager, disabled colors on Windows."""
388   - self.disable()
oletools/thirdparty/easygui/LICENSE.txt deleted
1   -LICENSE INFORMATION
2   -
3   -EasyGui version 0.96
4   -
5   -Copyright (c) 2010, Stephen Raymond Ferg
6   -
7   -All rights reserved.
8   -
9   -Redistribution and use in source and binary forms, with or without modification,
10   -are permitted provided that the following conditions are met:
11   -
12   - 1. Redistributions of source code must retain the above copyright notice,
13   - this list of conditions and the following disclaimer.
14   -
15   - 2. Redistributions in binary form must reproduce the above copyright notice,
16   - this list of conditions and the following disclaimer in the documentation and/or
17   - other materials provided with the distribution.
18   -
19   - 3. The name of the author may not be used to endorse or promote products derived
20   - from this software without specific prior written permission.
21   -
22   -THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS"
23   -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24   -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25   -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26   -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27   -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28   -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29   -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30   -STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31   -IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
32   -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
oletools/thirdparty/easygui/easygui.py deleted
1   -"""
2   -@version: 0.96(2010-08-29)
3   -
4   -@note:
5   -ABOUT EASYGUI
6   -
7   -EasyGui provides an easy-to-use interface for simple GUI interaction
8   -with a user. It does not require the programmer to know anything about
9   -tkinter, frames, widgets, callbacks or lambda. All GUI interactions are
10   -invoked by simple function calls that return results.
11   -
12   -@note:
13   -WARNING about using EasyGui with IDLE
14   -
15   -You may encounter problems using IDLE to run programs that use EasyGui. Try it
16   -and find out. EasyGui is a collection of Tkinter routines that run their own
17   -event loops. IDLE is also a Tkinter application, with its own event loop. The
18   -two may conflict, with unpredictable results. If you find that you have
19   -problems, try running your EasyGui program outside of IDLE.
20   -
21   -Note that EasyGui requires Tk release 8.0 or greater.
22   -
23   -@note:
24   -LICENSE INFORMATION
25   -
26   -EasyGui version 0.96
27   -
28   -Copyright (c) 2010, Stephen Raymond Ferg
29   -
30   -All rights reserved.
31   -
32   -Redistribution and use in source and binary forms, with or without modification,
33   -are permitted provided that the following conditions are met:
34   -
35   - 1. Redistributions of source code must retain the above copyright notice,
36   - this list of conditions and the following disclaimer.
37   -
38   - 2. Redistributions in binary form must reproduce the above copyright notice,
39   - this list of conditions and the following disclaimer in the documentation and/or
40   - other materials provided with the distribution.
41   -
42   - 3. The name of the author may not be used to endorse or promote products derived
43   - from this software without specific prior written permission.
44   -
45   -THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS"
46   -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
47   -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48   -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
49   -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50   -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51   -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52   -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53   -STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
54   -IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
55   -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
56   -
57   -@note:
58   -ABOUT THE EASYGUI LICENSE
59   -
60   -This license is what is generally known as the "modified BSD license",
61   -aka "revised BSD", "new BSD", "3-clause BSD".
62   -See http://www.opensource.org/licenses/bsd-license.php
63   -
64   -This license is GPL-compatible.
65   -See http://en.wikipedia.org/wiki/License_compatibility
66   -See http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses
67   -
68   -The BSD License is less restrictive than GPL.
69   -It allows software released under the license to be incorporated into proprietary products.
70   -Works based on the software may be released under a proprietary license or as closed source software.
71   -http://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_.28.22New_BSD_License.22.29
72   -
73   -"""
74   -egversion = __doc__.split()[1]
75   -
76   -__all__ = ['ynbox'
77   - , 'ccbox'
78   - , 'boolbox'
79   - , 'indexbox'
80   - , 'msgbox'
81   - , 'buttonbox'
82   - , 'integerbox'
83   - , 'multenterbox'
84   - , 'enterbox'
85   - , 'exceptionbox'
86   - , 'choicebox'
87   - , 'codebox'
88   - , 'textbox'
89   - , 'diropenbox'
90   - , 'fileopenbox'
91   - , 'filesavebox'
92   - , 'passwordbox'
93   - , 'multpasswordbox'
94   - , 'multchoicebox'
95   - , 'abouteasygui'
96   - , 'egversion'
97   - , 'egdemo'
98   - , 'EgStore'
99   - ]
100   -
101   -import sys, os
102   -import string
103   -import pickle
104   -import traceback
105   -
106   -
107   -#--------------------------------------------------
108   -# check python version and take appropriate action
109   -#--------------------------------------------------
110   -"""
111   -From the python documentation:
112   -
113   -sys.hexversion contains the version number encoded as a single integer. This is
114   -guaranteed to increase with each version, including proper support for non-
115   -production releases. For example, to test that the Python interpreter is at
116   -least version 1.5.2, use:
117   -
118   -if sys.hexversion >= 0x010502F0:
119   - # use some advanced feature
120   - ...
121   -else:
122   - # use an alternative implementation or warn the user
123   - ...
124   -"""
125   -
126   -
127   -if sys.hexversion >= 0x020600F0:
128   - runningPython26 = True
129   -else:
130   - runningPython26 = False
131   -
132   -if sys.hexversion >= 0x030000F0:
133   - runningPython3 = True
134   -else:
135   - runningPython3 = False
136   -
137   -try:
138   - from PIL import Image as PILImage
139   - from PIL import ImageTk as PILImageTk
140   - PILisLoaded = True
141   -except:
142   - PILisLoaded = False
143   -
144   -
145   -if runningPython3:
146   - from tkinter import *
147   - import tkinter.filedialog as tk_FileDialog
148   - from io import StringIO
149   -else:
150   - from Tkinter import *
151   - import tkFileDialog as tk_FileDialog
152   - from StringIO import StringIO
153   -
154   -def write(*args):
155   - args = [str(arg) for arg in args]
156   - args = " ".join(args)
157   - sys.stdout.write(args)
158   -
159   -def writeln(*args):
160   - write(*args)
161   - sys.stdout.write("\n")
162   -
163   -say = writeln
164   -
165   -
166   -if TkVersion < 8.0 :
167   - stars = "*"*75
168   - writeln("""\n\n\n""" + stars + """
169   -You are running Tk version: """ + str(TkVersion) + """
170   -You must be using Tk version 8.0 or greater to use EasyGui.
171   -Terminating.
172   -""" + stars + """\n\n\n""")
173   - sys.exit(0)
174   -
175   -def dq(s):
176   - return '"%s"' % s
177   -
178   -rootWindowPosition = "+300+200"
179   -
180   -PROPORTIONAL_FONT_FAMILY = ("MS", "Sans", "Serif")
181   -MONOSPACE_FONT_FAMILY = ("Courier")
182   -
183   -PROPORTIONAL_FONT_SIZE = 10
184   -MONOSPACE_FONT_SIZE = 9 #a little smaller, because it it more legible at a smaller size
185   -TEXT_ENTRY_FONT_SIZE = 12 # a little larger makes it easier to see
186   -
187   -#STANDARD_SELECTION_EVENTS = ["Return", "Button-1"]
188   -STANDARD_SELECTION_EVENTS = ["Return", "Button-1", "space"]
189   -
190   -# Initialize some global variables that will be reset later
191   -__choiceboxMultipleSelect = None
192   -__widgetTexts = None
193   -__replyButtonText = None
194   -__choiceboxResults = None
195   -__firstWidget = None
196   -__enterboxText = None
197   -__enterboxDefaultText=""
198   -__multenterboxText = ""
199   -choiceboxChoices = None
200   -choiceboxWidget = None
201   -entryWidget = None
202   -boxRoot = None
203   -ImageErrorMsg = (
204   - "\n\n---------------------------------------------\n"
205   - "Error: %s\n%s")
206   -#-------------------------------------------------------------------
207   -# various boxes built on top of the basic buttonbox
208   -#-----------------------------------------------------------------------
209   -
210   -#-----------------------------------------------------------------------
211   -# ynbox
212   -#-----------------------------------------------------------------------
213   -def ynbox(msg="Shall I continue?"
214   - , title=" "
215   - , choices=("Yes", "No")
216   - , image=None
217   - ):
218   - """
219   - Display a msgbox with choices of Yes and No.
220   -
221   - The default is "Yes".
222   -
223   - The returned value is calculated this way::
224   - if the first choice ("Yes") is chosen, or if the dialog is cancelled:
225   - return 1
226   - else:
227   - return 0
228   -
229   - If invoked without a msg argument, displays a generic request for a confirmation
230   - that the user wishes to continue. So it can be used this way::
231   - if ynbox(): pass # continue
232   - else: sys.exit(0) # exit the program
233   -
234   - @arg msg: the msg to be displayed.
235   - @arg title: the window title
236   - @arg choices: a list or tuple of the choices to be displayed
237   - """
238   - return boolbox(msg, title, choices, image=image)
239   -
240   -
241   -#-----------------------------------------------------------------------
242   -# ccbox
243   -#-----------------------------------------------------------------------
244   -def ccbox(msg="Shall I continue?"
245   - , title=" "
246   - , choices=("Continue", "Cancel")
247   - , image=None
248   - ):
249   - """
250   - Display a msgbox with choices of Continue and Cancel.
251   -
252   - The default is "Continue".
253   -
254   - The returned value is calculated this way::
255   - if the first choice ("Continue") is chosen, or if the dialog is cancelled:
256   - return 1
257   - else:
258   - return 0
259   -
260   - If invoked without a msg argument, displays a generic request for a confirmation
261   - that the user wishes to continue. So it can be used this way::
262   -
263   - if ccbox():
264   - pass # continue
265   - else:
266   - sys.exit(0) # exit the program
267   -
268   - @arg msg: the msg to be displayed.
269   - @arg title: the window title
270   - @arg choices: a list or tuple of the choices to be displayed
271   - """
272   - return boolbox(msg, title, choices, image=image)
273   -
274   -
275   -#-----------------------------------------------------------------------
276   -# boolbox
277   -#-----------------------------------------------------------------------
278   -def boolbox(msg="Shall I continue?"
279   - , title=" "
280   - , choices=("Yes","No")
281   - , image=None
282   - ):
283   - """
284   - Display a boolean msgbox.
285   -
286   - The default is the first choice.
287   -
288   - The returned value is calculated this way::
289   - if the first choice is chosen, or if the dialog is cancelled:
290   - returns 1
291   - else:
292   - returns 0
293   - """
294   - reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
295   - if reply == choices[0]: return 1
296   - else: return 0
297   -
298   -
299   -#-----------------------------------------------------------------------
300   -# indexbox
301   -#-----------------------------------------------------------------------
302   -def indexbox(msg="Shall I continue?"
303   - , title=" "
304   - , choices=("Yes","No")
305   - , image=None
306   - ):
307   - """
308   - Display a buttonbox with the specified choices.
309   - Return the index of the choice selected.
310   - """
311   - reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
312   - index = -1
313   - for choice in choices:
314   - index = index + 1
315   - if reply == choice: return index
316   - raise AssertionError(
317   - "There is a program logic error in the EasyGui code for indexbox.")
318   -
319   -
320   -#-----------------------------------------------------------------------
321   -# msgbox
322   -#-----------------------------------------------------------------------
323   -def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None):
324   - """
325   - Display a messagebox
326   - """
327   - if type(ok_button) != type("OK"):
328   - raise AssertionError("The 'ok_button' argument to msgbox must be a string.")
329   -
330   - return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root)
331   -
332   -
333   -#-------------------------------------------------------------------
334   -# buttonbox
335   -#-------------------------------------------------------------------
336   -def buttonbox(msg="",title=" "
337   - ,choices=("Button1", "Button2", "Button3")
338   - , image=None
339   - , root=None
340   - ):
341   - """
342   - Display a msg, a title, and a set of buttons.
343   - The buttons are defined by the members of the choices list.
344   - Return the text of the button that the user selected.
345   -
346   - @arg msg: the msg to be displayed.
347   - @arg title: the window title
348   - @arg choices: a list or tuple of the choices to be displayed
349   - """
350   - global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame
351   -
352   -
353   - # Initialize __replyButtonText to the first choice.
354   - # This is what will be used if the window is closed by the close button.
355   - __replyButtonText = choices[0]
356   -
357   - if root:
358   - root.withdraw()
359   - boxRoot = Toplevel(master=root)
360   - boxRoot.withdraw()
361   - else:
362   - boxRoot = Tk()
363   - boxRoot.withdraw()
364   -
365   - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
366   - boxRoot.title(title)
367   - boxRoot.iconname('Dialog')
368   - boxRoot.geometry(rootWindowPosition)
369   - boxRoot.minsize(400, 100)
370   -
371   - # ------------- define the messageFrame ---------------------------------
372   - messageFrame = Frame(master=boxRoot)
373   - messageFrame.pack(side=TOP, fill=BOTH)
374   -
375   - # ------------- define the imageFrame ---------------------------------
376   - tk_Image = None
377   - if image:
378   - imageFilename = os.path.normpath(image)
379   - junk,ext = os.path.splitext(imageFilename)
380   -
381   - if os.path.exists(imageFilename):
382   - if ext.lower() in [".gif", ".pgm", ".ppm"]:
383   - tk_Image = PhotoImage(master=boxRoot, file=imageFilename)
384   - else:
385   - if PILisLoaded:
386   - try:
387   - pil_Image = PILImage.open(imageFilename)
388   - tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot)
389   - except:
390   - msg += ImageErrorMsg % (imageFilename,
391   - "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image."
392   - "\n\nPIL reports:\n" + exception_format())
393   -
394   - else: # PIL is not loaded
395   - msg += ImageErrorMsg % (imageFilename,
396   - "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n"
397   - "You may need to install PIL\n"
398   - "(http://www.pythonware.com/products/pil/)\n"
399   - "to display " + ext + " image files.")
400   -
401   - else:
402   - msg += ImageErrorMsg % (imageFilename, "\nImage file not found.")
403   -
404   - if tk_Image:
405   - imageFrame = Frame(master=boxRoot)
406   - imageFrame.pack(side=TOP, fill=BOTH)
407   - label = Label(imageFrame,image=tk_Image)
408   - label.image = tk_Image # keep a reference!
409   - label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
410   -
411   - # ------------- define the buttonsFrame ---------------------------------
412   - buttonsFrame = Frame(master=boxRoot)
413   - buttonsFrame.pack(side=TOP, fill=BOTH)
414   -
415   - # -------------------- place the widgets in the frames -----------------------
416   - messageWidget = Message(messageFrame, text=msg, width=400)
417   - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
418   - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
419   -
420   - __put_buttons_in_buttonframe(choices)
421   -
422   - # -------------- the action begins -----------
423   - # put the focus on the first button
424   - __firstWidget.focus_force()
425   -
426   - boxRoot.deiconify()
427   - boxRoot.mainloop()
428   - boxRoot.destroy()
429   - if root: root.deiconify()
430   - return __replyButtonText
431   -
432   -
433   -#-------------------------------------------------------------------
434   -# integerbox
435   -#-------------------------------------------------------------------
436   -def integerbox(msg=""
437   - , title=" "
438   - , default=""
439   - , lowerbound=0
440   - , upperbound=99
441   - , image = None
442   - , root = None
443   - , **invalidKeywordArguments
444   - ):
445   - """
446   - Show a box in which a user can enter an integer.
447   -
448   - In addition to arguments for msg and title, this function accepts
449   - integer arguments for "default", "lowerbound", and "upperbound".
450   -
451   - The default argument may be None.
452   -
453   - When the user enters some text, the text is checked to verify that it
454   - can be converted to an integer between the lowerbound and upperbound.
455   -
456   - If it can be, the integer (not the text) is returned.
457   -
458   - If it cannot, then an error msg is displayed, and the integerbox is
459   - redisplayed.
460   -
461   - If the user cancels the operation, None is returned.
462   -
463   - NOTE that the "argLowerBound" and "argUpperBound" arguments are no longer
464   - supported. They have been replaced by "upperbound" and "lowerbound".
465   - """
466   - if "argLowerBound" in invalidKeywordArguments:
467   - raise AssertionError(
468   - "\nintegerbox no longer supports the 'argLowerBound' argument.\n"
469   - + "Use 'lowerbound' instead.\n\n")
470   - if "argUpperBound" in invalidKeywordArguments:
471   - raise AssertionError(
472   - "\nintegerbox no longer supports the 'argUpperBound' argument.\n"
473   - + "Use 'upperbound' instead.\n\n")
474   -
475   - if default != "":
476   - if type(default) != type(1):
477   - raise AssertionError(
478   - "integerbox received a non-integer value for "
479   - + "default of " + dq(str(default)) , "Error")
480   -
481   - if type(lowerbound) != type(1):
482   - raise AssertionError(
483   - "integerbox received a non-integer value for "
484   - + "lowerbound of " + dq(str(lowerbound)) , "Error")
485   -
486   - if type(upperbound) != type(1):
487   - raise AssertionError(
488   - "integerbox received a non-integer value for "
489   - + "upperbound of " + dq(str(upperbound)) , "Error")
490   -
491   - if msg == "":
492   - msg = ("Enter an integer between " + str(lowerbound)
493   - + " and "
494   - + str(upperbound)
495   - )
496   -
497   - while 1:
498   - reply = enterbox(msg, title, str(default), image=image, root=root)
499   - if reply == None: return None
500   -
501   - try:
502   - reply = int(reply)
503   - except:
504   - msgbox ("The value that you entered:\n\t%s\nis not an integer." % dq(str(reply))
505   - , "Error")
506   - continue
507   -
508   - if reply < lowerbound:
509   - msgbox ("The value that you entered is less than the lower bound of "
510   - + str(lowerbound) + ".", "Error")
511   - continue
512   -
513   - if reply > upperbound:
514   - msgbox ("The value that you entered is greater than the upper bound of "
515   - + str(upperbound) + ".", "Error")
516   - continue
517   -
518   - # reply has passed all validation checks.
519   - # It is an integer between the specified bounds.
520   - return reply
521   -
522   -#-------------------------------------------------------------------
523   -# multenterbox
524   -#-------------------------------------------------------------------
525   -def multenterbox(msg="Fill in values for the fields."
526   - , title=" "
527   - , fields=()
528   - , values=()
529   - ):
530   - r"""
531   - Show screen with multiple data entry fields.
532   -
533   - If there are fewer values than names, the list of values is padded with
534   - empty strings until the number of values is the same as the number of names.
535   -
536   - If there are more values than names, the list of values
537   - is truncated so that there are as many values as names.
538   -
539   - Returns a list of the values of the fields,
540   - or None if the user cancels the operation.
541   -
542   - Here is some example code, that shows how values returned from
543   - multenterbox can be checked for validity before they are accepted::
544   - ----------------------------------------------------------------------
545   - msg = "Enter your personal information"
546   - title = "Credit Card Application"
547   - fieldNames = ["Name","Street Address","City","State","ZipCode"]
548   - fieldValues = [] # we start with blanks for the values
549   - fieldValues = multenterbox(msg,title, fieldNames)
550   -
551   - # make sure that none of the fields was left blank
552   - while 1:
553   - if fieldValues == None: break
554   - errmsg = ""
555   - for i in range(len(fieldNames)):
556   - if fieldValues[i].strip() == "":
557   - errmsg += ('"%s" is a required field.\n\n' % fieldNames[i])
558   - if errmsg == "":
559   - break # no problems found
560   - fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
561   -
562   - writeln("Reply was: %s" % str(fieldValues))
563   - ----------------------------------------------------------------------
564   -
565   - @arg msg: the msg to be displayed.
566   - @arg title: the window title
567   - @arg fields: a list of fieldnames.
568   - @arg values: a list of field values
569   - """
570   - return __multfillablebox(msg,title,fields,values,None)
571   -
572   -
573   -#-----------------------------------------------------------------------
574   -# multpasswordbox
575   -#-----------------------------------------------------------------------
576   -def multpasswordbox(msg="Fill in values for the fields."
577   - , title=" "
578   - , fields=tuple()
579   - ,values=tuple()
580   - ):
581   - r"""
582   - Same interface as multenterbox. But in multpassword box,
583   - the last of the fields is assumed to be a password, and
584   - is masked with asterisks.
585   -
586   - Example
587   - =======
588   -
589   - Here is some example code, that shows how values returned from
590   - multpasswordbox can be checked for validity before they are accepted::
591   - msg = "Enter logon information"
592   - title = "Demo of multpasswordbox"
593   - fieldNames = ["Server ID", "User ID", "Password"]
594   - fieldValues = [] # we start with blanks for the values
595   - fieldValues = multpasswordbox(msg,title, fieldNames)
596   -
597   - # make sure that none of the fields was left blank
598   - while 1:
599   - if fieldValues == None: break
600   - errmsg = ""
601   - for i in range(len(fieldNames)):
602   - if fieldValues[i].strip() == "":
603   - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
604   - if errmsg == "": break # no problems found
605   - fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
606   -
607   - writeln("Reply was: %s" % str(fieldValues))
608   - """
609   - return __multfillablebox(msg,title,fields,values,"*")
610   -
611   -def bindArrows(widget):
612   - widget.bind("<Down>", tabRight)
613   - widget.bind("<Up>" , tabLeft)
614   -
615   - widget.bind("<Right>",tabRight)
616   - widget.bind("<Left>" , tabLeft)
617   -
618   -def tabRight(event):
619   - boxRoot.event_generate("<Tab>")
620   -
621   -def tabLeft(event):
622   - boxRoot.event_generate("<Shift-Tab>")
623   -
624   -#-----------------------------------------------------------------------
625   -# __multfillablebox
626   -#-----------------------------------------------------------------------
627   -def __multfillablebox(msg="Fill in values for the fields."
628   - , title=" "
629   - , fields=()
630   - , values=()
631   - , mask = None
632   - ):
633   - global boxRoot, __multenterboxText, __multenterboxDefaultText, cancelButton, entryWidget, okButton
634   -
635   - choices = ["OK", "Cancel"]
636   - if len(fields) == 0: return None
637   -
638   - fields = list(fields[:]) # convert possible tuples to a list
639   - values = list(values[:]) # convert possible tuples to a list
640   -
641   - if len(values) == len(fields): pass
642   - elif len(values) > len(fields):
643   - fields = fields[0:len(values)]
644   - else:
645   - while len(values) < len(fields):
646   - values.append("")
647   -
648   - boxRoot = Tk()
649   -
650   - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
651   - boxRoot.title(title)
652   - boxRoot.iconname('Dialog')
653   - boxRoot.geometry(rootWindowPosition)
654   - boxRoot.bind("<Escape>", __multenterboxCancel)
655   -
656   - # -------------------- put subframes in the boxRoot --------------------
657   - messageFrame = Frame(master=boxRoot)
658   - messageFrame.pack(side=TOP, fill=BOTH)
659   -
660   - #-------------------- the msg widget ----------------------------
661   - messageWidget = Message(messageFrame, width="4.5i", text=msg)
662   - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
663   - messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
664   -
665   - global entryWidgets
666   - entryWidgets = []
667   -
668   - lastWidgetIndex = len(fields) - 1
669   -
670   - for widgetIndex in range(len(fields)):
671   - argFieldName = fields[widgetIndex]
672   - argFieldValue = values[widgetIndex]
673   - entryFrame = Frame(master=boxRoot)
674   - entryFrame.pack(side=TOP, fill=BOTH)
675   -
676   - # --------- entryWidget ----------------------------------------------
677   - labelWidget = Label(entryFrame, text=argFieldName)
678   - labelWidget.pack(side=LEFT)
679   -
680   - entryWidget = Entry(entryFrame, width=40,highlightthickness=2)
681   - entryWidgets.append(entryWidget)
682   - entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE))
683   - entryWidget.pack(side=RIGHT, padx="3m")
684   -
685   - bindArrows(entryWidget)
686   -
687   - entryWidget.bind("<Return>", __multenterboxGetText)
688   - entryWidget.bind("<Escape>", __multenterboxCancel)
689   -
690   - # for the last entryWidget, if this is a multpasswordbox,
691   - # show the contents as just asterisks
692   - if widgetIndex == lastWidgetIndex:
693   - if mask:
694   - entryWidgets[widgetIndex].configure(show=mask)
695   -
696   - # put text into the entryWidget
697   - entryWidgets[widgetIndex].insert(0,argFieldValue)
698   - widgetIndex += 1
699   -
700   - # ------------------ ok button -------------------------------
701   - buttonsFrame = Frame(master=boxRoot)
702   - buttonsFrame.pack(side=BOTTOM, fill=BOTH)
703   -
704   - okButton = Button(buttonsFrame, takefocus=1, text="OK")
705   - bindArrows(okButton)
706   - okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
707   -
708   - # for the commandButton, bind activation events to the activation event handler
709   - commandButton = okButton
710   - handler = __multenterboxGetText
711   - for selectionEvent in STANDARD_SELECTION_EVENTS:
712   - commandButton.bind("<%s>" % selectionEvent, handler)
713   -
714   -
715   - # ------------------ cancel button -------------------------------
716   - cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel")
717   - bindArrows(cancelButton)
718   - cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
719   -
720   - # for the commandButton, bind activation events to the activation event handler
721   - commandButton = cancelButton
722   - handler = __multenterboxCancel
723   - for selectionEvent in STANDARD_SELECTION_EVENTS:
724   - commandButton.bind("<%s>" % selectionEvent, handler)
725   -
726   -
727   - # ------------------- time for action! -----------------
728   - entryWidgets[0].focus_force() # put the focus on the entryWidget
729   - boxRoot.mainloop() # run it!
730   -
731   - # -------- after the run has completed ----------------------------------
732   - boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now
733   - return __multenterboxText
734   -
735   -
736   -#-----------------------------------------------------------------------
737   -# __multenterboxGetText
738   -#-----------------------------------------------------------------------
739   -def __multenterboxGetText(event):
740   - global __multenterboxText
741   -
742   - __multenterboxText = []
743   - for entryWidget in entryWidgets:
744   - __multenterboxText.append(entryWidget.get())
745   - boxRoot.quit()
746   -
747   -
748   -def __multenterboxCancel(event):
749   - global __multenterboxText
750   - __multenterboxText = None
751   - boxRoot.quit()
752   -
753   -
754   -#-------------------------------------------------------------------
755   -# enterbox
756   -#-------------------------------------------------------------------
757   -def enterbox(msg="Enter something."
758   - , title=" "
759   - , default=""
760   - , strip=True
761   - , image=None
762   - , root=None
763   - ):
764   - """
765   - Show a box in which a user can enter some text.
766   -
767   - You may optionally specify some default text, which will appear in the
768   - enterbox when it is displayed.
769   -
770   - Returns the text that the user entered, or None if he cancels the operation.
771   -
772   - By default, enterbox strips its result (i.e. removes leading and trailing
773   - whitespace). (If you want it not to strip, use keyword argument: strip=False.)
774   - This makes it easier to test the results of the call::
775   -
776   - reply = enterbox(....)
777   - if reply:
778   - ...
779   - else:
780   - ...
781   - """
782   - result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root)
783   - if result and strip:
784   - result = result.strip()
785   - return result
786   -
787   -
788   -def passwordbox(msg="Enter your password."
789   - , title=" "
790   - , default=""
791   - , image=None
792   - , root=None
793   - ):
794   - """
795   - Show a box in which a user can enter a password.
796   - The text is masked with asterisks, so the password is not displayed.
797   - Returns the text that the user entered, or None if he cancels the operation.
798   - """
799   - return __fillablebox(msg, title, default, mask="*",image=image,root=root)
800   -
801   -
802   -def __fillablebox(msg
803   - , title=""
804   - , default=""
805   - , mask=None
806   - , image=None
807   - , root=None
808   - ):
809   - """
810   - Show a box in which a user can enter some text.
811   - You may optionally specify some default text, which will appear in the
812   - enterbox when it is displayed.
813   - Returns the text that the user entered, or None if he cancels the operation.
814   - """
815   -
816   - global boxRoot, __enterboxText, __enterboxDefaultText
817   - global cancelButton, entryWidget, okButton
818   -
819   - if title == None: title == ""
820   - if default == None: default = ""
821   - __enterboxDefaultText = default
822   - __enterboxText = __enterboxDefaultText
823   -
824   - if root:
825   - root.withdraw()
826   - boxRoot = Toplevel(master=root)
827   - boxRoot.withdraw()
828   - else:
829   - boxRoot = Tk()
830   - boxRoot.withdraw()
831   -
832   - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
833   - boxRoot.title(title)
834   - boxRoot.iconname('Dialog')
835   - boxRoot.geometry(rootWindowPosition)
836   - boxRoot.bind("<Escape>", __enterboxCancel)
837   -
838   - # ------------- define the messageFrame ---------------------------------
839   - messageFrame = Frame(master=boxRoot)
840   - messageFrame.pack(side=TOP, fill=BOTH)
841   -
842   - # ------------- define the imageFrame ---------------------------------
843   - tk_Image = None
844   - if image:
845   - imageFilename = os.path.normpath(image)
846   - junk,ext = os.path.splitext(imageFilename)
847   -
848   - if os.path.exists(imageFilename):
849   - if ext.lower() in [".gif", ".pgm", ".ppm"]:
850   - tk_Image = PhotoImage(master=boxRoot, file=imageFilename)
851   - else:
852   - if PILisLoaded:
853   - try:
854   - pil_Image = PILImage.open(imageFilename)
855   - tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot)
856   - except:
857   - msg += ImageErrorMsg % (imageFilename,
858   - "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image."
859   - "\n\nPIL reports:\n" + exception_format())
860   -
861   - else: # PIL is not loaded
862   - msg += ImageErrorMsg % (imageFilename,
863   - "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n"
864   - "You may need to install PIL\n"
865   - "(http://www.pythonware.com/products/pil/)\n"
866   - "to display " + ext + " image files.")
867   -
868   - else:
869   - msg += ImageErrorMsg % (imageFilename, "\nImage file not found.")
870   -
871   - if tk_Image:
872   - imageFrame = Frame(master=boxRoot)
873   - imageFrame.pack(side=TOP, fill=BOTH)
874   - label = Label(imageFrame,image=tk_Image)
875   - label.image = tk_Image # keep a reference!
876   - label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
877   -
878   - # ------------- define the buttonsFrame ---------------------------------
879   - buttonsFrame = Frame(master=boxRoot)
880   - buttonsFrame.pack(side=TOP, fill=BOTH)
881   -
882   -
883   - # ------------- define the entryFrame ---------------------------------
884   - entryFrame = Frame(master=boxRoot)
885   - entryFrame.pack(side=TOP, fill=BOTH)
886   -
887   - # ------------- define the buttonsFrame ---------------------------------
888   - buttonsFrame = Frame(master=boxRoot)
889   - buttonsFrame.pack(side=TOP, fill=BOTH)
890   -
891   - #-------------------- the msg widget ----------------------------
892   - messageWidget = Message(messageFrame, width="4.5i", text=msg)
893   - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
894   - messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
895   -
896   - # --------- entryWidget ----------------------------------------------
897   - entryWidget = Entry(entryFrame, width=40)
898   - bindArrows(entryWidget)
899   - entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE))
900   - if mask:
901   - entryWidget.configure(show=mask)
902   - entryWidget.pack(side=LEFT, padx="3m")
903   - entryWidget.bind("<Return>", __enterboxGetText)
904   - entryWidget.bind("<Escape>", __enterboxCancel)
905   - # put text into the entryWidget
906   - entryWidget.insert(0,__enterboxDefaultText)
907   -
908   - # ------------------ ok button -------------------------------
909   - okButton = Button(buttonsFrame, takefocus=1, text="OK")
910   - bindArrows(okButton)
911   - okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
912   -
913   - # for the commandButton, bind activation events to the activation event handler
914   - commandButton = okButton
915   - handler = __enterboxGetText
916   - for selectionEvent in STANDARD_SELECTION_EVENTS:
917   - commandButton.bind("<%s>" % selectionEvent, handler)
918   -
919   -
920   - # ------------------ cancel button -------------------------------
921   - cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel")
922   - bindArrows(cancelButton)
923   - cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m')
924   -
925   - # for the commandButton, bind activation events to the activation event handler
926   - commandButton = cancelButton
927   - handler = __enterboxCancel
928   - for selectionEvent in STANDARD_SELECTION_EVENTS:
929   - commandButton.bind("<%s>" % selectionEvent, handler)
930   -
931   - # ------------------- time for action! -----------------
932   - entryWidget.focus_force() # put the focus on the entryWidget
933   - boxRoot.deiconify()
934   - boxRoot.mainloop() # run it!
935   -
936   - # -------- after the run has completed ----------------------------------
937   - if root: root.deiconify()
938   - boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now
939   - return __enterboxText
940   -
941   -
942   -def __enterboxGetText(event):
943   - global __enterboxText
944   -
945   - __enterboxText = entryWidget.get()
946   - boxRoot.quit()
947   -
948   -
949   -def __enterboxRestore(event):
950   - global entryWidget
951   -
952   - entryWidget.delete(0,len(entryWidget.get()))
953   - entryWidget.insert(0, __enterboxDefaultText)
954   -
955   -
956   -def __enterboxCancel(event):
957   - global __enterboxText
958   -
959   - __enterboxText = None
960   - boxRoot.quit()
961   -
962   -def denyWindowManagerClose():
963   - """ don't allow WindowManager close
964   - """
965   - x = Tk()
966   - x.withdraw()
967   - x.bell()
968   - x.destroy()
969   -
970   -
971   -
972   -#-------------------------------------------------------------------
973   -# multchoicebox
974   -#-------------------------------------------------------------------
975   -def multchoicebox(msg="Pick as many items as you like."
976   - , title=" "
977   - , choices=()
978   - , **kwargs
979   - ):
980   - """
981   - Present the user with a list of choices.
982   - allow him to select multiple items and return them in a list.
983   - if the user doesn't choose anything from the list, return the empty list.
984   - return None if he cancelled selection.
985   -
986   - @arg msg: the msg to be displayed.
987   - @arg title: the window title
988   - @arg choices: a list or tuple of the choices to be displayed
989   - """
990   - if len(choices) == 0: choices = ["Program logic error - no choices were specified."]
991   -
992   - global __choiceboxMultipleSelect
993   - __choiceboxMultipleSelect = 1
994   - return __choicebox(msg, title, choices)
995   -
996   -
997   -#-----------------------------------------------------------------------
998   -# choicebox
999   -#-----------------------------------------------------------------------
1000   -def choicebox(msg="Pick something."
1001   - , title=" "
1002   - , choices=()
1003   - ):
1004   - """
1005   - Present the user with a list of choices.
1006   - return the choice that he selects.
1007   - return None if he cancels the selection selection.
1008   -
1009   - @arg msg: the msg to be displayed.
1010   - @arg title: the window title
1011   - @arg choices: a list or tuple of the choices to be displayed
1012   - """
1013   - if len(choices) == 0: choices = ["Program logic error - no choices were specified."]
1014   -
1015   - global __choiceboxMultipleSelect
1016   - __choiceboxMultipleSelect = 0
1017   - return __choicebox(msg,title,choices)
1018   -
1019   -
1020   -#-----------------------------------------------------------------------
1021   -# __choicebox
1022   -#-----------------------------------------------------------------------
1023   -def __choicebox(msg
1024   - , title
1025   - , choices
1026   - ):
1027   - """
1028   - internal routine to support choicebox() and multchoicebox()
1029   - """
1030   - global boxRoot, __choiceboxResults, choiceboxWidget, defaultText
1031   - global choiceboxWidget, choiceboxChoices
1032   - #-------------------------------------------------------------------
1033   - # If choices is a tuple, we make it a list so we can sort it.
1034   - # If choices is already a list, we make a new list, so that when
1035   - # we sort the choices, we don't affect the list object that we
1036   - # were given.
1037   - #-------------------------------------------------------------------
1038   - choices = list(choices[:])
1039   - if len(choices) == 0:
1040   - choices = ["Program logic error - no choices were specified."]
1041   - defaultButtons = ["OK", "Cancel"]
1042   -
1043   - # make sure all choices are strings
1044   - for index in range(len(choices)):
1045   - choices[index] = str(choices[index])
1046   -
1047   - lines_to_show = min(len(choices), 20)
1048   - lines_to_show = 20
1049   -
1050   - if title == None: title = ""
1051   -
1052   - # Initialize __choiceboxResults
1053   - # This is the value that will be returned if the user clicks the close icon
1054   - __choiceboxResults = None
1055   -
1056   - boxRoot = Tk()
1057   - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
1058   - screen_width = boxRoot.winfo_screenwidth()
1059   - screen_height = boxRoot.winfo_screenheight()
1060   - root_width = int((screen_width * 0.8))
1061   - root_height = int((screen_height * 0.5))
1062   - root_xpos = int((screen_width * 0.1))
1063   - root_ypos = int((screen_height * 0.05))
1064   -
1065   - boxRoot.title(title)
1066   - boxRoot.iconname('Dialog')
1067   - rootWindowPosition = "+0+0"
1068   - boxRoot.geometry(rootWindowPosition)
1069   - boxRoot.expand=NO
1070   - boxRoot.minsize(root_width, root_height)
1071   - rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos)
1072   - boxRoot.geometry(rootWindowPosition)
1073   -
1074   - # ---------------- put the frames in the window -----------------------------------------
1075   - message_and_buttonsFrame = Frame(master=boxRoot)
1076   - message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO)
1077   -
1078   - messageFrame = Frame(message_and_buttonsFrame)
1079   - messageFrame.pack(side=LEFT, fill=X, expand=YES)
1080   - #messageFrame.pack(side=TOP, fill=X, expand=YES)
1081   -
1082   - buttonsFrame = Frame(message_and_buttonsFrame)
1083   - buttonsFrame.pack(side=RIGHT, expand=NO, pady=0)
1084   - #buttonsFrame.pack(side=TOP, expand=YES, pady=0)
1085   -
1086   - choiceboxFrame = Frame(master=boxRoot)
1087   - choiceboxFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
1088   -
1089   - # -------------------------- put the widgets in the frames ------------------------------
1090   -
1091   - # ---------- put a msg widget in the msg frame-------------------
1092   - messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9))
1093   - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
1094   - messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m')
1095   -
1096   - # -------- put the choiceboxWidget in the choiceboxFrame ---------------------------
1097   - choiceboxWidget = Listbox(choiceboxFrame
1098   - , height=lines_to_show
1099   - , borderwidth="1m"
1100   - , relief="flat"
1101   - , bg="white"
1102   - )
1103   -
1104   - if __choiceboxMultipleSelect:
1105   - choiceboxWidget.configure(selectmode=MULTIPLE)
1106   -
1107   - choiceboxWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
1108   -
1109   - # add a vertical scrollbar to the frame
1110   - rightScrollbar = Scrollbar(choiceboxFrame, orient=VERTICAL, command=choiceboxWidget.yview)
1111   - choiceboxWidget.configure(yscrollcommand = rightScrollbar.set)
1112   -
1113   - # add a horizontal scrollbar to the frame
1114   - bottomScrollbar = Scrollbar(choiceboxFrame, orient=HORIZONTAL, command=choiceboxWidget.xview)
1115   - choiceboxWidget.configure(xscrollcommand = bottomScrollbar.set)
1116   -
1117   - # pack the Listbox and the scrollbars. Note that although we must define
1118   - # the textArea first, we must pack it last, so that the bottomScrollbar will
1119   - # be located properly.
1120   -
1121   - bottomScrollbar.pack(side=BOTTOM, fill = X)
1122   - rightScrollbar.pack(side=RIGHT, fill = Y)
1123   -
1124   - choiceboxWidget.pack(side=LEFT, padx="1m", pady="1m", expand=YES, fill=BOTH)
1125   -
1126   - #---------------------------------------------------
1127   - # sort the choices
1128   - # eliminate duplicates
1129   - # put the choices into the choiceboxWidget
1130   - #---------------------------------------------------
1131   - for index in range(len(choices)):
1132   - choices[index] = str(choices[index])
1133   -
1134   - if runningPython3:
1135   - choices.sort(key=str.lower)
1136   - else:
1137   - choices.sort( lambda x,y: cmp(x.lower(), y.lower())) # case-insensitive sort
1138   -
1139   - lastInserted = None
1140   - choiceboxChoices = []
1141   - for choice in choices:
1142   - if choice == lastInserted: pass
1143   - else:
1144   - choiceboxWidget.insert(END, choice)
1145   - choiceboxChoices.append(choice)
1146   - lastInserted = choice
1147   -
1148   - boxRoot.bind('<Any-Key>', KeyboardListener)
1149   -
1150   - # put the buttons in the buttonsFrame
1151   - if len(choices) > 0:
1152   - okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6)
1153   - bindArrows(okButton)
1154   - okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m")
1155   -
1156   - # for the commandButton, bind activation events to the activation event handler
1157   - commandButton = okButton
1158   - handler = __choiceboxGetChoice
1159   - for selectionEvent in STANDARD_SELECTION_EVENTS:
1160   - commandButton.bind("<%s>" % selectionEvent, handler)
1161   -
1162   - # now bind the keyboard events
1163   - choiceboxWidget.bind("<Return>", __choiceboxGetChoice)
1164   - choiceboxWidget.bind("<Double-Button-1>", __choiceboxGetChoice)
1165   - else:
1166   - # now bind the keyboard events
1167   - choiceboxWidget.bind("<Return>", __choiceboxCancel)
1168   - choiceboxWidget.bind("<Double-Button-1>", __choiceboxCancel)
1169   -
1170   - cancelButton = Button(buttonsFrame, takefocus=YES, text="Cancel", height=1, width=6)
1171   - bindArrows(cancelButton)
1172   - cancelButton.pack(expand=NO, side=BOTTOM, padx='2m', pady='1m', ipady="1m", ipadx="2m")
1173   -
1174   - # for the commandButton, bind activation events to the activation event handler
1175   - commandButton = cancelButton
1176   - handler = __choiceboxCancel
1177   - for selectionEvent in STANDARD_SELECTION_EVENTS:
1178   - commandButton.bind("<%s>" % selectionEvent, handler)
1179   -
1180   -
1181   - # add special buttons for multiple select features
1182   - if len(choices) > 0 and __choiceboxMultipleSelect:
1183   - selectionButtonsFrame = Frame(messageFrame)
1184   - selectionButtonsFrame.pack(side=RIGHT, fill=Y, expand=NO)
1185   -
1186   - selectAllButton = Button(selectionButtonsFrame, text="Select All", height=1, width=6)
1187   - bindArrows(selectAllButton)
1188   -
1189   - selectAllButton.bind("<Button-1>",__choiceboxSelectAll)
1190   - selectAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m")
1191   -
1192   - clearAllButton = Button(selectionButtonsFrame, text="Clear All", height=1, width=6)
1193   - bindArrows(clearAllButton)
1194   - clearAllButton.bind("<Button-1>",__choiceboxClearAll)
1195   - clearAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m")
1196   -
1197   -
1198   - # -------------------- bind some keyboard events ----------------------------
1199   - boxRoot.bind("<Escape>", __choiceboxCancel)
1200   -
1201   - # --------------------- the action begins -----------------------------------
1202   - # put the focus on the choiceboxWidget, and the select highlight on the first item
1203   - choiceboxWidget.select_set(0)
1204   - choiceboxWidget.focus_force()
1205   -
1206   - # --- run it! -----
1207   - boxRoot.mainloop()
1208   -
1209   - boxRoot.destroy()
1210   - return __choiceboxResults
1211   -
1212   -
1213   -def __choiceboxGetChoice(event):
1214   - global boxRoot, __choiceboxResults, choiceboxWidget
1215   -
1216   - if __choiceboxMultipleSelect:
1217   - __choiceboxResults = [choiceboxWidget.get(index) for index in choiceboxWidget.curselection()]
1218   -
1219   - else:
1220   - choice_index = choiceboxWidget.curselection()
1221   - __choiceboxResults = choiceboxWidget.get(choice_index)
1222   -
1223   - # writeln("Debugging> mouse-event=", event, " event.type=", event.type)
1224   - # writeln("Debugging> choice=", choice_index, __choiceboxResults)
1225   - boxRoot.quit()
1226   -
1227   -
1228   -def __choiceboxSelectAll(event):
1229   - global choiceboxWidget, choiceboxChoices
1230   -
1231   - choiceboxWidget.selection_set(0, len(choiceboxChoices)-1)
1232   -
1233   -def __choiceboxClearAll(event):
1234   - global choiceboxWidget, choiceboxChoices
1235   -
1236   - choiceboxWidget.selection_clear(0, len(choiceboxChoices)-1)
1237   -
1238   -
1239   -
1240   -def __choiceboxCancel(event):
1241   - global boxRoot, __choiceboxResults
1242   -
1243   - __choiceboxResults = None
1244   - boxRoot.quit()
1245   -
1246   -
1247   -def KeyboardListener(event):
1248   - global choiceboxChoices, choiceboxWidget
1249   - key = event.keysym
1250   - if len(key) <= 1:
1251   - if key in string.printable:
1252   - # Find the key in the list.
1253   - # before we clear the list, remember the selected member
1254   - try:
1255   - start_n = int(choiceboxWidget.curselection()[0])
1256   - except IndexError:
1257   - start_n = -1
1258   -
1259   - ## clear the selection.
1260   - choiceboxWidget.selection_clear(0, 'end')
1261   -
1262   - ## start from previous selection +1
1263   - for n in range(start_n+1, len(choiceboxChoices)):
1264   - item = choiceboxChoices[n]
1265   - if item[0].lower() == key.lower():
1266   - choiceboxWidget.selection_set(first=n)
1267   - choiceboxWidget.see(n)
1268   - return
1269   - else:
1270   - # has not found it so loop from top
1271   - for n in range(len(choiceboxChoices)):
1272   - item = choiceboxChoices[n]
1273   - if item[0].lower() == key.lower():
1274   - choiceboxWidget.selection_set(first = n)
1275   - choiceboxWidget.see(n)
1276   - return
1277   -
1278   - # nothing matched -- we'll look for the next logical choice
1279   - for n in range(len(choiceboxChoices)):
1280   - item = choiceboxChoices[n]
1281   - if item[0].lower() > key.lower():
1282   - if n > 0:
1283   - choiceboxWidget.selection_set(first = (n-1))
1284   - else:
1285   - choiceboxWidget.selection_set(first = 0)
1286   - choiceboxWidget.see(n)
1287   - return
1288   -
1289   - # still no match (nothing was greater than the key)
1290   - # we set the selection to the first item in the list
1291   - lastIndex = len(choiceboxChoices)-1
1292   - choiceboxWidget.selection_set(first = lastIndex)
1293   - choiceboxWidget.see(lastIndex)
1294   - return
1295   -
1296   -#-----------------------------------------------------------------------
1297   -# exception_format
1298   -#-----------------------------------------------------------------------
1299   -def exception_format():
1300   - """
1301   - Convert exception info into a string suitable for display.
1302   - """
1303   - return "".join(traceback.format_exception(
1304   - sys.exc_info()[0]
1305   - , sys.exc_info()[1]
1306   - , sys.exc_info()[2]
1307   - ))
1308   -
1309   -#-----------------------------------------------------------------------
1310   -# exceptionbox
1311   -#-----------------------------------------------------------------------
1312   -def exceptionbox(msg=None, title=None):
1313   - """
1314   - Display a box that gives information about
1315   - an exception that has just been raised.
1316   -
1317   - The caller may optionally pass in a title for the window, or a
1318   - msg to accompany the error information.
1319   -
1320   - Note that you do not need to (and cannot) pass an exception object
1321   - as an argument. The latest exception will automatically be used.
1322   - """
1323   - if title == None: title = "Error Report"
1324   - if msg == None:
1325   - msg = "An error (exception) has occurred in the program."
1326   -
1327   - codebox(msg, title, exception_format())
1328   -
1329   -#-------------------------------------------------------------------
1330   -# codebox
1331   -#-------------------------------------------------------------------
1332   -
1333   -def codebox(msg=""
1334   - , title=" "
1335   - , text=""
1336   - ):
1337   - """
1338   - Display some text in a monospaced font, with no line wrapping.
1339   - This function is suitable for displaying code and text that is
1340   - formatted using spaces.
1341   -
1342   - The text parameter should be a string, or a list or tuple of lines to be
1343   - displayed in the textbox.
1344   - """
1345   - return textbox(msg, title, text, codebox=1 )
1346   -
1347   -#-------------------------------------------------------------------
1348   -# textbox
1349   -#-------------------------------------------------------------------
1350   -def textbox(msg=""
1351   - , title=" "
1352   - , text=""
1353   - , codebox=0
1354   - ):
1355   - """
1356   - Display some text in a proportional font with line wrapping at word breaks.
1357   - This function is suitable for displaying general written text.
1358   -
1359   - The text parameter should be a string, or a list or tuple of lines to be
1360   - displayed in the textbox.
1361   - """
1362   -
1363   - if msg == None: msg = ""
1364   - if title == None: title = ""
1365   -
1366   - global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame
1367   - global rootWindowPosition
1368   - choices = ["OK"]
1369   - __replyButtonText = choices[0]
1370   -
1371   -
1372   - boxRoot = Tk()
1373   -
1374   - boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
1375   -
1376   - screen_width = boxRoot.winfo_screenwidth()
1377   - screen_height = boxRoot.winfo_screenheight()
1378   - root_width = int((screen_width * 0.8))
1379   - root_height = int((screen_height * 0.5))
1380   - root_xpos = int((screen_width * 0.1))
1381   - root_ypos = int((screen_height * 0.05))
1382   -
1383   - boxRoot.title(title)
1384   - boxRoot.iconname('Dialog')
1385   - rootWindowPosition = "+0+0"
1386   - boxRoot.geometry(rootWindowPosition)
1387   - boxRoot.expand=NO
1388   - boxRoot.minsize(root_width, root_height)
1389   - rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos)
1390   - boxRoot.geometry(rootWindowPosition)
1391   -
1392   - mainframe = Frame(master=boxRoot)
1393   - mainframe.pack(side=TOP, fill=BOTH, expand=YES)
1394   -
1395   - # ---- put frames in the window -----------------------------------
1396   - # we pack the textboxFrame first, so it will expand first
1397   - textboxFrame = Frame(mainframe, borderwidth=3)
1398   - textboxFrame.pack(side=BOTTOM , fill=BOTH, expand=YES)
1399   -
1400   - message_and_buttonsFrame = Frame(mainframe)
1401   - message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO)
1402   -
1403   - messageFrame = Frame(message_and_buttonsFrame)
1404   - messageFrame.pack(side=LEFT, fill=X, expand=YES)
1405   -
1406   - buttonsFrame = Frame(message_and_buttonsFrame)
1407   - buttonsFrame.pack(side=RIGHT, expand=NO)
1408   -
1409   - # -------------------- put widgets in the frames --------------------
1410   -
1411   - # put a textArea in the top frame
1412   - if codebox:
1413   - character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE)
1414   - textArea = Text(textboxFrame,height=25,width=character_width, padx="2m", pady="1m")
1415   - textArea.configure(wrap=NONE)
1416   - textArea.configure(font=(MONOSPACE_FONT_FAMILY, MONOSPACE_FONT_SIZE))
1417   -
1418   - else:
1419   - character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE)
1420   - textArea = Text(
1421   - textboxFrame
1422   - , height=25
1423   - , width=character_width
1424   - , padx="2m"
1425   - , pady="1m"
1426   - )
1427   - textArea.configure(wrap=WORD)
1428   - textArea.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
1429   -
1430   -
1431   - # some simple keybindings for scrolling
1432   - mainframe.bind("<Next>" , textArea.yview_scroll( 1,PAGES))
1433   - mainframe.bind("<Prior>", textArea.yview_scroll(-1,PAGES))
1434   -
1435   - mainframe.bind("<Right>", textArea.xview_scroll( 1,PAGES))
1436   - mainframe.bind("<Left>" , textArea.xview_scroll(-1,PAGES))
1437   -
1438   - mainframe.bind("<Down>", textArea.yview_scroll( 1,UNITS))
1439   - mainframe.bind("<Up>" , textArea.yview_scroll(-1,UNITS))
1440   -
1441   -
1442   - # add a vertical scrollbar to the frame
1443   - rightScrollbar = Scrollbar(textboxFrame, orient=VERTICAL, command=textArea.yview)
1444   - textArea.configure(yscrollcommand = rightScrollbar.set)
1445   -
1446   - # add a horizontal scrollbar to the frame
1447   - bottomScrollbar = Scrollbar(textboxFrame, orient=HORIZONTAL, command=textArea.xview)
1448   - textArea.configure(xscrollcommand = bottomScrollbar.set)
1449   -
1450   - # pack the textArea and the scrollbars. Note that although we must define
1451   - # the textArea first, we must pack it last, so that the bottomScrollbar will
1452   - # be located properly.
1453   -
1454   - # Note that we need a bottom scrollbar only for code.
1455   - # Text will be displayed with wordwrap, so we don't need to have a horizontal
1456   - # scroll for it.
1457   - if codebox:
1458   - bottomScrollbar.pack(side=BOTTOM, fill=X)
1459   - rightScrollbar.pack(side=RIGHT, fill=Y)
1460   -
1461   - textArea.pack(side=LEFT, fill=BOTH, expand=YES)
1462   -
1463   -
1464   - # ---------- put a msg widget in the msg frame-------------------
1465   - messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9))
1466   - messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
1467   - messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m')
1468   -
1469   - # put the buttons in the buttonsFrame
1470   - okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6)
1471   - okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m")
1472   -
1473   - # for the commandButton, bind activation events to the activation event handler
1474   - commandButton = okButton
1475   - handler = __textboxOK
1476   - for selectionEvent in ["Return","Button-1","Escape"]:
1477   - commandButton.bind("<%s>" % selectionEvent, handler)
1478   -
1479   -
1480   - # ----------------- the action begins ----------------------------------------
1481   - try:
1482   - # load the text into the textArea
1483   - if type(text) == type("abc"): pass
1484   - else:
1485   - try:
1486   - text = "".join(text) # convert a list or a tuple to a string
1487   - except:
1488   - msgbox("Exception when trying to convert "+ str(type(text)) + " to text in textArea")
1489   - sys.exit(16)
1490   - textArea.insert(END,text, "normal")
1491   -
1492   - except:
1493   - msgbox("Exception when trying to load the textArea.")
1494   - sys.exit(16)
1495   -
1496   - try:
1497   - okButton.focus_force()
1498   - except:
1499   - msgbox("Exception when trying to put focus on okButton.")
1500   - sys.exit(16)
1501   -
1502   - boxRoot.mainloop()
1503   -
1504   - # this line MUST go before the line that destroys boxRoot
1505   - areaText = textArea.get(0.0,END)
1506   - boxRoot.destroy()
1507   - return areaText # return __replyButtonText
1508   -
1509   -#-------------------------------------------------------------------
1510   -# __textboxOK
1511   -#-------------------------------------------------------------------
1512   -def __textboxOK(event):
1513   - global boxRoot
1514   - boxRoot.quit()
1515   -
1516   -
1517   -
1518   -#-------------------------------------------------------------------
1519   -# diropenbox
1520   -#-------------------------------------------------------------------
1521   -def diropenbox(msg=None
1522   - , title=None
1523   - , default=None
1524   - ):
1525   - """
1526   - A dialog to get a directory name.
1527   - Note that the msg argument, if specified, is ignored.
1528   -
1529   - Returns the name of a directory, or None if user chose to cancel.
1530   -
1531   - If the "default" argument specifies a directory name, and that
1532   - directory exists, then the dialog box will start with that directory.
1533   - """
1534   - title=getFileDialogTitle(msg,title)
1535   - localRoot = Tk()
1536   - localRoot.withdraw()
1537   - if not default: default = None
1538   - f = tk_FileDialog.askdirectory(
1539   - parent=localRoot
1540   - , title=title
1541   - , initialdir=default
1542   - , initialfile=None
1543   - )
1544   - localRoot.destroy()
1545   - if not f: return None
1546   - return os.path.normpath(f)
1547   -
1548   -
1549   -
1550   -#-------------------------------------------------------------------
1551   -# getFileDialogTitle
1552   -#-------------------------------------------------------------------
1553   -def getFileDialogTitle(msg
1554   - , title
1555   - ):
1556   - if msg and title: return "%s - %s" % (title,msg)
1557   - if msg and not title: return str(msg)
1558   - if title and not msg: return str(title)
1559   - return None # no message and no title
1560   -
1561   -#-------------------------------------------------------------------
1562   -# class FileTypeObject for use with fileopenbox
1563   -#-------------------------------------------------------------------
1564   -class FileTypeObject:
1565   - def __init__(self,filemask):
1566   - if len(filemask) == 0:
1567   - raise AssertionError('Filetype argument is empty.')
1568   -
1569   - self.masks = []
1570   -
1571   - if type(filemask) == type("abc"): # a string
1572   - self.initializeFromString(filemask)
1573   -
1574   - elif type(filemask) == type([]): # a list
1575   - if len(filemask) < 2:
1576   - raise AssertionError('Invalid filemask.\n'
1577   - +'List contains less than 2 members: "%s"' % filemask)
1578   - else:
1579   - self.name = filemask[-1]
1580   - self.masks = list(filemask[:-1] )
1581   - else:
1582   - raise AssertionError('Invalid filemask: "%s"' % filemask)
1583   -
1584   - def __eq__(self,other):
1585   - if self.name == other.name: return True
1586   - return False
1587   -
1588   - def add(self,other):
1589   - for mask in other.masks:
1590   - if mask in self.masks: pass
1591   - else: self.masks.append(mask)
1592   -
1593   - def toTuple(self):
1594   - return (self.name,tuple(self.masks))
1595   -
1596   - def isAll(self):
1597   - if self.name == "All files": return True
1598   - return False
1599   -
1600   - def initializeFromString(self, filemask):
1601   - # remove everything except the extension from the filemask
1602   - self.ext = os.path.splitext(filemask)[1]
1603   - if self.ext == "" : self.ext = ".*"
1604   - if self.ext == ".": self.ext = ".*"
1605   - self.name = self.getName()
1606   - self.masks = ["*" + self.ext]
1607   -
1608   - def getName(self):
1609   - e = self.ext
1610   - if e == ".*" : return "All files"
1611   - if e == ".txt": return "Text files"
1612   - if e == ".py" : return "Python files"
1613   - if e == ".pyc" : return "Python files"
1614   - if e == ".xls": return "Excel files"
1615   - if e.startswith("."):
1616   - return e[1:].upper() + " files"
1617   - return e.upper() + " files"
1618   -
1619   -
1620   -#-------------------------------------------------------------------
1621   -# fileopenbox
1622   -#-------------------------------------------------------------------
1623   -def fileopenbox(msg=None
1624   - , title=None
1625   - , default="*"
1626   - , filetypes=None
1627   - ):
1628   - """
1629   - A dialog to get a file name.
1630   -
1631   - About the "default" argument
1632   - ============================
1633   - The "default" argument specifies a filepath that (normally)
1634   - contains one or more wildcards.
1635   - fileopenbox will display only files that match the default filepath.
1636   - If omitted, defaults to "*" (all files in the current directory).
1637   -
1638   - WINDOWS EXAMPLE::
1639   - ...default="c:/myjunk/*.py"
1640   - will open in directory c:\myjunk\ and show all Python files.
1641   -
1642   - WINDOWS EXAMPLE::
1643   - ...default="c:/myjunk/test*.py"
1644   - will open in directory c:\myjunk\ and show all Python files
1645   - whose names begin with "test".
1646   -
1647   -
1648   - Note that on Windows, fileopenbox automatically changes the path
1649   - separator to the Windows path separator (backslash).
1650   -
1651   - About the "filetypes" argument
1652   - ==============================
1653   - If specified, it should contain a list of items,
1654   - where each item is either::
1655   - - a string containing a filemask # e.g. "*.txt"
1656   - - a list of strings, where all of the strings except the last one
1657   - are filemasks (each beginning with "*.",
1658   - such as "*.txt" for text files, "*.py" for Python files, etc.).
1659   - and the last string contains a filetype description
1660   -
1661   - EXAMPLE::
1662   - filetypes = ["*.css", ["*.htm", "*.html", "HTML files"] ]
1663   -
1664   - NOTE THAT
1665   - =========
1666   -
1667   - If the filetypes list does not contain ("All files","*"),
1668   - it will be added.
1669   -
1670   - If the filetypes list does not contain a filemask that includes
1671   - the extension of the "default" argument, it will be added.
1672   - For example, if default="*abc.py"
1673   - and no filetypes argument was specified, then
1674   - "*.py" will automatically be added to the filetypes argument.
1675   -
1676   - @rtype: string or None
1677   - @return: the name of a file, or None if user chose to cancel
1678   -
1679   - @arg msg: the msg to be displayed.
1680   - @arg title: the window title
1681   - @arg default: filepath with wildcards
1682   - @arg filetypes: filemasks that a user can choose, e.g. "*.txt"
1683   - """
1684   - localRoot = Tk()
1685   - localRoot.withdraw()
1686   -
1687   - initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)
1688   -
1689   - #------------------------------------------------------------
1690   - # if initialfile contains no wildcards; we don't want an
1691   - # initial file. It won't be used anyway.
1692   - # Also: if initialbase is simply "*", we don't want an
1693   - # initialfile; it is not doing any useful work.
1694   - #------------------------------------------------------------
1695   - if (initialfile.find("*") < 0) and (initialfile.find("?") < 0):
1696   - initialfile = None
1697   - elif initialbase == "*":
1698   - initialfile = None
1699   -
1700   - f = tk_FileDialog.askopenfilename(parent=localRoot
1701   - , title=getFileDialogTitle(msg,title)
1702   - , initialdir=initialdir
1703   - , initialfile=initialfile
1704   - , filetypes=filetypes
1705   - )
1706   -
1707   - localRoot.destroy()
1708   -
1709   - if not f: return None
1710   - return os.path.normpath(f)
1711   -
1712   -
1713   -#-------------------------------------------------------------------
1714   -# filesavebox
1715   -#-------------------------------------------------------------------
1716   -def filesavebox(msg=None
1717   - , title=None
1718   - , default=""
1719   - , filetypes=None
1720   - ):
1721   - """
1722   - A file to get the name of a file to save.
1723   - Returns the name of a file, or None if user chose to cancel.
1724   -
1725   - The "default" argument should contain a filename (i.e. the
1726   - current name of the file to be saved). It may also be empty,
1727   - or contain a filemask that includes wildcards.
1728   -
1729   - The "filetypes" argument works like the "filetypes" argument to
1730   - fileopenbox.
1731   - """
1732   -
1733   - localRoot = Tk()
1734   - localRoot.withdraw()
1735   -
1736   - initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)
1737   -
1738   - f = tk_FileDialog.asksaveasfilename(parent=localRoot
1739   - , title=getFileDialogTitle(msg,title)
1740   - , initialfile=initialfile
1741   - , initialdir=initialdir
1742   - , filetypes=filetypes
1743   - )
1744   - localRoot.destroy()
1745   - if not f: return None
1746   - return os.path.normpath(f)
1747   -
1748   -
1749   -#-------------------------------------------------------------------
1750   -#
1751   -# fileboxSetup
1752   -#
1753   -#-------------------------------------------------------------------
1754   -def fileboxSetup(default,filetypes):
1755   - if not default: default = os.path.join(".","*")
1756   - initialdir, initialfile = os.path.split(default)
1757   - if not initialdir : initialdir = "."
1758   - if not initialfile: initialfile = "*"
1759   - initialbase, initialext = os.path.splitext(initialfile)
1760   - initialFileTypeObject = FileTypeObject(initialfile)
1761   -
1762   - allFileTypeObject = FileTypeObject("*")
1763   - ALL_filetypes_was_specified = False
1764   -
1765   - if not filetypes: filetypes= []
1766   - filetypeObjects = []
1767   -
1768   - for filemask in filetypes:
1769   - fto = FileTypeObject(filemask)
1770   -
1771   - if fto.isAll():
1772   - ALL_filetypes_was_specified = True # remember this
1773   -
1774   - if fto == initialFileTypeObject:
1775   - initialFileTypeObject.add(fto) # add fto to initialFileTypeObject
1776   - else:
1777   - filetypeObjects.append(fto)
1778   -
1779   - #------------------------------------------------------------------
1780   - # make sure that the list of filetypes includes the ALL FILES type.
1781   - #------------------------------------------------------------------
1782   - if ALL_filetypes_was_specified:
1783   - pass
1784   - elif allFileTypeObject == initialFileTypeObject:
1785   - pass
1786   - else:
1787   - filetypeObjects.insert(0,allFileTypeObject)
1788   - #------------------------------------------------------------------
1789   - # Make sure that the list includes the initialFileTypeObject
1790   - # in the position in the list that will make it the default.
1791   - # This changed between Python version 2.5 and 2.6
1792   - #------------------------------------------------------------------
1793   - if len(filetypeObjects) == 0:
1794   - filetypeObjects.append(initialFileTypeObject)
1795   -
1796   - if initialFileTypeObject in (filetypeObjects[0], filetypeObjects[-1]):
1797   - pass
1798   - else:
1799   - if runningPython26:
1800   - filetypeObjects.append(initialFileTypeObject)
1801   - else:
1802   - filetypeObjects.insert(0,initialFileTypeObject)
1803   -
1804   - filetypes = [fto.toTuple() for fto in filetypeObjects]
1805   -
1806   - return initialbase, initialfile, initialdir, filetypes
1807   -
1808   -#-------------------------------------------------------------------
1809   -# utility routines
1810   -#-------------------------------------------------------------------
1811   -# These routines are used by several other functions in the EasyGui module.
1812   -
1813   -def __buttonEvent(event):
1814   - """
1815   - Handle an event that is generated by a person clicking a button.
1816   - """
1817   - global boxRoot, __widgetTexts, __replyButtonText
1818   - __replyButtonText = __widgetTexts[event.widget]
1819   - boxRoot.quit() # quit the main loop
1820   -
1821   -
1822   -def __put_buttons_in_buttonframe(choices):
1823   - """Put the buttons in the buttons frame
1824   - """
1825   - global __widgetTexts, __firstWidget, buttonsFrame
1826   -
1827   - __firstWidget = None
1828   - __widgetTexts = {}
1829   -
1830   - i = 0
1831   -
1832   - for buttonText in choices:
1833   - tempButton = Button(buttonsFrame, takefocus=1, text=buttonText)
1834   - bindArrows(tempButton)
1835   - tempButton.pack(expand=YES, side=LEFT, padx='1m', pady='1m', ipadx='2m', ipady='1m')
1836   -
1837   - # remember the text associated with this widget
1838   - __widgetTexts[tempButton] = buttonText
1839   -
1840   - # remember the first widget, so we can put the focus there
1841   - if i == 0:
1842   - __firstWidget = tempButton
1843   - i = 1
1844   -
1845   - # for the commandButton, bind activation events to the activation event handler
1846   - commandButton = tempButton
1847   - handler = __buttonEvent
1848   - for selectionEvent in STANDARD_SELECTION_EVENTS:
1849   - commandButton.bind("<%s>" % selectionEvent, handler)
1850   -
1851   -#-----------------------------------------------------------------------
1852   -#
1853   -# class EgStore
1854   -#
1855   -#-----------------------------------------------------------------------
1856   -class EgStore:
1857   - r"""
1858   -A class to support persistent storage.
1859   -
1860   -You can use EgStore to support the storage and retrieval
1861   -of user settings for an EasyGui application.
1862   -
1863   -
1864   -# Example A
1865   -#-----------------------------------------------------------------------
1866   -# define a class named Settings as a subclass of EgStore
1867   -#-----------------------------------------------------------------------
1868   -class Settings(EgStore):
1869   -::
1870   - def __init__(self, filename): # filename is required
1871   - #-------------------------------------------------
1872   - # Specify default/initial values for variables that
1873   - # this particular application wants to remember.
1874   - #-------------------------------------------------
1875   - self.userId = ""
1876   - self.targetServer = ""
1877   -
1878   - #-------------------------------------------------
1879   - # For subclasses of EgStore, these must be
1880   - # the last two statements in __init__
1881   - #-------------------------------------------------
1882   - self.filename = filename # this is required
1883   - self.restore() # restore values from the storage file if possible
1884   -
1885   -
1886   -
1887   -# Example B
1888   -#-----------------------------------------------------------------------
1889   -# create settings, a persistent Settings object
1890   -#-----------------------------------------------------------------------
1891   -settingsFile = "myApp_settings.txt"
1892   -settings = Settings(settingsFile)
1893   -
1894   -user = "obama_barak"
1895   -server = "whitehouse1"
1896   -settings.userId = user
1897   -settings.targetServer = server
1898   -settings.store() # persist the settings
1899   -
1900   -# run code that gets a new value for userId, and persist the settings
1901   -user = "biden_joe"
1902   -settings.userId = user
1903   -settings.store()
1904   -
1905   -
1906   -# Example C
1907   -#-----------------------------------------------------------------------
1908   -# recover the Settings instance, change an attribute, and store it again.
1909   -#-----------------------------------------------------------------------
1910   -settings = Settings(settingsFile)
1911   -settings.userId = "vanrossum_g"
1912   -settings.store()
1913   -
1914   -"""
1915   - def __init__(self, filename): # obtaining filename is required
1916   - self.filename = None
1917   - raise NotImplementedError()
1918   -
1919   - def restore(self):
1920   - """
1921   - Set the values of whatever attributes are recoverable
1922   - from the pickle file.
1923   -
1924   - Populate the attributes (the __dict__) of the EgStore object
1925   - from the attributes (the __dict__) of the pickled object.
1926   -
1927   - If the pickled object has attributes that have been initialized
1928   - in the EgStore object, then those attributes of the EgStore object
1929   - will be replaced by the values of the corresponding attributes
1930   - in the pickled object.
1931   -
1932   - If the pickled object is missing some attributes that have
1933   - been initialized in the EgStore object, then those attributes
1934   - of the EgStore object will retain the values that they were
1935   - initialized with.
1936   -
1937   - If the pickled object has some attributes that were not
1938   - initialized in the EgStore object, then those attributes
1939   - will be ignored.
1940   -
1941   - IN SUMMARY:
1942   -
1943   - After the recover() operation, the EgStore object will have all,
1944   - and only, the attributes that it had when it was initialized.
1945   -
1946   - Where possible, those attributes will have values recovered
1947   - from the pickled object.
1948   - """
1949   - if not os.path.exists(self.filename): return self
1950   - if not os.path.isfile(self.filename): return self
1951   -
1952   - try:
1953   - f = open(self.filename,"rb")
1954   - unpickledObject = pickle.load(f)
1955   - f.close()
1956   -
1957   - for key in list(self.__dict__.keys()):
1958   - default = self.__dict__[key]
1959   - self.__dict__[key] = unpickledObject.__dict__.get(key,default)
1960   - except:
1961   - pass
1962   -
1963   - return self
1964   -
1965   - def store(self):
1966   - """
1967   - Save the attributes of the EgStore object to a pickle file.
1968   - Note that if the directory for the pickle file does not already exist,
1969   - the store operation will fail.
1970   - """
1971   - f = open(self.filename, "wb")
1972   - pickle.dump(self, f)
1973   - f.close()
1974   -
1975   -
1976   - def kill(self):
1977   - """
1978   - Delete my persistent file (i.e. pickle file), if it exists.
1979   - """
1980   - if os.path.isfile(self.filename):
1981   - os.remove(self.filename)
1982   - return
1983   -
1984   - def __str__(self):
1985   - """
1986   - return my contents as a string in an easy-to-read format.
1987   - """
1988   - # find the length of the longest attribute name
1989   - longest_key_length = 0
1990   - keys = []
1991   - for key in self.__dict__.keys():
1992   - keys.append(key)
1993   - longest_key_length = max(longest_key_length, len(key))
1994   -
1995   - keys.sort() # sort the attribute names
1996   - lines = []
1997   - for key in keys:
1998   - value = self.__dict__[key]
1999   - key = key.ljust(longest_key_length)
2000   - lines.append("%s : %s\n" % (key,repr(value)) )
2001   - return "".join(lines) # return a string showing the attributes
2002   -
2003   -
2004   -
2005   -
2006   -#-----------------------------------------------------------------------
2007   -#
2008   -# test/demo easygui
2009   -#
2010   -#-----------------------------------------------------------------------
2011   -def egdemo():
2012   - """
2013   - Run the EasyGui demo.
2014   - """
2015   - # clear the console
2016   - writeln("\n" * 100)
2017   -
2018   - intro_message = ("Pick the kind of box that you wish to demo.\n"
2019   - + "\n * Python version " + sys.version
2020   - + "\n * EasyGui version " + egversion
2021   - + "\n * Tk version " + str(TkVersion)
2022   - )
2023   -
2024   - #========================================== END DEMONSTRATION DATA
2025   -
2026   -
2027   - while 1: # do forever
2028   - choices = [
2029   - "msgbox",
2030   - "buttonbox",
2031   - "buttonbox(image) -- a buttonbox that displays an image",
2032   - "choicebox",
2033   - "multchoicebox",
2034   - "textbox",
2035   - "ynbox",
2036   - "ccbox",
2037   - "enterbox",
2038   - "enterbox(image) -- an enterbox that displays an image",
2039   - "exceptionbox",
2040   - "codebox",
2041   - "integerbox",
2042   - "boolbox",
2043   - "indexbox",
2044   - "filesavebox",
2045   - "fileopenbox",
2046   - "passwordbox",
2047   - "multenterbox",
2048   - "multpasswordbox",
2049   - "diropenbox",
2050   - "About EasyGui",
2051   - " Help"
2052   - ]
2053   - choice = choicebox(msg=intro_message
2054   - , title="EasyGui " + egversion
2055   - , choices=choices)
2056   -
2057   - if not choice: return
2058   -
2059   - reply = choice.split()
2060   -
2061   - if reply[0] == "msgbox":
2062   - reply = msgbox("short msg", "This is a long title")
2063   - writeln("Reply was: %s" % repr(reply))
2064   -
2065   - elif reply[0] == "About":
2066   - reply = abouteasygui()
2067   -
2068   - elif reply[0] == "Help":
2069   - _demo_help()
2070   -
2071   - elif reply[0] == "buttonbox":
2072   - reply = buttonbox()
2073   - writeln("Reply was: %s" % repr(reply))
2074   -
2075   - title = "Demo of Buttonbox with many, many buttons!"
2076   - msg = "This buttonbox shows what happens when you specify too many buttons."
2077   - reply = buttonbox(msg=msg, title=title, choices=choices)
2078   - writeln("Reply was: %s" % repr(reply))
2079   -
2080   - elif reply[0] == "buttonbox(image)":
2081   - _demo_buttonbox_with_image()
2082   -
2083   - elif reply[0] == "boolbox":
2084   - reply = boolbox()
2085   - writeln("Reply was: %s" % repr(reply))
2086   -
2087   - elif reply[0] == "enterbox":
2088   - image = "python_and_check_logo.gif"
2089   - message = "Enter the name of your best friend."\
2090   - "\n(Result will be stripped.)"
2091   - reply = enterbox(message, "Love!", " Suzy Smith ")
2092   - writeln("Reply was: %s" % repr(reply))
2093   -
2094   - message = "Enter the name of your best friend."\
2095   - "\n(Result will NOT be stripped.)"
2096   - reply = enterbox(message, "Love!", " Suzy Smith ",strip=False)
2097   - writeln("Reply was: %s" % repr(reply))
2098   -
2099   - reply = enterbox("Enter the name of your worst enemy:", "Hate!")
2100   - writeln("Reply was: %s" % repr(reply))
2101   -
2102   - elif reply[0] == "enterbox(image)":
2103   - image = "python_and_check_logo.gif"
2104   - message = "What kind of snake is this?"
2105   - reply = enterbox(message, "Quiz",image=image)
2106   - writeln("Reply was: %s" % repr(reply))
2107   -
2108   - elif reply[0] == "exceptionbox":
2109   - try:
2110   - thisWillCauseADivideByZeroException = 1/0
2111   - except:
2112   - exceptionbox()
2113   -
2114   - elif reply[0] == "integerbox":
2115   - reply = integerbox(
2116   - "Enter a number between 3 and 333",
2117   - "Demo: integerbox WITH a default value",
2118   - 222, 3, 333)
2119   - writeln("Reply was: %s" % repr(reply))
2120   -
2121   - reply = integerbox(
2122   - "Enter a number between 0 and 99",
2123   - "Demo: integerbox WITHOUT a default value"
2124   - )
2125   - writeln("Reply was: %s" % repr(reply))
2126   -
2127   - elif reply[0] == "diropenbox" : _demo_diropenbox()
2128   - elif reply[0] == "fileopenbox": _demo_fileopenbox()
2129   - elif reply[0] == "filesavebox": _demo_filesavebox()
2130   -
2131   - elif reply[0] == "indexbox":
2132   - title = reply[0]
2133   - msg = "Demo of " + reply[0]
2134   - choices = ["Choice1", "Choice2", "Choice3", "Choice4"]
2135   - reply = indexbox(msg, title, choices)
2136   - writeln("Reply was: %s" % repr(reply))
2137   -
2138   - elif reply[0] == "passwordbox":
2139   - reply = passwordbox("Demo of password box WITHOUT default"
2140   - + "\n\nEnter your secret password", "Member Logon")
2141   - writeln("Reply was: %s" % str(reply))
2142   -
2143   - reply = passwordbox("Demo of password box WITH default"
2144   - + "\n\nEnter your secret password", "Member Logon", "alfie")
2145   - writeln("Reply was: %s" % str(reply))
2146   -
2147   - elif reply[0] == "multenterbox":
2148   - msg = "Enter your personal information"
2149   - title = "Credit Card Application"
2150   - fieldNames = ["Name","Street Address","City","State","ZipCode"]
2151   - fieldValues = [] # we start with blanks for the values
2152   - fieldValues = multenterbox(msg,title, fieldNames)
2153   -
2154   - # make sure that none of the fields was left blank
2155   - while 1:
2156   - if fieldValues == None: break
2157   - errmsg = ""
2158   - for i in range(len(fieldNames)):
2159   - if fieldValues[i].strip() == "":
2160   - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
2161   - if errmsg == "": break # no problems found
2162   - fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)
2163   -
2164   - writeln("Reply was: %s" % str(fieldValues))
2165   -
2166   - elif reply[0] == "multpasswordbox":
2167   - msg = "Enter logon information"
2168   - title = "Demo of multpasswordbox"
2169   - fieldNames = ["Server ID", "User ID", "Password"]
2170   - fieldValues = [] # we start with blanks for the values
2171   - fieldValues = multpasswordbox(msg,title, fieldNames)
2172   -
2173   - # make sure that none of the fields was left blank
2174   - while 1:
2175   - if fieldValues == None: break
2176   - errmsg = ""
2177   - for i in range(len(fieldNames)):
2178   - if fieldValues[i].strip() == "":
2179   - errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
2180   - if errmsg == "": break # no problems found
2181   - fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
2182   -
2183   - writeln("Reply was: %s" % str(fieldValues))
2184   -
2185   - elif reply[0] == "ynbox":
2186   - title = "Demo of ynbox"
2187   - msg = "Were you expecting the Spanish Inquisition?"
2188   - reply = ynbox(msg, title)
2189   - writeln("Reply was: %s" % repr(reply))
2190   - if reply:
2191   - msgbox("NOBODY expects the Spanish Inquisition!", "Wrong!")
2192   -
2193   - elif reply[0] == "ccbox":
2194   - title = "Demo of ccbox"
2195   - reply = ccbox(msg,title)
2196   - writeln("Reply was: %s" % repr(reply))
2197   -
2198   - elif reply[0] == "choicebox":
2199   - title = "Demo of choicebox"
2200   - longchoice = "This is an example of a very long option which you may or may not wish to choose."*2
2201   - listChoices = ["nnn", "ddd", "eee", "fff", "aaa", longchoice
2202   - , "aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk", "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq", "rrr", "sss", "ttt", "uuu", "vvv"]
2203   -
2204   - msg = "Pick something. " + ("A wrapable sentence of text ?! "*30) + "\nA separate line of text."*6
2205   - reply = choicebox(msg=msg, choices=listChoices)
2206   - writeln("Reply was: %s" % repr(reply))
2207   -
2208   - msg = "Pick something. "
2209   - reply = choicebox(msg=msg, title=title, choices=listChoices)
2210   - writeln("Reply was: %s" % repr(reply))
2211   -
2212   - msg = "Pick something. "
2213   - reply = choicebox(msg="The list of choices is empty!", choices=[])
2214   - writeln("Reply was: %s" % repr(reply))
2215   -
2216   - elif reply[0] == "multchoicebox":
2217   - listChoices = ["aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk"
2218   - , "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq"
2219   - , "rrr", "sss", "ttt", "uuu", "vvv"]
2220   -
2221   - msg = "Pick as many choices as you wish."
2222   - reply = multchoicebox(msg,"Demo of multchoicebox", listChoices)
2223   - writeln("Reply was: %s" % repr(reply))
2224   -
2225   - elif reply[0] == "textbox": _demo_textbox(reply[0])
2226   - elif reply[0] == "codebox": _demo_codebox(reply[0])
2227   -
2228   - else:
2229   - msgbox("Choice\n\n" + choice + "\n\nis not recognized", "Program Logic Error")
2230   - return
2231   -
2232   -
2233   -def _demo_textbox(reply):
2234   - text_snippet = ((\
2235   -"""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! """ \
2236   -*5)+"\n\n")*10
2237   - title = "Demo of textbox"
2238   - msg = "Here is some sample text. " * 16
2239   - reply = textbox(msg, title, text_snippet)
2240   - writeln("Reply was: %s" % str(reply))
2241   -
2242   -def _demo_codebox(reply):
2243   - code_snippet = ("dafsdfa dasflkj pp[oadsij asdfp;ij asdfpjkop asdfpok asdfpok asdfpok"*3) +"\n"+\
2244   -"""# here is some dummy Python code
2245   -for someItem in myListOfStuff:
2246   - do something(someItem)
2247   - do something()
2248   - do something()
2249   - if somethingElse(someItem):
2250   - doSomethingEvenMoreInteresting()
2251   -
2252   -"""*16
2253   - msg = "Here is some sample code. " * 16
2254   - reply = codebox(msg, "Code Sample", code_snippet)
2255   - writeln("Reply was: %s" % repr(reply))
2256   -
2257   -
2258   -def _demo_buttonbox_with_image():
2259   -
2260   - msg = "Do you like this picture?\nIt is "
2261   - choices = ["Yes","No","No opinion"]
2262   -
2263   - for image in [
2264   - "python_and_check_logo.gif"
2265   - ,"python_and_check_logo.jpg"
2266   - ,"python_and_check_logo.png"
2267   - ,"zzzzz.gif"]:
2268   -
2269   - reply=buttonbox(msg + image,image=image,choices=choices)
2270   - writeln("Reply was: %s" % repr(reply))
2271   -
2272   -
2273   -def _demo_help():
2274   - savedStdout = sys.stdout # save the sys.stdout file object
2275   - sys.stdout = capturedOutput = StringIO()
2276   - help("easygui")
2277   - sys.stdout = savedStdout # restore the sys.stdout file object
2278   - codebox("EasyGui Help",text=capturedOutput.getvalue())
2279   -
2280   -def _demo_filesavebox():
2281   - filename = "myNewFile.txt"
2282   - title = "File SaveAs"
2283   - msg ="Save file as:"
2284   -
2285   - f = filesavebox(msg,title,default=filename)
2286   - writeln("You chose to save file: %s" % f)
2287   -
2288   -def _demo_diropenbox():
2289   - title = "Demo of diropenbox"
2290   - msg = "Pick the directory that you wish to open."
2291   - d = diropenbox(msg, title)
2292   - writeln("You chose directory...: %s" % d)
2293   -
2294   - d = diropenbox(msg, title,default="./")
2295   - writeln("You chose directory...: %s" % d)
2296   -
2297   - d = diropenbox(msg, title,default="c:/")
2298   - writeln("You chose directory...: %s" % d)
2299   -
2300   -
2301   -def _demo_fileopenbox():
2302   - msg = "Python files"
2303   - title = "Open files"
2304   - default="*.py"
2305   - f = fileopenbox(msg,title,default=default)
2306   - writeln("You chose to open file: %s" % f)
2307   -
2308   - default="./*.gif"
2309   - filetypes = ["*.jpg",["*.zip","*.tgs","*.gz", "Archive files"],["*.htm", "*.html","HTML files"]]
2310   - f = fileopenbox(msg,title,default=default,filetypes=filetypes)
2311   - writeln("You chose to open file: %s" % f)
2312   -
2313   - """#deadcode -- testing ----------------------------------------
2314   - f = fileopenbox(None,None,default=default)
2315   - writeln("You chose to open file: %s" % f)
2316   -
2317   - f = fileopenbox(None,title,default=default)
2318   - writeln("You chose to open file: %s" % f)
2319   -
2320   - f = fileopenbox(msg,None,default=default)
2321   - writeln("You chose to open file: %s" % f)
2322   -
2323   - f = fileopenbox(default=default)
2324   - writeln("You chose to open file: %s" % f)
2325   -
2326   - f = fileopenbox(default=None)
2327   - writeln("You chose to open file: %s" % f)
2328   - #----------------------------------------------------deadcode """
2329   -
2330   -
2331   -def _dummy():
2332   - pass
2333   -
2334   -EASYGUI_ABOUT_INFORMATION = '''
2335   -========================================================================
2336   -0.96(2010-08-29)
2337   -========================================================================
2338   -This version fixes some problems with version independence.
2339   -
2340   -BUG FIXES
2341   -------------------------------------------------------
2342   - * A statement with Python 2.x-style exception-handling syntax raised
2343   - a syntax error when running under Python 3.x.
2344   - Thanks to David Williams for reporting this problem.
2345   -
2346   - * Under some circumstances, PIL was unable to display non-gif images
2347   - that it should have been able to display.
2348   - The cause appears to be non-version-independent import syntax.
2349   - PIL modules are now imported with a version-independent syntax.
2350   - Thanks to Horst Jens for reporting this problem.
2351   -
2352   -LICENSE CHANGE
2353   -------------------------------------------------------
2354   -Starting with this version, EasyGui is licensed under what is generally known as
2355   -the "modified BSD license" (aka "revised BSD", "new BSD", "3-clause BSD").
2356   -This license is GPL-compatible but less restrictive than GPL.
2357   -Earlier versions were licensed under the Creative Commons Attribution License 2.0.
2358   -
2359   -
2360   -========================================================================
2361   -0.95(2010-06-12)
2362   -========================================================================
2363   -
2364   -ENHANCEMENTS
2365   -------------------------------------------------------
2366   - * Previous versions of EasyGui could display only .gif image files using the
2367   - msgbox "image" argument. This version can now display all image-file formats
2368   - supported by PIL the Python Imaging Library) if PIL is installed.
2369   - If msgbox is asked to open a non-gif image file, it attempts to import
2370   - PIL and to use PIL to convert the image file to a displayable format.
2371   - If PIL cannot be imported (probably because PIL is not installed)
2372   - EasyGui displays an error message saying that PIL must be installed in order
2373   - to display the image file.
2374   -
2375   - Note that
2376   - http://www.pythonware.com/products/pil/
2377   - says that PIL doesn't yet support Python 3.x.
2378   -
2379   -
2380   -========================================================================
2381   -0.94(2010-06-06)
2382   -========================================================================
2383   -
2384   -ENHANCEMENTS
2385   -------------------------------------------------------
2386   - * The codebox and textbox functions now return the contents of the box, rather
2387   - than simply the name of the button ("Yes"). This makes it possible to use
2388   - codebox and textbox as data-entry widgets. A big "thank you!" to Dominic
2389   - Comtois for requesting this feature, patiently explaining his requirement,
2390   - and helping to discover the tkinter techniques to implement it.
2391   -
2392   - NOTE THAT in theory this change breaks backward compatibility. But because
2393   - (in previous versions of EasyGui) the value returned by codebox and textbox
2394   - was meaningless, no application should have been checking it. So in actual
2395   - practice, this change should not break backward compatibility.
2396   -
2397   - * Added support for SPACEBAR to command buttons. Now, when keyboard
2398   - focus is on a command button, a press of the SPACEBAR will act like
2399   - a press of the ENTER key; it will activate the command button.
2400   -
2401   - * Added support for keyboard navigation with the arrow keys (up,down,left,right)
2402   - to the fields and buttons in enterbox, multenterbox and multpasswordbox,
2403   - and to the buttons in choicebox and all buttonboxes.
2404   -
2405   - * added highlightthickness=2 to entry fields in multenterbox and
2406   - multpasswordbox. Now it is easier to tell which entry field has
2407   - keyboard focus.
2408   -
2409   -
2410   -BUG FIXES
2411   -------------------------------------------------------
2412   - * In EgStore, the pickle file is now opened with "rb" and "wb" rather than
2413   - with "r" and "w". This change is necessary for compatibility with Python 3+.
2414   - Thanks to Marshall Mattingly for reporting this problem and providing the fix.
2415   -
2416   - * In integerbox, the actual argument names did not match the names described
2417   - in the docstring. Thanks to Daniel Zingaro of at University of Toronto for
2418   - reporting this problem.
2419   -
2420   - * In integerbox, the "argLowerBound" and "argUpperBound" arguments have been
2421   - renamed to "lowerbound" and "upperbound" and the docstring has been corrected.
2422   -
2423   - NOTE THAT THIS CHANGE TO THE ARGUMENT-NAMES BREAKS BACKWARD COMPATIBILITY.
2424   - If argLowerBound or argUpperBound are used, an AssertionError with an
2425   - explanatory error message is raised.
2426   -
2427   - * In choicebox, the signature to choicebox incorrectly showed choicebox as
2428   - accepting a "buttons" argument. The signature has been fixed.
2429   -
2430   -
2431   -========================================================================
2432   -0.93(2009-07-07)
2433   -========================================================================
2434   -
2435   -ENHANCEMENTS
2436   -------------------------------------------------------
2437   -
2438   - * Added exceptionbox to display stack trace of exceptions
2439   -
2440   - * modified names of some font-related constants to make it
2441   - easier to customize them
2442   -
2443   -
2444   -========================================================================
2445   -0.92(2009-06-22)
2446   -========================================================================
2447   -
2448   -ENHANCEMENTS
2449   -------------------------------------------------------
2450   -
2451   - * Added EgStore class to to provide basic easy-to-use persistence.
2452   -
2453   -BUG FIXES
2454   -------------------------------------------------------
2455   -
2456   - * Fixed a bug that was preventing Linux users from copying text out of
2457   - a textbox and a codebox. This was not a problem for Windows users.
2458   -
2459   -'''
2460   -
2461   -def abouteasygui():
2462   - """
2463   - shows the easygui revision history
2464   - """
2465   - codebox("About EasyGui\n"+egversion,"EasyGui",EASYGUI_ABOUT_INFORMATION)
2466   - return None
2467   -
2468   -
2469   -
2470   -if __name__ == '__main__':
2471   - if True:
2472   - egdemo()
2473   - else:
2474   - # test the new root feature
2475   - root = Tk()
2476   - msg = """This is a test of a main Tk() window in which we will place an easygui msgbox.
2477   - It will be an interesting experiment.\n\n"""
2478   - messageWidget = Message(root, text=msg, width=1000)
2479   - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
2480   - messageWidget = Message(root, text=msg, width=1000)
2481   - messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
2482   -
2483   -
2484   - msgbox("this is a test of passing in boxRoot", root=root)
2485   - msgbox("this is a second test of passing in boxRoot", root=root)
2486   -
2487   - reply = enterbox("Enter something", root=root)
2488   - writeln("You wrote:", reply)
2489   -
2490   - reply = enterbox("Enter something else", root=root)
2491   - writeln("You wrote:", reply)
2492   - root.destroy()
oletools/thirdparty/olefile/CONTRIBUTORS.txt deleted
1   -CONTRIBUTORS for the olefile project
2   -====================================
3   -
4   -This is a non-exhaustive list of all the people who helped me improve the
5   -olefile project (formerly OleFileIO_PL), in approximative chronological order.
6   -Please contact me if I forgot to mention your name.
7   -
8   -A big thank you to all of them:
9   -
10   -- Niko Ehrenfeuchter: added support for Jython
11   -- Niko Ehrenfeuchter, Martijn Berger and Dave Jones: helped fix 4K sector support
12   -- Martin Panter: conversion to Python 3.x/2.6+
13   -- mete0r_kr: added support for file-like objects
14   -- chuckleberryfinn: fixed bug in getproperties
15   -- Martijn, Ben G.: bug report for 64 bits platforms
16   -- Philippe Lagadec: main author and maintainer since 2005
17   -- and of course Fredrik Lundh: original author of OleFileIO from 1995 to 2005
oletools/thirdparty/olefile/LICENSE.txt deleted
1   -LICENSE for the olefile package:
2   -
3   -olefile (formerly OleFileIO_PL) is copyright (c) 2005-2016 Philippe Lagadec
4   -(http://www.decalage.info)
5   -
6   -All rights reserved.
7   -
8   -Redistribution and use in source and binary forms, with or without modification,
9   -are permitted provided that the following conditions are met:
10   -
11   - * Redistributions of source code must retain the above copyright notice, this
12   - list of conditions and the following disclaimer.
13   - * Redistributions in binary form must reproduce the above copyright notice,
14   - this list of conditions and the following disclaimer in the documentation
15   - and/or other materials provided with the distribution.
16   -
17   -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18   -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19   -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20   -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21   -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22   -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23   -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24   -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25   -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26   -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27   -
28   -
29   -----------
30   -
31   -olefile is based on source code from the OleFileIO module of the Python
32   -Imaging Library (PIL) published by Fredrik Lundh under the following license:
33   -
34   -The Python Imaging Library (PIL) is
35   -- Copyright (c) 1997-2005 by Secret Labs AB
36   -- Copyright (c) 1995-2005 by Fredrik Lundh
37   -
38   -By obtaining, using, and/or copying this software and/or its associated
39   -documentation, you agree that you have read, understood, and will comply with
40   -the following terms and conditions:
41   -
42   -Permission to use, copy, modify, and distribute this software and its
43   -associated documentation for any purpose and without fee is hereby granted,
44   -provided that the above copyright notice appears in all copies, and that both
45   -that copyright notice and this permission notice appear in supporting
46   -documentation, and that the name of Secret Labs AB or the author not be used
47   -in advertising or publicity pertaining to distribution of the software without
48   -specific, written prior permission.
49   -
50   -SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
51   -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
52   -NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
53   -INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
54   -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
55   -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
56   -PERFORMANCE OF THIS SOFTWARE.
oletools/thirdparty/olefile/README.html deleted
1   -<h1 id="olefile-formerly-olefileio_pl">olefile (formerly OleFileIO_PL)</h1>
2   -<p><a href="http://www.decalage.info/olefile">olefile</a> is a Python package to parse, read and write <a href="http://en.wikipedia.org/wiki/Compound_File_Binary_Format">Microsoft OLE2 files</a> (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.</p>
3   -<p><strong>Quick links:</strong> <a href="http://www.decalage.info/olefile">Home page</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/wiki/Install">Download/Install</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">Documentation</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/issues?status=new&amp;status=open">Report Issues/Suggestions/Questions</a> - <a href="http://decalage.info/contact">Contact the author</a> - <a href="https://bitbucket.org/decalage/olefileio_pl">Repository</a> - <a href="https://twitter.com/decalage2">Updates on Twitter</a></p>
4   -<h2 id="news">News</h2>
5   -<p>Follow all updates and news on Twitter: <a href="https://twitter.com/decalage2">https://twitter.com/decalage2</a></p>
6   -<ul>
7   -<li><strong>2016-02-02 v0.43</strong>: fixed issues <a href="https://bitbucket.org/decalage/olefileio_pl/issues/26/variable-referenced-before-assignment">#26</a> and <a href="https://bitbucket.org/decalage/olefileio_pl/issues/27/incomplete-ole-stream-incorrect-ole-fat">#27</a>, better handling of malformed files, use python logging.</li>
8   -<li>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.</li>
9   -<li>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)</li>
10   -<li>2014-10-01 v0.40: renamed OleFileIO_PL to olefile, added initial write support for streams &gt;4K, updated doc and license, improved the setup script.</li>
11   -<li>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)</li>
12   -<li>2014-02-04 v0.30: now compatible with Python 3.x, thanks to Martin Panter who did most of the hard work.</li>
13   -<li>2013-07-24 v0.26: added methods to parse stream/storage timestamps, improved listdir to include storages, fixed parsing of direntry timestamps</li>
14   -<li>2013-05-27 v0.25: improved metadata extraction, properties parsing and exception handling, fixed <a href="https://bitbucket.org/decalage/olefileio_pl/issue/12/error-when-converting-timestamps-in-ole">issue #12</a></li>
15   -<li>2013-05-07 v0.24: new features to extract metadata (get_metadata method and OleMetadata class), improved getproperties to convert timestamps to Python datetime</li>
16   -<li>2012-10-09: published <a href="http://www.decalage.info/python/oletools">python-oletools</a>, a package of analysis tools based on OleFileIO_PL</li>
17   -<li>2012-09-11 v0.23: added support for file-like objects, fixed <a href="https://bitbucket.org/decalage/olefileio_pl/issue/8/bug-with-file-object">issue #8</a></li>
18   -<li>2012-02-17 v0.22: fixed issues #7 (bug in getproperties) and #2 (added close method)</li>
19   -<li>2011-10-20: code hosted on bitbucket to ease contributions and bug tracking</li>
20   -<li>2010-01-24 v0.21: fixed support for big-endian CPUs, such as PowerPC Macs.</li>
21   -<li>2009-12-11 v0.20: small bugfix in OleFileIO.open when filename is not plain str.</li>
22   -<li>2009-12-10 v0.19: fixed support for 64 bits platforms (thanks to Ben G. and Martijn for reporting the bug)</li>
23   -<li>see changelog in source code for more info.</li>
24   -</ul>
25   -<h2 id="downloadinstall">Download/Install</h2>
26   -<p>If you have pip or setuptools installed (pip is included in Python 2.7.9+), you may simply run <strong>pip install olefile</strong> or <strong>easy_install olefile</strong> for the first installation.</p>
27   -<p>To update olefile, run <strong>pip install -U olefile</strong>.</p>
28   -<p>Otherwise, see https://bitbucket.org/decalage/olefileio_pl/wiki/Install</p>
29   -<h2 id="features">Features</h2>
30   -<ul>
31   -<li>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</li>
32   -<li>List all the streams and storages contained in an OLE file</li>
33   -<li>Open streams as files</li>
34   -<li>Parse and read property streams, containing metadata of the file</li>
35   -<li>Portable, pure Python module, no dependency</li>
36   -</ul>
37   -<p>olefile can be used as an independent package or with PIL/Pillow.</p>
38   -<p>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 <a href="http://www.decalage.info/python/oletools">python-oletools</a>, which are built upon olefile and provide a higher-level interface.</p>
39   -<h2 id="history">History</h2>
40   -<p>olefile is based on the OleFileIO module from <a href="http://www.pythonware.com/products/pil/index.htm">PIL</a>, 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.</p>
41   -<p>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)</p>
42   -<p>Since 2014 olefile/OleFileIO_PL has been integrated into <a href="http://python-imaging.github.io/">Pillow</a>, the friendly fork of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly.</p>
43   -<h2 id="main-improvements-over-the-original-version-of-olefileio-in-pil">Main improvements over the original version of OleFileIO in PIL:</h2>
44   -<ul>
45   -<li>Compatible with Python 3.x and 2.6+</li>
46   -<li>Many bug fixes</li>
47   -<li>Support for files larger than 6.8MB</li>
48   -<li>Support for 64 bits platforms and big-endian CPUs</li>
49   -<li>Robust: many checks to detect malformed files</li>
50   -<li>Runtime option to choose if malformed files should be parsed or raise exceptions</li>
51   -<li>Improved API</li>
52   -<li>Metadata extraction, stream/storage timestamps (e.g. for document forensics)</li>
53   -<li>Can open file-like objects</li>
54   -<li>Added setup.py and install.bat to ease installation</li>
55   -<li>More convenient slash-based syntax for stream paths</li>
56   -<li>Write features</li>
57   -</ul>
58   -<h2 id="documentation">Documentation</h2>
59   -<p>Please see the <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">online documentation</a> for more information, especially the <a href="https://bitbucket.org/decalage/olefileio_pl/wiki/OLE_Overview">OLE overview</a> and the <a href="https://bitbucket.org/decalage/olefileio_pl/wiki/API">API page</a> 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.</p>
60   -<h2 id="real-life-examples">Real-life examples</h2>
61   -<p>A real-life example: <a href="http://blog.gregback.net/2011/03/using-remnux-for-forensic-puzzle-6/">using OleFileIO_PL for malware analysis and forensics</a>.</p>
62   -<p>See also <a href="https://computer-forensics.sans.org/community/papers/gcfa/grow-forensic-tools-taxonomy-python-libraries-helpful-forensic-analysis_6879">this paper</a> about python tools for forensics, which features olefile.</p>
63   -<h2 id="license">License</h2>
64   -<p>olefile (formerly OleFileIO_PL) is copyright (c) 2005-2016 Philippe Lagadec (<a href="http://www.decalage.info">http://www.decalage.info</a>)</p>
65   -<p>All rights reserved.</p>
66   -<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>
67   -<ul>
68   -<li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li>
69   -<li>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.</li>
70   -</ul>
71   -<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; 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.</p>
72   -<hr />
73   -<p>olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license:</p>
74   -<p>The Python Imaging Library (PIL) is</p>
75   -<ul>
76   -<li>Copyright (c) 1997-2005 by Secret Labs AB</li>
77   -<li>Copyright (c) 1995-2005 by Fredrik Lundh</li>
78   -</ul>
79   -<p>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:</p>
80   -<p>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.</p>
81   -<p>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.</p>
oletools/thirdparty/olefile/README.rst deleted
1   -olefile (formerly OleFileIO\_PL)
2   -================================
3   -
4   -`olefile <http://www.decalage.info/olefile>`__ is a Python package to
5   -parse, read and write `Microsoft OLE2
6   -files <http://en.wikipedia.org/wiki/Compound_File_Binary_Format>`__
7   -(also called Structured Storage, Compound File Binary Format or Compound
8   -Document File Format), such as Microsoft Office 97-2003 documents,
9   -vbaProject.bin in MS Office 2007+ files, Image Composer and FlashPix
10   -files, Outlook messages, StickyNotes, several Microscopy file formats,
11   -McAfee antivirus quarantine files, etc.
12   -
13   -**Quick links:** `Home page <http://www.decalage.info/olefile>`__ -
14   -`Download/Install <https://bitbucket.org/decalage/olefileio_pl/wiki/Install>`__
15   -- `Documentation <https://bitbucket.org/decalage/olefileio_pl/wiki>`__ -
16   -`Report
17   -Issues/Suggestions/Questions <https://bitbucket.org/decalage/olefileio_pl/issues?status=new&status=open>`__
18   -- `Contact the author <http://decalage.info/contact>`__ -
19   -`Repository <https://bitbucket.org/decalage/olefileio_pl>`__ - `Updates
20   -on Twitter <https://twitter.com/decalage2>`__
21   -
22   -News
23   -----
24   -
25   -Follow all updates and news on Twitter: https://twitter.com/decalage2
26   -
27   -- **2016-02-02 v0.43**: fixed issues
28   - `#26 <https://bitbucket.org/decalage/olefileio_pl/issues/26/variable-referenced-before-assignment>`__
29   - and
30   - `#27 <https://bitbucket.org/decalage/olefileio_pl/issues/27/incomplete-ole-stream-incorrect-ole-fat>`__,
31   - better handling of malformed files, use python logging.
32   -- 2015-01-25 v0.42: improved handling of special characters in
33   - stream/storage names on Python 2.x (using UTF-8 instead of Latin-1),
34   - fixed bug in listdir with empty storages.
35   -- 2014-11-25 v0.41: OleFileIO.open and isOleFile now support OLE files
36   - stored in byte strings, fixed installer for python 3, added support
37   - for Jython (Niko Ehrenfeuchter)
38   -- 2014-10-01 v0.40: renamed OleFileIO\_PL to olefile, added initial
39   - write support for streams >4K, updated doc and license, improved the
40   - setup script.
41   -- 2014-07-27 v0.31: fixed support for large files with 4K sectors,
42   - thanks to Niko Ehrenfeuchter, Martijn Berger and Dave Jones. Added
43   - test scripts from Pillow (by hugovk). Fixed setup for Python 3
44   - (Martin Panter)
45   -- 2014-02-04 v0.30: now compatible with Python 3.x, thanks to Martin
46   - Panter who did most of the hard work.
47   -- 2013-07-24 v0.26: added methods to parse stream/storage timestamps,
48   - improved listdir to include storages, fixed parsing of direntry
49   - timestamps
50   -- 2013-05-27 v0.25: improved metadata extraction, properties parsing
51   - and exception handling, fixed `issue
52   - #12 <https://bitbucket.org/decalage/olefileio_pl/issue/12/error-when-converting-timestamps-in-ole>`__
53   -- 2013-05-07 v0.24: new features to extract metadata (get\_metadata
54   - method and OleMetadata class), improved getproperties to convert
55   - timestamps to Python datetime
56   -- 2012-10-09: published
57   - `python-oletools <http://www.decalage.info/python/oletools>`__, a
58   - package of analysis tools based on OleFileIO\_PL
59   -- 2012-09-11 v0.23: added support for file-like objects, fixed `issue
60   - #8 <https://bitbucket.org/decalage/olefileio_pl/issue/8/bug-with-file-object>`__
61   -- 2012-02-17 v0.22: fixed issues #7 (bug in getproperties) and #2
62   - (added close method)
63   -- 2011-10-20: code hosted on bitbucket to ease contributions and bug
64   - tracking
65   -- 2010-01-24 v0.21: fixed support for big-endian CPUs, such as PowerPC
66   - Macs.
67   -- 2009-12-11 v0.20: small bugfix in OleFileIO.open when filename is not
68   - plain str.
69   -- 2009-12-10 v0.19: fixed support for 64 bits platforms (thanks to Ben
70   - G. and Martijn for reporting the bug)
71   -- see changelog in source code for more info.
72   -
73   -Download/Install
74   -----------------
75   -
76   -If you have pip or setuptools installed (pip is included in Python
77   -2.7.9+), you may simply run **pip install olefile** or **easy\_install
78   -olefile** for the first installation.
79   -
80   -To update olefile, run **pip install -U olefile**.
81   -
82   -Otherwise, see https://bitbucket.org/decalage/olefileio\_pl/wiki/Install
83   -
84   -Features
85   ---------
86   -
87   -- Parse, read and write any OLE file such as Microsoft Office 97-2003
88   - legacy document formats (Word .doc, Excel .xls, PowerPoint .ppt,
89   - Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook
90   - messages, StickyNotes, Zeiss AxioVision ZVI files, Olympus FluoView
91   - OIB files, etc
92   -- List all the streams and storages contained in an OLE file
93   -- Open streams as files
94   -- Parse and read property streams, containing metadata of the file
95   -- Portable, pure Python module, no dependency
96   -
97   -olefile can be used as an independent package or with PIL/Pillow.
98   -
99   -olefile is mostly meant for developers. If you are looking for tools to
100   -analyze OLE files or to extract data (especially for security purposes
101   -such as malware analysis and forensics), then please also check my
102   -`python-oletools <http://www.decalage.info/python/oletools>`__, which
103   -are built upon olefile and provide a higher-level interface.
104   -
105   -History
106   --------
107   -
108   -olefile is based on the OleFileIO module from
109   -`PIL <http://www.pythonware.com/products/pil/index.htm>`__, the
110   -excellent Python Imaging Library, created and maintained by Fredrik
111   -Lundh. The olefile API is still compatible with PIL, but since 2005 I
112   -have improved the internal implementation significantly, with new
113   -features, bugfixes and a more robust design. From 2005 to 2014 the
114   -project was called OleFileIO\_PL, and in 2014 I changed its name to
115   -olefile to celebrate its 9 years and its new write features.
116   -
117   -As far as I know, olefile is the most complete and robust Python
118   -implementation to read MS OLE2 files, portable on several operating
119   -systems. (please tell me if you know other similar Python modules)
120   -
121   -Since 2014 olefile/OleFileIO\_PL has been integrated into
122   -`Pillow <http://python-imaging.github.io/>`__, the friendly fork of PIL.
123   -olefile will continue to be improved as a separate project, and new
124   -versions will be merged into Pillow regularly.
125   -
126   -Main improvements over the original version of OleFileIO in PIL:
127   -----------------------------------------------------------------
128   -
129   -- Compatible with Python 3.x and 2.6+
130   -- Many bug fixes
131   -- Support for files larger than 6.8MB
132   -- Support for 64 bits platforms and big-endian CPUs
133   -- Robust: many checks to detect malformed files
134   -- Runtime option to choose if malformed files should be parsed or raise
135   - exceptions
136   -- Improved API
137   -- Metadata extraction, stream/storage timestamps (e.g. for document
138   - forensics)
139   -- Can open file-like objects
140   -- Added setup.py and install.bat to ease installation
141   -- More convenient slash-based syntax for stream paths
142   -- Write features
143   -
144   -Documentation
145   --------------
146   -
147   -Please see the `online
148   -documentation <https://bitbucket.org/decalage/olefileio_pl/wiki>`__ for
149   -more information, especially the `OLE
150   -overview <https://bitbucket.org/decalage/olefileio_pl/wiki/OLE_Overview>`__
151   -and the `API
152   -page <https://bitbucket.org/decalage/olefileio_pl/wiki/API>`__ which
153   -describe how to use olefile in Python applications. A copy of the same
154   -documentation is also provided in the doc subfolder of the olefile
155   -package.
156   -
157   -Real-life examples
158   -------------------
159   -
160   -A real-life example: `using OleFileIO\_PL for malware analysis and
161   -forensics <http://blog.gregback.net/2011/03/using-remnux-for-forensic-puzzle-6/>`__.
162   -
163   -See also `this
164   -paper <https://computer-forensics.sans.org/community/papers/gcfa/grow-forensic-tools-taxonomy-python-libraries-helpful-forensic-analysis_6879>`__
165   -about python tools for forensics, which features olefile.
166   -
167   -License
168   --------
169   -
170   -olefile (formerly OleFileIO\_PL) is copyright (c) 2005-2016 Philippe
171   -Lagadec (http://www.decalage.info)
172   -
173   -All rights reserved.
174   -
175   -Redistribution and use in source and binary forms, with or without
176   -modification, are permitted provided that the following conditions are
177   -met:
178   -
179   -- Redistributions of source code must retain the above copyright
180   - notice, this list of conditions and the following disclaimer.
181   -- Redistributions in binary form must reproduce the above copyright
182   - notice, this list of conditions and the following disclaimer in the
183   - documentation and/or other materials provided with the distribution.
184   -
185   -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
186   -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
187   -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
188   -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
189   -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
190   -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
191   -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
192   -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
193   -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
194   -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
195   -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
196   -
197   ---------------
198   -
199   -olefile is based on source code from the OleFileIO module of the Python
200   -Imaging Library (PIL) published by Fredrik Lundh under the following
201   -license:
202   -
203   -The Python Imaging Library (PIL) is
204   -
205   -- Copyright (c) 1997-2005 by Secret Labs AB
206   -- Copyright (c) 1995-2005 by Fredrik Lundh
207   -
208   -By obtaining, using, and/or copying this software and/or its associated
209   -documentation, you agree that you have read, understood, and will comply
210   -with the following terms and conditions:
211   -
212   -Permission to use, copy, modify, and distribute this software and its
213   -associated documentation for any purpose and without fee is hereby
214   -granted, provided that the above copyright notice appears in all copies,
215   -and that both that copyright notice and this permission notice appear in
216   -supporting documentation, and that the name of Secret Labs AB or the
217   -author not be used in advertising or publicity pertaining to
218   -distribution of the software without specific, written prior permission.
219   -
220   -SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
221   -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
222   -FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
223   -ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
224   -RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
225   -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
226   -CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
oletools/thirdparty/olefile/__init__.py deleted
1   -#!/usr/local/bin/python
2   -# -*- coding: latin-1 -*-
3   -"""
4   -olefile (formerly OleFileIO_PL)
5   -
6   -Module to read/write Microsoft OLE2 files (also called Structured Storage or
7   -Microsoft Compound Document File Format), such as Microsoft Office 97-2003
8   -documents, Image Composer and FlashPix files, Outlook messages, ...
9   -This version is compatible with Python 2.6+ and 3.x
10   -
11   -Project website: http://www.decalage.info/olefile
12   -
13   -olefile is copyright (c) 2005-2015 Philippe Lagadec (http://www.decalage.info)
14   -
15   -olefile is based on the OleFileIO module from the PIL library v1.1.6
16   -See: http://www.pythonware.com/products/pil/index.htm
17   -
18   -The Python Imaging Library (PIL) is
19   - Copyright (c) 1997-2005 by Secret Labs AB
20   - Copyright (c) 1995-2005 by Fredrik Lundh
21   -
22   -See source code and LICENSE.txt for information on usage and redistribution.
23   -"""
24   -
25   -# first try to import olefile for Python 2.6+/3.x
26   -from .olefile import *
27   -# import metadata not covered by *:
28   -from .olefile import __version__, __author__, __date__
oletools/thirdparty/olefile/doc/API.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="how-to-use-olefile---api">How to use olefile - API</h1>
11   -<p>This page is part of the documentation for <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">olefile</a>. It explains how to use all its features to parse and write OLE files. For more information about OLE files, see <a href="OLE_Overview.html">OLE_Overview</a>.</p>
12   -<p>olefile can be used as an independent module or with PIL/Pillow. The main functions and methods are explained below.</p>
13   -<p>For more information, see also the file <strong>olefile.html</strong>, sample code at the end of the module itself, and docstrings within the code.</p>
14   -<h2 id="import-olefile">Import olefile</h2>
15   -<p>When the olefile package has been installed, it can be imported in Python applications with this statement:</p>
16   -<pre><code>import olefile</code></pre>
17   -<p>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:</p>
18   -<pre><code>import OleFileIO_PL</code></pre>
19   -<p>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/<strong>init</strong>.py. (new in v0.40)</p>
20   -<p>If you think olefile should stay compatible with Python 2.5 or older, please <a href="http://decalage.info/contact">contact me</a>.</p>
21   -<h2 id="test-if-a-file-is-an-ole-container">Test if a file is an OLE container</h2>
22   -<p>Use <strong>isOleFile</strong> 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).</p>
23   -<pre><code>assert olefile.isOleFile(&#39;myfile.doc&#39;)</code></pre>
24   -<p>The argument of isOleFile can be (new in v0.41):</p>
25   -<ul>
26   -<li>the path of the file to open on disk (bytes or unicode string smaller than 1536 bytes),</li>
27   -<li>or a bytes string containing the file in memory. (bytes string longer than 1535 bytes),</li>
28   -<li>or a file-like object (with read and seek methods).</li>
29   -</ul>
30   -<h2 id="open-an-ole-file-from-disk">Open an OLE file from disk</h2>
31   -<p>Create an <strong>OleFileIO</strong> object with the file path as parameter:</p>
32   -<pre><code>ole = olefile.OleFileIO(&#39;myfile.doc&#39;)</code></pre>
33   -<h2 id="open-an-ole-file-from-a-bytes-string">Open an OLE file from a bytes string</h2>
34   -<p>This is useful if the file is already stored in memory as a bytes string.</p>
35   -<pre><code>ole = olefile.OleFileIO(s)</code></pre>
36   -<p>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.</p>
37   -<p>(new in v0.41)</p>
38   -<h2 id="open-an-ole-file-from-a-file-like-object">Open an OLE file from a file-like object</h2>
39   -<p>This is useful if the file is not on disk but only available as a file-like object (with read, seek and tell methods).</p>
40   -<pre><code>ole = olefile.OleFileIO(f)</code></pre>
41   -<p>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:</p>
42   -<pre><code>data = f.read()
43   -ole = olefile.OleFileIO(data)</code></pre>
44   -<h2 id="how-to-handle-malformed-ole-files">How to handle malformed OLE files</h2>
45   -<p>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):</p>
46   -<pre><code>ole = olefile.OleFileIO(&#39;myfile.doc&#39;, raise_defects=olefile.DEFECT_INCORRECT)</code></pre>
47   -<p>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):</p>
48   -<pre><code>print(&#39;Non-fatal issues raised during parsing:&#39;)
49   -if ole.parsing_issues:
50   - for exctype, msg in ole.parsing_issues:
51   - print(&#39;- %s: %s&#39; % (exctype.__name__, msg))
52   -else:
53   - print(&#39;None&#39;)</code></pre>
54   -<h2 id="open-an-ole-file-in-write-mode">Open an OLE file in write mode</h2>
55   -<p>Before using the write features, the OLE file must be opened in read/write mode:</p>
56   -<pre><code>ole = olefile.OleFileIO(&#39;test.doc&#39;, write_mode=True)</code></pre>
57   -<p>(new in v0.40)</p>
58   -<p>The code for write features is new and it has not been thoroughly tested yet. See <a href="https://bitbucket.org/decalage/olefileio_pl/issue/6/improve-olefileio_pl-to-write-ole-files">issue #6</a> for the roadmap and the implementation status. If you encounter any issue, please send me your <a href="http://www.decalage.info/en/contact">feedback</a> or <a href="https://bitbucket.org/decalage/olefileio_pl/issues?status=new&amp;status=open">report issues</a>.</p>
59   -<h2 id="syntax-for-stream-and-storage-paths">Syntax for stream and storage paths</h2>
60   -<p>Two different syntaxes are allowed for methods that need or return the path of streams and storages:</p>
61   -<ol style="list-style-type: decimal">
62   -<li><p>Either a <strong>list of strings</strong> including all the storages from the root up to the stream/storage name. For example a stream called &quot;WordDocument&quot; at the root will have ['WordDocument'] as full path. A stream called &quot;ThisDocument&quot; located in the storage &quot;Macros/VBA&quot; 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.</p></li>
63   -<li><p>Or a <strong>single string with slashes</strong> 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)</p></li>
64   -</ol>
65   -<p>Both are case-insensitive.</p>
66   -<p>Switching between the two is easy:</p>
67   -<pre><code>slash_path = &#39;/&#39;.join(list_path)
68   -list_path = slash_path.split(&#39;/&#39;)</code></pre>
69   -<p><strong>Encoding</strong>:</p>
70   -<ul>
71   -<li>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.</li>
72   -<li><strong>On Python 2.x</strong>, all stream and storage paths are handled by olefile in bytes strings, using the <strong>UTF-8 encoding</strong> by default. If you need to use Unicode instead, add the option <strong>path_encoding=None</strong> 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.<br /></li>
73   -<li><strong>On Python 3.x</strong>, all stream and storage paths are handled by olefile in unicode strings, without encoding.</li>
74   -</ul>
75   -<h2 id="get-the-list-of-streams">Get the list of streams</h2>
76   -<p>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.</p>
77   -<pre><code>print(ole.listdir())</code></pre>
78   -<p>Sample result:</p>
79   -<pre><code>[[&#39;\x01CompObj&#39;], [&#39;\x05DocumentSummaryInformation&#39;], [&#39;\x05SummaryInformation&#39;]
80   -, [&#39;1Table&#39;], [&#39;Macros&#39;, &#39;PROJECT&#39;], [&#39;Macros&#39;, &#39;PROJECTwm&#39;], [&#39;Macros&#39;, &#39;VBA&#39;,
81   -&#39;Module1&#39;], [&#39;Macros&#39;, &#39;VBA&#39;, &#39;ThisDocument&#39;], [&#39;Macros&#39;, &#39;VBA&#39;, &#39;_VBA_PROJECT&#39;]
82   -, [&#39;Macros&#39;, &#39;VBA&#39;, &#39;dir&#39;], [&#39;ObjectPool&#39;], [&#39;WordDocument&#39;]]</code></pre>
83   -<p>As an option it is possible to choose if storages should also be listed, with or without streams (new in v0.26):</p>
84   -<pre><code>ole.listdir (streams=False, storages=True)</code></pre>
85   -<h2 id="test-if-known-streamsstorages-exist">Test if known streams/storages exist:</h2>
86   -<p>exists(path) checks if a given stream or storage exists in the OLE file (new in v0.16). The provided path is case-insensitive.</p>
87   -<pre><code>if ole.exists(&#39;worddocument&#39;):
88   - print(&quot;This is a Word document.&quot;)
89   - if ole.exists(&#39;macros/vba&#39;):
90   - print(&quot;This document seems to contain VBA macros.&quot;)</code></pre>
91   -<h2 id="read-data-from-a-stream">Read data from a stream</h2>
92   -<p>openstream(path) opens a stream as a file-like object. The provided path is case-insensitive.</p>
93   -<p>The following example extracts the &quot;Pictures&quot; stream from a PPT file:</p>
94   -<pre><code>pics = ole.openstream(&#39;Pictures&#39;)
95   -data = pics.read()</code></pre>
96   -<h2 id="get-information-about-a-streamstorage">Get information about a stream/storage</h2>
97   -<p>Several methods can provide the size, type and timestamps of a given stream/storage:</p>
98   -<p>get_size(path) returns the size of a stream in bytes (new in v0.16):</p>
99   -<pre><code>s = ole.get_size(&#39;WordDocument&#39;)</code></pre>
100   -<p>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).</p>
101   -<pre><code>t = ole.get_type(&#39;WordDocument&#39;)</code></pre>
102   -<p>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).</p>
103   -<pre><code>c = ole.get_ctime(&#39;WordDocument&#39;)
104   -m = ole.get_mtime(&#39;WordDocument&#39;)</code></pre>
105   -<p>The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute (new in v0.26):</p>
106   -<pre><code>c = ole.root.getctime()
107   -m = ole.root.getmtime()</code></pre>
108   -<p>Note: all these methods are case-insensitive.</p>
109   -<h2 id="overwriting-a-sector">Overwriting a sector</h2>
110   -<p>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)</p>
111   -<p>Here is an example:</p>
112   -<pre><code>ole.write_sect(0x17, b&#39;TEST&#39;)</code></pre>
113   -<p>Note: following the <a href="http://msdn.microsoft.com/en-us/library/dd942138.aspx">MS-CFB specifications</a>, sector 0 is actually the second sector of the file. You may use -1 as index to write the first sector.</p>
114   -<h2 id="overwriting-a-stream">Overwriting a stream</h2>
115   -<p>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).</p>
116   -<p>For example, you may change text in a MS Word document:</p>
117   -<pre><code>ole = olefile.OleFileIO(&#39;test.doc&#39;, write_mode=True)
118   -data = ole.openstream(&#39;WordDocument&#39;).read()
119   -data = data.replace(b&#39;foo&#39;, b&#39;bar&#39;)
120   -ole.write_stream(&#39;WordDocument&#39;, data)
121   -ole.close()</code></pre>
122   -<p>(new in v0.40)</p>
123   -<h2 id="extract-metadata">Extract metadata</h2>
124   -<p>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).</p>
125   -<pre><code>meta = ole.get_metadata()
126   -print(&#39;Author:&#39;, meta.author)
127   -print(&#39;Title:&#39;, meta.title)
128   -print(&#39;Creation date:&#39;, meta.create_time)
129   -# print all metadata:
130   -meta.dump()</code></pre>
131   -<p>Available attributes include:</p>
132   -<pre><code>codepage, title, subject, author, keywords, comments, template,
133   -last_saved_by, revision_number, total_edit_time, last_printed, create_time,
134   -last_saved_time, num_pages, num_words, num_chars, thumbnail,
135   -creating_application, security, codepage_doc, category, presentation_target,
136   -bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
137   -scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
138   -chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
139   -version, dig_sig, content_type, content_status, language, doc_version</code></pre>
140   -<p>See the source code of the OleMetadata class for more information.</p>
141   -<h2 id="parse-a-property-stream">Parse a property stream</h2>
142   -<p>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>
143   -<pre><code>p = ole.getproperties(&#39;specialprops&#39;)</code></pre>
144   -<p>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>
145   -<pre><code>p = ole.getproperties(&#39;specialprops&#39;, convert_time=True, no_conversion=[10])</code></pre>
146   -<h2 id="close-the-ole-file">Close the OLE file</h2>
147   -<p>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)</p>
148   -<pre><code>ole.close()</code></pre>
149   -<h2 id="use-olefile-as-a-script-for-testingdebugging">Use olefile as a script for testing/debugging</h2>
150   -<p>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:</p>
151   -<pre><code>olefile.py myfile.doc</code></pre>
152   -<p>You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information.</p>
153   -<hr />
154   -<h2 id="olefile-documentation">olefile documentation</h2>
155   -<ul>
156   -<li><a href="Home.html">Home</a></li>
157   -<li><a href="License.html">License</a></li>
158   -<li><a href="Install.html">Install</a></li>
159   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
160   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
161   -<li><a href="API.html">API</a> and Usage</li>
162   -</ul>
163   -</body>
164   -</html>
oletools/thirdparty/olefile/doc/API.md deleted
1   -How to use olefile - API
2   -========================
3   -
4   -This page is part of the documentation for [olefile](https://bitbucket.org/decalage/olefileio_pl/wiki). It explains
5   -how to use all its features to parse and write OLE files. For more information about OLE files, see [[OLE_Overview]].
6   -
7   -olefile can be used as an independent module or with PIL/Pillow. The main functions and methods are explained below.
8   -
9   -For more information, see also the file **olefile.html**, sample code at the end of the module itself, and docstrings within the code.
10   -
11   -
12   -
13   -Import olefile
14   ---------------
15   -
16   -When the olefile package has been installed, it can be imported in Python applications with this statement:
17   -
18   - :::python
19   - import olefile
20   -
21   -Before v0.40, olefile was named OleFileIO_PL. To maintain backward compatibility with older applications and samples, a
22   -simple script is also installed so that the following statement imports olefile as OleFileIO_PL:
23   -
24   - :::python
25   - import OleFileIO_PL
26   -
27   -As of version 0.30, the code has been changed to be compatible with Python 3.x. As a consequence, compatibility with
28   -Python 2.5 or older is not provided anymore. However, a copy of OleFileIO_PL v0.26 (with some backported enhancements)
29   -is available as olefile2.py. When importing the olefile package, it falls back automatically to olefile2 if running on
30   -Python 2.5 or older. This is implemented in olefile/__init__.py. (new in v0.40)
31   -
32   -If you think olefile should stay compatible with Python 2.5 or older, please [contact me](http://decalage.info/contact).
33   -
34   -
35   -## Test if a file is an OLE container
36   -
37   -Use **isOleFile** to check if the first bytes of the file contain the Magic for OLE files, before opening it. isOleFile
38   -returns True if it is an OLE file, False otherwise (new in v0.16).
39   -
40   - :::python
41   - assert olefile.isOleFile('myfile.doc')
42   -
43   -The argument of isOleFile can be (new in v0.41):
44   -
45   -- the path of the file to open on disk (bytes or unicode string smaller than 1536 bytes),
46   -- or a bytes string containing the file in memory. (bytes string longer than 1535 bytes),
47   -- or a file-like object (with read and seek methods).
48   -
49   -## Open an OLE file from disk
50   -
51   -Create an **OleFileIO** object with the file path as parameter:
52   -
53   - :::python
54   - ole = olefile.OleFileIO('myfile.doc')
55   -
56   -## Open an OLE file from a bytes string
57   -
58   -This is useful if the file is already stored in memory as a bytes string.
59   -
60   - :::python
61   - ole = olefile.OleFileIO(s)
62   -
63   -Note: olefile checks the size of the string provided as argument to determine if it is a file path or the content of an
64   -OLE file. An OLE file cannot be smaller than 1536 bytes. If the string is larger than 1535 bytes, then it is expected to
65   -contain an OLE file, otherwise it is expected to be a file path.
66   -
67   -(new in v0.41)
68   -
69   -
70   -## Open an OLE file from a file-like object
71   -
72   -This is useful if the file is not on disk but only available as a file-like object (with read, seek and tell methods).
73   -
74   - :::python
75   - ole = olefile.OleFileIO(f)
76   -
77   -If the file-like object does not have seek or tell methods, the easiest solution is to read the file entirely in
78   -a bytes string before parsing:
79   -
80   - :::python
81   - data = f.read()
82   - ole = olefile.OleFileIO(data)
83   -
84   -
85   -## How to handle malformed OLE files
86   -
87   -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):
88   -
89   - :::python
90   - ole = olefile.OleFileIO('myfile.doc', raise_defects=olefile.DEFECT_INCORRECT)
91   -
92   -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):
93   -
94   - :::python
95   - print('Non-fatal issues raised during parsing:')
96   - if ole.parsing_issues:
97   - for exctype, msg in ole.parsing_issues:
98   - print('- %s: %s' % (exctype.__name__, msg))
99   - else:
100   - print('None')
101   -
102   -
103   -## Open an OLE file in write mode
104   -
105   -Before using the write features, the OLE file must be opened in read/write mode:
106   -
107   - :::python
108   - ole = olefile.OleFileIO('test.doc', write_mode=True)
109   -
110   -(new in v0.40)
111   -
112   -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).
113   -
114   -
115   -## Syntax for stream and storage paths
116   -
117   -Two different syntaxes are allowed for methods that need or return the path of streams and storages:
118   -
119   -1) Either a **list of strings** including all the storages from the root up to the stream/storage name. For example a
120   -stream called "WordDocument" at the root will have ['WordDocument'] as full path. A stream called "ThisDocument"
121   -located in the storage "Macros/VBA" will be ['Macros', 'VBA', 'ThisDocument']. This is the original syntax from PIL.
122   -While hard to read and not very convenient, this syntax works in all cases.
123   -
124   -2) Or a **single string with slashes** to separate storage and stream names (similar to the Unix path syntax).
125   -The previous examples would be 'WordDocument' and 'Macros/VBA/ThisDocument'. This syntax is easier, but may fail if a
126   -stream or storage name contains a slash (which is normally not allowed, according to the Microsoft specifications [MS-CFB]). (new in v0.15)
127   -
128   -Both are case-insensitive.
129   -
130   -Switching between the two is easy:
131   -
132   - :::python
133   - slash_path = '/'.join(list_path)
134   - list_path = slash_path.split('/')
135   -
136   -**Encoding**:
137   -
138   -- Stream and Storage names are stored in Unicode format in OLE files, which means they may contain special characters
139   - (e.g. Greek, Cyrillic, Japanese, etc) that applications must support to avoid exceptions.
140   -- **On Python 2.x**, all stream and storage paths are handled by olefile in bytes strings, using the **UTF-8 encoding**
141   - by default. If you need to use Unicode instead, add the option **path_encoding=None** when creating the OleFileIO
142   - object. This is new in v0.42. Olefile was using the Latin-1 encoding until v0.41, therefore special characters were
143   - not supported.
144   -- **On Python 3.x**, all stream and storage paths are handled by olefile in unicode strings, without encoding.
145   -
146   -## Get the list of streams
147   -
148   -listdir() returns a list of all the streams contained in the OLE file, including those stored in storages.
149   -Each stream is listed itself as a list, as described above.
150   -
151   - :::python
152   - print(ole.listdir())
153   -
154   -Sample result:
155   -
156   - :::python
157   - [['\x01CompObj'], ['\x05DocumentSummaryInformation'], ['\x05SummaryInformation']
158   - , ['1Table'], ['Macros', 'PROJECT'], ['Macros', 'PROJECTwm'], ['Macros', 'VBA',
159   - 'Module1'], ['Macros', 'VBA', 'ThisDocument'], ['Macros', 'VBA', '_VBA_PROJECT']
160   - , ['Macros', 'VBA', 'dir'], ['ObjectPool'], ['WordDocument']]
161   -
162   -As an option it is possible to choose if storages should also be listed, with or without streams (new in v0.26):
163   -
164   - :::python
165   - ole.listdir (streams=False, storages=True)
166   -
167   -
168   -## Test if known streams/storages exist:
169   -
170   -exists(path) checks if a given stream or storage exists in the OLE file (new in v0.16). The provided path is case-insensitive.
171   -
172   - :::python
173   - if ole.exists('worddocument'):
174   - print("This is a Word document.")
175   - if ole.exists('macros/vba'):
176   - print("This document seems to contain VBA macros.")
177   -
178   -
179   -## Read data from a stream
180   -
181   -openstream(path) opens a stream as a file-like object. The provided path is case-insensitive.
182   -
183   -The following example extracts the "Pictures" stream from a PPT file:
184   -
185   - :::python
186   - pics = ole.openstream('Pictures')
187   - data = pics.read()
188   -
189   -
190   -## Get information about a stream/storage
191   -
192   -Several methods can provide the size, type and timestamps of a given stream/storage:
193   -
194   -get_size(path) returns the size of a stream in bytes (new in v0.16):
195   -
196   - :::python
197   - s = ole.get_size('WordDocument')
198   -
199   -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).
200   -
201   - :::python
202   - t = ole.get_type('WordDocument')
203   -
204   -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).
205   -
206   - :::python
207   - c = ole.get_ctime('WordDocument')
208   - m = ole.get_mtime('WordDocument')
209   -
210   -The root storage is a special case: You can get its creation and modification timestamps using the OleFileIO.root attribute (new in v0.26):
211   -
212   - :::python
213   - c = ole.root.getctime()
214   - m = ole.root.getmtime()
215   -
216   -Note: all these methods are case-insensitive.
217   -
218   -## Overwriting a sector
219   -
220   -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)
221   -
222   -Here is an example:
223   -
224   - :::python
225   - ole.write_sect(0x17, b'TEST')
226   -
227   -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.
228   -
229   -
230   -## Overwriting a stream
231   -
232   -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).
233   -
234   -For example, you may change text in a MS Word document:
235   -
236   - :::python
237   - ole = olefile.OleFileIO('test.doc', write_mode=True)
238   - data = ole.openstream('WordDocument').read()
239   - data = data.replace(b'foo', b'bar')
240   - ole.write_stream('WordDocument', data)
241   - ole.close()
242   -
243   -(new in v0.40)
244   -
245   -
246   -
247   -## Extract metadata
248   -
249   -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).
250   -
251   - :::python
252   - meta = ole.get_metadata()
253   - print('Author:', meta.author)
254   - print('Title:', meta.title)
255   - print('Creation date:', meta.create_time)
256   - # print all metadata:
257   - meta.dump()
258   -
259   -Available attributes include:
260   -
261   - :::text
262   - codepage, title, subject, author, keywords, comments, template,
263   - last_saved_by, revision_number, total_edit_time, last_printed, create_time,
264   - last_saved_time, num_pages, num_words, num_chars, thumbnail,
265   - creating_application, security, codepage_doc, category, presentation_target,
266   - bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
267   - scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
268   - chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
269   - version, dig_sig, content_type, content_status, language, doc_version
270   -
271   -See the source code of the OleMetadata class for more information.
272   -
273   -
274   -## Parse a property stream
275   -
276   -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.
277   -
278   - :::python
279   - p = ole.getproperties('specialprops')
280   -
281   -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):
282   -
283   - :::python
284   - p = ole.getproperties('specialprops', convert_time=True, no_conversion=[10])
285   -
286   -
287   -## Close the OLE file
288   -
289   -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)
290   -
291   - :::python
292   - ole.close()
293   -
294   -## Use olefile as a script for testing/debugging
295   -
296   -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:
297   -
298   - :::text
299   - olefile.py myfile.doc
300   -
301   -You can use the option -c to check that all streams can be read fully, and -d to generate very verbose debugging information.
302   -
303   ---------------------------------------------------------------------------
304   -
305   -olefile documentation
306   ----------------------
307   -
308   -- [[Home]]
309   -- [[License]]
310   -- [[Install]]
311   -- [[Contribute]], Suggest Improvements or Report Issues
312   -- [[OLE_Overview]]
313   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/Contribute.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="how-to-suggest-improvements-report-issues-or-contribute">How to Suggest Improvements, Report Issues or Contribute</h1>
11   -<p>This is a personal open-source project, developed on my spare time. Any contribution, suggestion, feedback or bug report is welcome.</p>
12   -<p>To <strong>suggest improvements, report a bug or any issue</strong>, please use the <a href="https://bitbucket.org/decalage/olefileio_pl/issues?status=new&amp;status=open">issue reporting page</a>, providing all the information and files to reproduce the problem.</p>
13   -<p>If possible please join the debugging output of olefile. For this, launch the following command :</p>
14   -<pre><code> olefile.py -d -c file &gt;debug.txt </code></pre>
15   -<p>You may also <a href="http://decalage.info/contact">contact the author</a> directly to <strong>provide feedback</strong>.</p>
16   -<p>The code is available in <a href="https://bitbucket.org/decalage/olefileio_pl">a Mercurial repository on Bitbucket</a>. You may use it to <strong>submit enhancements</strong> using forks and pull requests.</p>
17   -<hr />
18   -<h2 id="olefile-documentation">olefile documentation</h2>
19   -<ul>
20   -<li><a href="Home.html">Home</a></li>
21   -<li><a href="License.html">License</a></li>
22   -<li><a href="Install.html">Install</a></li>
23   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
24   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
25   -<li><a href="API.html">API</a> and Usage</li>
26   -</ul>
27   -</body>
28   -</html>
oletools/thirdparty/olefile/doc/Contribute.md deleted
1   -How to Suggest Improvements, Report Issues or Contribute
2   -========================================================
3   -
4   -This is a personal open-source project, developed on my spare time. Any contribution, suggestion, feedback or bug report is welcome.
5   -
6   -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.
7   -
8   -If possible please join the debugging output of olefile. For this, launch the following command :
9   -
10   - :::text
11   - olefile.py -d -c file >debug.txt
12   -
13   -
14   -You may also [contact the author](http://decalage.info/contact) directly to **provide feedback**.
15   -
16   -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.
17   -
18   ---------------------------------------------------------------------------
19   -
20   -olefile documentation
21   ----------------------
22   -
23   -- [[Home]]
24   -- [[License]]
25   -- [[Install]]
26   -- [[Contribute]], Suggest Improvements or Report Issues
27   -- [[OLE_Overview]]
28   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/Home.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="olefile-v0.42-documentation">olefile v0.42 documentation</h1>
11   -<p>This is the home page of the documentation for olefile. The latest version can be found <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">online</a>, otherwise a copy is provided in the doc subfolder of the package.</p>
12   -<p><a href="http://www.decalage.info/olefile">olefile</a> is a Python package to parse, read and write <a href="http://en.wikipedia.org/wiki/Compound_File_Binary_Format">Microsoft OLE2 files</a> (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.</p>
13   -<p><strong>Quick links:</strong> <a href="http://www.decalage.info/olefile">Home page</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/wiki/Install">Download/Install</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">Documentation</a> - <a href="https://bitbucket.org/decalage/olefileio_pl/issues?status=new&amp;status=open">Report Issues/Suggestions/Questions</a> - <a href="http://decalage.info/contact">Contact the author</a> - <a href="https://bitbucket.org/decalage/olefileio_pl">Repository</a> - <a href="https://twitter.com/decalage2">Updates on Twitter</a></p>
14   -<h2 id="documentation-pages">Documentation pages</h2>
15   -<ul>
16   -<li><a href="License.html">License</a></li>
17   -<li><a href="Install.html">Install</a></li>
18   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
19   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
20   -<li><a href="API.html">API</a> and Usage</li>
21   -</ul>
22   -<h2 id="features">Features</h2>
23   -<ul>
24   -<li>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</li>
25   -<li>List all the streams and storages contained in an OLE file</li>
26   -<li>Open streams as files</li>
27   -<li>Parse and read property streams, containing metadata of the file</li>
28   -<li>Portable, pure Python module, no dependency</li>
29   -</ul>
30   -<p>olefile can be used as an independent module or with PIL/Pillow.</p>
31   -<p>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 <a href="http://www.decalage.info/python/oletools">python-oletools</a>, which are built upon olefile and provide a higher-level interface.</p>
32   -<h2 id="history">History</h2>
33   -<p>olefile is based on the OleFileIO module from <a href="http://www.pythonware.com/products/pil/index.htm">PIL</a>, 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.</p>
34   -<p>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)</p>
35   -<p>Since 2014 olefile/OleFileIO_PL has been integrated into <a href="http://python-imaging.github.io/">Pillow</a>, the friendly fork of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly.</p>
36   -<h2 id="main-improvements-over-the-original-version-of-olefileio-in-pil">Main improvements over the original version of OleFileIO in PIL:</h2>
37   -<ul>
38   -<li>Compatible with Python 3.x and 2.6+</li>
39   -<li>Many bug fixes</li>
40   -<li>Support for files larger than 6.8MB</li>
41   -<li>Support for 64 bits platforms and big-endian CPUs</li>
42   -<li>Robust: many checks to detect malformed files</li>
43   -<li>Runtime option to choose if malformed files should be parsed or raise exceptions</li>
44   -<li>Improved API</li>
45   -<li>Metadata extraction, stream/storage timestamps (e.g. for document forensics)</li>
46   -<li>Can open file-like objects</li>
47   -<li>Added setup.py and install.bat to ease installation</li>
48   -<li>More convenient slash-based syntax for stream paths</li>
49   -<li>Write features</li>
50   -</ul>
51   -<hr />
52   -<h2 id="olefile-documentation">olefile documentation</h2>
53   -<ul>
54   -<li><a href="Home.html">Home</a></li>
55   -<li><a href="License.html">License</a></li>
56   -<li><a href="Install.html">Install</a></li>
57   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
58   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
59   -<li><a href="API.html">API</a> and Usage</li>
60   -</ul>
61   -</body>
62   -</html>
oletools/thirdparty/olefile/doc/Home.md deleted
1   -olefile v0.42 documentation
2   -===========================
3   -
4   -This is the home page of the documentation for olefile. The latest version can be found
5   -[online](https://bitbucket.org/decalage/olefileio_pl/wiki), otherwise a copy is provided in the doc subfolder of the package.
6   -
7   -[olefile](http://www.decalage.info/olefile) is a Python package to parse, read and write
8   -[Microsoft OLE2 files](http://en.wikipedia.org/wiki/Compound_File_Binary_Format)
9   -(also called Structured Storage, Compound File Binary Format or Compound Document File Format), such as Microsoft
10   -Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file
11   -formats, McAfee antivirus quarantine files, etc.
12   -
13   -
14   -**Quick links:**
15   -[Home page](http://www.decalage.info/olefile) -
16   -[Download/Install](https://bitbucket.org/decalage/olefileio_pl/wiki/Install) -
17   -[Documentation](https://bitbucket.org/decalage/olefileio_pl/wiki) -
18   -[Report Issues/Suggestions/Questions](https://bitbucket.org/decalage/olefileio_pl/issues?status=new&status=open) -
19   -[Contact the author](http://decalage.info/contact) -
20   -[Repository](https://bitbucket.org/decalage/olefileio_pl) -
21   -[Updates on Twitter](https://twitter.com/decalage2)
22   -
23   -Documentation pages
24   --------------------
25   -
26   -- [[License]]
27   -- [[Install]]
28   -- [[Contribute]], Suggest Improvements or Report Issues
29   -- [[OLE_Overview]]
30   -- [[API]] and Usage
31   -
32   -
33   -Features
34   ---------
35   -
36   -- Parse, read and write any OLE file such as Microsoft Office 97-2003 legacy document formats (Word .doc, Excel .xls,
37   - PowerPoint .ppt, Visio .vsd, Project .mpp), Image Composer and FlashPix files, Outlook messages, StickyNotes, Zeiss
38   - AxioVision ZVI files, Olympus FluoView OIB files, etc
39   -- List all the streams and storages contained in an OLE file
40   -- Open streams as files
41   -- Parse and read property streams, containing metadata of the file
42   -- Portable, pure Python module, no dependency
43   -
44   -olefile can be used as an independent module or with PIL/Pillow.
45   -
46   -olefile is mostly meant for developers. If you are looking for tools to analyze OLE files or to extract data
47   -(especially for security purposes such as malware analysis and forensics), then please also check my
48   -[python-oletools](http://www.decalage.info/python/oletools), which are built upon olefile and provide a higher-level
49   -interface.
50   -
51   -
52   -History
53   --------
54   -
55   -olefile is based on the OleFileIO module from [PIL](http://www.pythonware.com/products/pil/index.htm), the excellent
56   -Python Imaging Library, created and maintained by Fredrik Lundh. The olefile API is still compatible with PIL, but
57   -since 2005 I have improved the internal implementation significantly, with new features, bugfixes and a more robust
58   -design. From 2005 to 2014 the project was called OleFileIO_PL, and in 2014 I changed its name to olefile to celebrate
59   -its 9 years and its new write features.
60   -
61   -As far as I know, this module is the most complete and robust Python implementation to read MS OLE2 files, portable on
62   -several operating systems. (please tell me if you know other similar Python modules)
63   -
64   -Since 2014 olefile/OleFileIO_PL has been integrated into [Pillow](http://python-imaging.github.io/), the friendly fork
65   -of PIL. olefile will continue to be improved as a separate project, and new versions will be merged into Pillow regularly.
66   -
67   -Main improvements over the original version of OleFileIO in PIL:
68   -----------------------------------------------------------------
69   -
70   -- Compatible with Python 3.x and 2.6+
71   -- Many bug fixes
72   -- Support for files larger than 6.8MB
73   -- Support for 64 bits platforms and big-endian CPUs
74   -- Robust: many checks to detect malformed files
75   -- Runtime option to choose if malformed files should be parsed or raise exceptions
76   -- Improved API
77   -- Metadata extraction, stream/storage timestamps (e.g. for document forensics)
78   -- Can open file-like objects
79   -- Added setup.py and install.bat to ease installation
80   -- More convenient slash-based syntax for stream paths
81   -- Write features
82   -
83   -
84   ---------------------------------------------------------------------------
85   -
86   -olefile documentation
87   ----------------------
88   -
89   -- [[Home]]
90   -- [[License]]
91   -- [[Install]]
92   -- [[Contribute]], Suggest Improvements or Report Issues
93   -- [[OLE_Overview]]
94   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/Install.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="how-to-download-and-install-olefile">How to Download and Install olefile</h1>
11   -<h2 id="pre-requisites">Pre-requisites</h2>
12   -<p>olefile requires Python 2.6, 2.7 or 3.x.</p>
13   -<p>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.</p>
14   -<h2 id="download-and-install">Download and Install</h2>
15   -<p>To use olefile with other Python applications or your own scripts, the simplest solution is to run <strong>pip install olefile</strong> or <strong>easy_install olefile</strong>, to download and install the package in one go. Pip is part of the standard Python distribution since v2.7.9.</p>
16   -<p>To update olefile if a previous version is already installed, run <strong>pip install -U olefile</strong>.</p>
17   -<p>Otherwise you may download/extract the <a href="https://bitbucket.org/decalage/olefileio_pl/downloads">zip archive</a> in a temporary directory and run <strong>python setup.py install</strong>.</p>
18   -<p>On Windows you may simply double-click on <strong>install.bat</strong>.</p>
19   -<hr />
20   -<h2 id="olefile-documentation">olefile documentation</h2>
21   -<ul>
22   -<li><a href="Home.html">Home</a></li>
23   -<li><a href="License.html">License</a></li>
24   -<li><a href="Install.html">Install</a></li>
25   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
26   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
27   -<li><a href="API.html">API</a> and Usage</li>
28   -</ul>
29   -</body>
30   -</html>
oletools/thirdparty/olefile/doc/Install.md deleted
1   -How to Download and Install olefile
2   -===================================
3   -
4   -Pre-requisites
5   ---------------
6   -
7   -olefile requires Python 2.6, 2.7 or 3.x.
8   -
9   -For Python 2.5 and older, olefile falls back to an older version (based on OleFileIO_PL 0.26) which might not contain
10   -all the enhancements implemented in olefile.
11   -
12   -
13   -Download and Install
14   ---------------------
15   -
16   -To use olefile with other Python applications or your own scripts, the simplest solution is to run **pip install olefile**
17   -or **easy_install olefile**, to download and install the package in one go. Pip is part of the standard Python
18   -distribution since v2.7.9.
19   -
20   -To update olefile if a previous version is already installed, run **pip install -U olefile**.
21   -
22   -Otherwise you may download/extract the [zip archive](https://bitbucket.org/decalage/olefileio_pl/downloads) in a
23   -temporary directory and run **python setup.py install**.
24   -
25   -On Windows you may simply double-click on **install.bat**.
26   -
27   ---------------------------------------------------------------------------
28   -
29   -olefile documentation
30   ----------------------
31   -
32   -- [[Home]]
33   -- [[License]]
34   -- [[Install]]
35   -- [[Contribute]], Suggest Improvements or Report Issues
36   -- [[OLE_Overview]]
37   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/License.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="license-for-olefile">License for olefile</h1>
11   -<p>olefile (formerly OleFileIO_PL) is copyright (c) 2005-2015 Philippe Lagadec (<a href="http://www.decalage.info">http://www.decalage.info</a>)</p>
12   -<p>All rights reserved.</p>
13   -<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>
14   -<ul>
15   -<li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li>
16   -<li>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.</li>
17   -</ul>
18   -<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; 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.</p>
19   -<hr />
20   -<p>olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license:</p>
21   -<p>The Python Imaging Library (PIL) is</p>
22   -<ul>
23   -<li>Copyright (c) 1997-2005 by Secret Labs AB</li>
24   -<li>Copyright (c) 1995-2005 by Fredrik Lundh</li>
25   -</ul>
26   -<p>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:</p>
27   -<p>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.</p>
28   -<p>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.</p>
29   -<hr />
30   -<h2 id="olefile-documentation">olefile documentation</h2>
31   -<ul>
32   -<li><a href="Home.html">Home</a></li>
33   -<li><a href="License.html">License</a></li>
34   -<li><a href="Install.html">Install</a></li>
35   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
36   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
37   -<li><a href="API.html">API</a> and Usage</li>
38   -</ul>
39   -</body>
40   -</html>
oletools/thirdparty/olefile/doc/License.md deleted
1   -License for olefile
2   -===================
3   -
4   -olefile (formerly OleFileIO_PL) is copyright (c) 2005-2015 Philippe Lagadec ([http://www.decalage.info](http://www.decalage.info))
5   -
6   -All rights reserved.
7   -
8   -Redistribution and use in source and binary forms, with or without modification,
9   -are permitted provided that the following conditions are met:
10   -
11   - * Redistributions of source code must retain the above copyright notice, this
12   - list of conditions and the following disclaimer.
13   - * Redistributions in binary form must reproduce the above copyright notice,
14   - this list of conditions and the following disclaimer in the documentation
15   - and/or other materials provided with the distribution.
16   -
17   -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18   -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19   -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20   -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21   -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22   -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23   -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24   -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25   -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26   -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27   -
28   -
29   -----------
30   -
31   -olefile is based on source code from the OleFileIO module of the Python Imaging Library (PIL) published by Fredrik Lundh under the following license:
32   -
33   -The Python Imaging Library (PIL) is
34   -
35   -- Copyright (c) 1997-2005 by Secret Labs AB
36   -- Copyright (c) 1995-2005 by Fredrik Lundh
37   -
38   -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:
39   -
40   -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.
41   -
42   -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.
43   -
44   ---------------------------------------------------------------------------
45   -
46   -olefile documentation
47   ----------------------
48   -
49   -- [[Home]]
50   -- [[License]]
51   -- [[Install]]
52   -- [[Contribute]], Suggest Improvements or Report Issues
53   -- [[OLE_Overview]]
54   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/OLE_Overview.html deleted
1   -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2   -<html xmlns="http://www.w3.org/1999/xhtml">
3   -<head>
4   - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5   - <meta http-equiv="Content-Style-Type" content="text/css" />
6   - <meta name="generator" content="pandoc" />
7   - <title></title>
8   -</head>
9   -<body>
10   -<h1 id="about-the-structure-of-ole-files">About the structure of OLE files</h1>
11   -<p>This page is part of the documentation for <a href="https://bitbucket.org/decalage/olefileio_pl/wiki">olefile</a>. It provides a brief overview of the structure of <a href="http://en.wikipedia.org/wiki/Compound_File_Binary_Format">Microsoft OLE2 files (also called Structured Storage, Compound File Binary Format or Compound Document File Format)</a>, such as Microsoft Office 97-2003 documents, Image Composer and FlashPix files, Outlook messages, StickyNotes, several Microscopy file formats, McAfee antivirus quarantine files, etc.</p>
12   -<p>An OLE file can be seen as a mini file system or a Zip archive: It contains <strong>streams</strong> 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 &quot;WordDocument&quot;.</p>
13   -<p>An OLE file can also contain <strong>storages</strong>. A storage is a folder that contains streams or other storages. For example, a MS Word document with VBA macros has a storage called &quot;Macros&quot;.</p>
14   -<p>Special streams can contain <strong>properties</strong>. 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'.</p>
15   -<p>For example, a typical MS Word document may look like this:</p>
16   -<div class="figure">
17   -<img src="OLE_VBA_sample.png" /><p class="caption"></p>
18   -</div>
19   -<p>Go to the <a href="API.html">API</a> page to see how to use all olefile features to parse OLE files.</p>
20   -<hr />
21   -<h2 id="olefile-documentation">olefile documentation</h2>
22   -<ul>
23   -<li><a href="Home.html">Home</a></li>
24   -<li><a href="License.html">License</a></li>
25   -<li><a href="Install.html">Install</a></li>
26   -<li><a href="Contribute.html">Contribute</a>, Suggest Improvements or Report Issues</li>
27   -<li><a href="OLE_Overview.html">OLE_Overview</a></li>
28   -<li><a href="API.html">API</a> and Usage</li>
29   -</ul>
30   -</body>
31   -</html>
oletools/thirdparty/olefile/doc/OLE_Overview.md deleted
1   -About the structure of OLE files
2   -================================
3   -
4   -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.
5   -
6   -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".
7   -
8   -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".
9   -
10   -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'.
11   -
12   -For example, a typical MS Word document may look like this:
13   -
14   -![](OLE_VBA_sample.png)
15   -
16   -Go to the [[API]] page to see how to use all olefile features to parse OLE files.
17   -
18   -
19   ---------------------------------------------------------------------------
20   -
21   -olefile documentation
22   ----------------------
23   -
24   -- [[Home]]
25   -- [[License]]
26   -- [[Install]]
27   -- [[Contribute]], Suggest Improvements or Report Issues
28   -- [[OLE_Overview]]
29   -- [[API]] and Usage
oletools/thirdparty/olefile/doc/OLE_VBA_sample.png deleted

3.48 KB

oletools/thirdparty/olefile/olefile.html deleted
No preview for this file type
oletools/thirdparty/olefile/olefile.py deleted
1   -"""
2   -olefile (formerly OleFileIO_PL)
3   -
4   -Module to read/write Microsoft OLE2 files (also called Structured Storage or
5   -Microsoft Compound Document File Format), such as Microsoft Office 97-2003
6   -documents, Image Composer and FlashPix files, Outlook messages, ...
7   -This version is compatible with Python 2.6+ and 3.x
8   -
9   -Project website: https://www.decalage.info/olefile
10   -
11   -olefile is copyright (c) 2005-2017 Philippe Lagadec
12   -(https://www.decalage.info)
13   -
14   -olefile is based on the OleFileIO module from the PIL library v1.1.7
15   -See: http://www.pythonware.com/products/pil/index.htm
16   -and http://svn.effbot.org/public/tags/pil-1.1.7/PIL/OleFileIO.py
17   -
18   -The Python Imaging Library (PIL) is
19   -Copyright (c) 1997-2009 by Secret Labs AB
20   -Copyright (c) 1995-2009 by Fredrik Lundh
21   -
22   -See source code and LICENSE.txt for information on usage and redistribution.
23   -"""
24   -
25   -# Since OleFileIO_PL v0.30, only Python 2.6+ and 3.x is supported
26   -# This import enables print() as a function rather than a keyword
27   -# (main requirement to be compatible with Python 3.x)
28   -# The comment on the line below should be printed on Python 2.5 or older:
29   -from __future__ import print_function # This version of olefile requires Python 2.6+ or 3.x.
30   -
31   -
32   -#--- LICENSE ------------------------------------------------------------------
33   -
34   -# olefile (formerly OleFileIO_PL) is copyright (c) 2005-2017 Philippe Lagadec
35   -# (https://www.decalage.info)
36   -#
37   -# All rights reserved.
38   -#
39   -# Redistribution and use in source and binary forms, with or without modification,
40   -# are permitted provided that the following conditions are met:
41   -#
42   -# * Redistributions of source code must retain the above copyright notice, this
43   -# list of conditions and the following disclaimer.
44   -# * Redistributions in binary form must reproduce the above copyright notice,
45   -# this list of conditions and the following disclaimer in the documentation
46   -# and/or other materials provided with the distribution.
47   -#
48   -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
49   -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
50   -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
51   -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
52   -# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53   -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
54   -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
55   -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56   -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57   -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58   -
59   -# ----------
60   -# PIL License:
61   -#
62   -# olefile is based on source code from the OleFileIO module of the Python
63   -# Imaging Library (PIL) published by Fredrik Lundh under the following license:
64   -
65   -# The Python Imaging Library (PIL) is
66   -# Copyright (c) 1997-2009 by Secret Labs AB
67   -# Copyright (c) 1995-2009 by Fredrik Lundh
68   -#
69   -# By obtaining, using, and/or copying this software and/or its associated
70   -# documentation, you agree that you have read, understood, and will comply with
71   -# the following terms and conditions:
72   -#
73   -# Permission to use, copy, modify, and distribute this software and its
74   -# associated documentation for any purpose and without fee is hereby granted,
75   -# provided that the above copyright notice appears in all copies, and that both
76   -# that copyright notice and this permission notice appear in supporting
77   -# documentation, and that the name of Secret Labs AB or the author(s) not be used
78   -# in advertising or publicity pertaining to distribution of the software
79   -# without specific, written prior permission.
80   -#
81   -# SECRET LABS AB AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
82   -# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
83   -# IN NO EVENT SHALL SECRET LABS AB OR THE AUTHORS BE LIABLE FOR ANY SPECIAL,
84   -# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
85   -# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
86   -# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
87   -# PERFORMANCE OF THIS SOFTWARE.
88   -
89   -#-----------------------------------------------------------------------------
90   -# CHANGELOG: (only olefile/OleFileIO_PL changes compared to PIL 1.1.6)
91   -# 2005-05-11 v0.10 PL: - a few fixes for Python 2.4 compatibility
92   -# (all changes flagged with [PL])
93   -# 2006-02-22 v0.11 PL: - a few fixes for some Office 2003 documents which raise
94   -# exceptions in OleStream.__init__()
95   -# 2006-06-09 v0.12 PL: - fixes for files above 6.8MB (DIFAT in loadfat)
96   -# - added some constants
97   -# - added header values checks
98   -# - added some docstrings
99   -# - getsect: bugfix in case sectors >512 bytes
100   -# - getsect: added conformity checks
101   -# - DEBUG_MODE constant to activate debug display
102   -# 2007-09-04 v0.13 PL: - improved/translated (lots of) comments
103   -# - updated license
104   -# - converted tabs to 4 spaces
105   -# 2007-11-19 v0.14 PL: - added OleFileIO._raise_defect() to adapt sensitivity
106   -# - improved _unicode() to use Python 2.x unicode support
107   -# - fixed bug in OleDirectoryEntry
108   -# 2007-11-25 v0.15 PL: - added safety checks to detect FAT loops
109   -# - fixed OleStream which didn't check stream size
110   -# - added/improved many docstrings and comments
111   -# - moved helper functions _unicode and _clsid out of
112   -# OleFileIO class
113   -# - improved OleFileIO._find() to add Unix path syntax
114   -# - OleFileIO._find() is now case-insensitive
115   -# - added get_type() and get_rootentry_name()
116   -# - rewritten loaddirectory and OleDirectoryEntry
117   -# 2007-11-27 v0.16 PL: - added OleDirectoryEntry.kids_dict
118   -# - added detection of duplicate filenames in storages
119   -# - added detection of duplicate references to streams
120   -# - added get_size() and exists() to OleDirectoryEntry
121   -# - added isOleFile to check header before parsing
122   -# - added __all__ list to control public keywords in pydoc
123   -# 2007-12-04 v0.17 PL: - added _load_direntry to fix a bug in loaddirectory
124   -# - improved _unicode(), added workarounds for Python <2.3
125   -# - added set_debug_mode and -d option to set debug mode
126   -# - fixed bugs in OleFileIO.open and OleDirectoryEntry
127   -# - added safety check in main for large or binary
128   -# properties
129   -# - allow size>0 for storages for some implementations
130   -# 2007-12-05 v0.18 PL: - fixed several bugs in handling of FAT, MiniFAT and
131   -# streams
132   -# - added option '-c' in main to check all streams
133   -# 2009-12-10 v0.19 PL: - bugfix for 32 bit arrays on 64 bits platforms
134   -# (thanks to Ben G. and Martijn for reporting the bug)
135   -# 2009-12-11 v0.20 PL: - bugfix in OleFileIO.open when filename is not plain str
136   -# 2010-01-22 v0.21 PL: - added support for big-endian CPUs such as PowerPC Macs
137   -# 2012-02-16 v0.22 PL: - fixed bug in getproperties, patch by chuckleberryfinn
138   -# (https://github.com/decalage2/olefile/issues/7)
139   -# - added close method to OleFileIO (fixed issue #2)
140   -# 2012-07-25 v0.23 PL: - added support for file-like objects (patch by mete0r_kr)
141   -# 2013-05-05 v0.24 PL: - getproperties: added conversion from filetime to python
142   -# datetime
143   -# - main: displays properties with date format
144   -# - new class OleMetadata to parse standard properties
145   -# - added get_metadata method
146   -# 2013-05-07 v0.24 PL: - a few improvements in OleMetadata
147   -# 2013-05-24 v0.25 PL: - getproperties: option to not convert some timestamps
148   -# - OleMetaData: total_edit_time is now a number of seconds,
149   -# not a timestamp
150   -# - getproperties: added support for VT_BOOL, VT_INT, V_UINT
151   -# - getproperties: filter out null chars from strings
152   -# - getproperties: raise non-fatal defects instead of
153   -# exceptions when properties cannot be parsed properly
154   -# 2013-05-27 PL: - getproperties: improved exception handling
155   -# - _raise_defect: added option to set exception type
156   -# - all non-fatal issues are now recorded, and displayed
157   -# when run as a script
158   -# 2013-07-11 v0.26 PL: - added methods to get modification and creation times
159   -# of a directory entry or a storage/stream
160   -# - fixed parsing of direntry timestamps
161   -# 2013-07-24 PL: - new options in listdir to list storages and/or streams
162   -# 2014-02-04 v0.30 PL: - upgraded code to support Python 3.x by Martin Panter
163   -# - several fixes for Python 2.6 (xrange, MAGIC)
164   -# - reused i32 from Pillow's _binary
165   -# 2014-07-18 v0.31 - preliminary support for 4K sectors
166   -# 2014-07-27 v0.31 PL: - a few improvements in OleFileIO.open (header parsing)
167   -# - Fixed loadfat for large files with 4K sectors (issue #3)
168   -# 2014-07-30 v0.32 PL: - added write_sect to write sectors to disk
169   -# - added write_mode option to OleFileIO.__init__ and open
170   -# 2014-07-31 PL: - fixed padding in write_sect for Python 3, added checks
171   -# - added write_stream to write a stream to disk
172   -# 2014-09-26 v0.40 PL: - renamed OleFileIO_PL to olefile
173   -# 2014-11-09 NE: - added support for Jython (Niko Ehrenfeuchter)
174   -# 2014-11-13 v0.41 PL: - improved isOleFile and OleFileIO.open to support OLE
175   -# data in a string buffer and file-like objects.
176   -# 2014-11-21 PL: - updated comments according to Pillow's commits
177   -# 2015-01-24 v0.42 PL: - changed the default path name encoding from Latin-1
178   -# to UTF-8 on Python 2.x (Unicode on Python 3.x)
179   -# - added path_encoding option to override the default
180   -# - fixed a bug in _list when a storage is empty
181   -# 2015-04-17 v0.43 PL: - slight changes in OleDirectoryEntry
182   -# 2015-10-19 - fixed issue #26 in OleFileIO.getproperties
183   -# (using id and type as local variable names)
184   -# 2015-10-29 - replaced debug() with proper logging
185   -# - use optparse to handle command line options
186   -# - improved attribute names in OleFileIO class
187   -# 2015-11-05 - fixed issue #27 by correcting the MiniFAT sector
188   -# cutoff size if invalid.
189   -# 2016-02-02 - logging is disabled by default
190   -# 2016-04-26 v0.44 PL: - added enable_logging
191   -# - renamed _OleDirectoryEntry and _OleStream without '_'
192   -# - in OleStream use _raise_defect instead of exceptions
193   -# 2016-04-27 - added support for incomplete streams and incorrect
194   -# directory entries (to read malformed documents)
195   -# 2016-05-04 - fixed slight bug in OleStream
196   -# 2016-11-27 DR: - added method to get the clsid of a storage/stream
197   -# (Daniel Roethlisberger)
198   -# 2017-05-31 v0.45 BS: - PR #114 from oletools to handle excessive number of
199   -# properties:
200   -# https://github.com/decalage2/oletools/pull/114
201   -# 2017-07-11 PL: - ignore incorrect ByteOrder (issue #70)
202   -
203   -__date__ = "2017-07-11"
204   -__version__ = '0.45dev2'
205   -__author__ = "Philippe Lagadec"
206   -
207   -#-----------------------------------------------------------------------------
208   -# TODO (for version 1.0):
209   -# + get rid of print statements, to simplify Python 2.x and 3.x support
210   -# + add is_stream and is_storage
211   -# + remove leading and trailing slashes where a path is used
212   -# + add functions path_list2str and path_str2list
213   -# + fix how all the methods handle unicode str and/or bytes as arguments
214   -# + add path attrib to _OleDirEntry, set it once and for all in init or
215   -# append_kids (then listdir/_list can be simplified)
216   -# - TESTS with Linux, MacOSX, Python 1.5.2, various files, PIL, ...
217   -# - add underscore to each private method, to avoid their display in
218   -# pydoc/epydoc documentation - Remove it for classes to be documented
219   -# - replace all raised exceptions with _raise_defect (at least in OleFileIO)
220   -# - merge code from OleStream and OleFileIO.getsect to read sectors
221   -# (maybe add a class for FAT and MiniFAT ?)
222   -# - add method to check all streams (follow sectors chains without storing all
223   -# stream in memory, and report anomalies)
224   -# - use OleDirectoryEntry.kids_dict to improve _find and _list ?
225   -# - fix Unicode names handling (find some way to stay compatible with Py1.5.2)
226   -# => if possible avoid converting names to Latin-1
227   -# - review DIFAT code: fix handling of DIFSECT blocks in FAT (not stop)
228   -# - rewrite OleFileIO.getproperties
229   -# - improve docstrings to show more sample uses
230   -# - see also original notes and FIXME below
231   -# - remove all obsolete FIXMEs
232   -# - OleMetadata: fix version attrib according to
233   -# https://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx
234   -
235   -# IDEAS:
236   -# - in OleFileIO._open and OleStream, use size=None instead of 0x7FFFFFFF for
237   -# streams with unknown size
238   -# - use arrays of int instead of long integers for FAT/MiniFAT, to improve
239   -# performance and reduce memory usage ? (possible issue with values >2^31)
240   -# - provide tests with unittest (may need write support to create samples)
241   -# - move all debug code (and maybe dump methods) to a separate module, with
242   -# a class which inherits OleFileIO ?
243   -# - fix docstrings to follow epydoc format
244   -# - add support for big endian byte order ?
245   -# - create a simple OLE explorer with wxPython
246   -
247   -# FUTURE EVOLUTIONS to add write support:
248   -# see issue #6 on GitHub:
249   -# https://github.com/decalage2/olefile/issues/6
250   -
251   -#-----------------------------------------------------------------------------
252   -# NOTES from PIL 1.1.6:
253   -
254   -# History:
255   -# 1997-01-20 fl Created
256   -# 1997-01-22 fl Fixed 64-bit portability quirk
257   -# 2003-09-09 fl Fixed typo in OleFileIO.loadfat (noted by Daniel Haertle)
258   -# 2004-02-29 fl Changed long hex constants to signed integers
259   -#
260   -# Notes:
261   -# FIXME: sort out sign problem (eliminate long hex constants)
262   -# FIXME: change filename to use "a/b/c" instead of ["a", "b", "c"]
263   -# FIXME: provide a glob mechanism function (using fnmatchcase)
264   -#
265   -# Literature:
266   -#
267   -# "FlashPix Format Specification, Appendix A", Kodak and Microsoft,
268   -# September 1996.
269   -#
270   -# Quotes:
271   -#
272   -# "If this document and functionality of the Software conflict,
273   -# the actual functionality of the Software represents the correct
274   -# functionality" -- Microsoft, in the OLE format specification
275   -
276   -#------------------------------------------------------------------------------
277   -
278   -__all__ = ['isOleFile', 'OleFileIO', 'OleMetadata', 'enable_logging',
279   - 'MAGIC', 'STGTY_EMPTY',
280   - 'STGTY_STREAM', 'STGTY_STORAGE', 'STGTY_ROOT', 'STGTY_PROPERTY',
281   - 'STGTY_LOCKBYTES', 'MINIMAL_OLEFILE_SIZE', 'NOSTREAM']
282   -
283   -import io
284   -import sys
285   -import struct, array, os.path, datetime, logging
286   -
287   -#=== COMPATIBILITY WORKAROUNDS ================================================
288   -
289   -#[PL] Define explicitly the public API to avoid private objects in pydoc:
290   -#TODO: add more
291   -# __all__ = ['OleFileIO', 'isOleFile', 'MAGIC']
292   -
293   -# For Python 3.x, need to redefine long as int:
294   -if str is not bytes:
295   - long = int
296   -
297   -# Need to make sure we use xrange both on Python 2 and 3.x:
298   -try:
299   - # on Python 2 we need xrange:
300   - iterrange = xrange
301   -except:
302   - # no xrange, for Python 3 it was renamed as range:
303   - iterrange = range
304   -
305   -#[PL] workaround to fix an issue with array item size on 64 bits systems:
306   -if array.array('L').itemsize == 4:
307   - # on 32 bits platforms, long integers in an array are 32 bits:
308   - UINT32 = 'L'
309   -elif array.array('I').itemsize == 4:
310   - # on 64 bits platforms, integers in an array are 32 bits:
311   - UINT32 = 'I'
312   -elif array.array('i').itemsize == 4:
313   - # On 64 bit Jython, signed integers ('i') are the only way to store our 32
314   - # bit values in an array in a *somewhat* reasonable way, as the otherwise
315   - # perfectly suited 'H' (unsigned int, 32 bits) results in a completely
316   - # unusable behaviour. This is most likely caused by the fact that Java
317   - # doesn't have unsigned values, and thus Jython's "array" implementation,
318   - # which is based on "jarray", doesn't have them either.
319   - # NOTE: to trick Jython into converting the values it would normally
320   - # interpret as "signed" into "unsigned", a binary-and operation with
321   - # 0xFFFFFFFF can be used. This way it is possible to use the same comparing
322   - # operations on all platforms / implementations. The corresponding code
323   - # lines are flagged with a 'JYTHON-WORKAROUND' tag below.
324   - UINT32 = 'i'
325   -else:
326   - raise ValueError('Need to fix a bug with 32 bit arrays, please contact author...')
327   -
328   -
329   -#[PL] These workarounds were inspired from the Path module
330   -# (see http://www.jorendorff.com/articles/python/path/)
331   -try:
332   - basestring
333   -except NameError:
334   - basestring = str
335   -
336   -#[PL] Experimental setting: if True, OLE filenames will be kept in Unicode
337   -# if False (default PIL behaviour), all filenames are converted to Latin-1.
338   -KEEP_UNICODE_NAMES = True
339   -
340   -if sys.version_info[0] < 3:
341   - # On Python 2.x, the default encoding for path names is UTF-8:
342   - DEFAULT_PATH_ENCODING = 'utf-8'
343   -else:
344   - # On Python 3.x, the default encoding for path names is Unicode (None):
345   - DEFAULT_PATH_ENCODING = None
346   -
347   -
348   -# === LOGGING =================================================================
349   -
350   -class NullHandler(logging.Handler):
351   - """
352   - Log Handler without output, to avoid printing messages if logging is not
353   - configured by the main application.
354   - Python 2.7 has logging.NullHandler, but this is necessary for 2.6:
355   - see https://docs.python.org/2.6/library/logging.html#configuring-logging-for-a-library
356   - """
357   - def emit(self, record):
358   - pass
359   -
360   -def get_logger(name, level=logging.CRITICAL+1):
361   - """
362   - Create a suitable logger object for this module.
363   - The goal is not to change settings of the root logger, to avoid getting
364   - other modules' logs on the screen.
365   - If a logger exists with same name, reuse it. (Else it would have duplicate
366   - handlers and messages would be doubled.)
367   - The level is set to CRITICAL+1 by default, to avoid any logging.
368   - """
369   - # First, test if there is already a logger with the same name, else it
370   - # will generate duplicate messages (due to duplicate handlers):
371   - if name in logging.Logger.manager.loggerDict:
372   - #NOTE: another less intrusive but more "hackish" solution would be to
373   - # use getLogger then test if its effective level is not default.
374   - logger = logging.getLogger(name)
375   - # make sure level is OK:
376   - logger.setLevel(level)
377   - return logger
378   - # get a new logger:
379   - logger = logging.getLogger(name)
380   - # only add a NullHandler for this logger, it is up to the application
381   - # to configure its own logging:
382   - logger.addHandler(NullHandler())
383   - logger.setLevel(level)
384   - return logger
385   -
386   -
387   -# a global logger object used for debugging:
388   -log = get_logger('olefile')
389   -
390   -
391   -def enable_logging():
392   - """
393   - Enable logging for this module (disabled by default).
394   - This will set the module-specific logger level to NOTSET, which
395   - means the main application controls the actual logging level.
396   - """
397   - log.setLevel(logging.NOTSET)
398   -
399   -
400   -#=== CONSTANTS ===============================================================
401   -
402   -#: magic bytes that should be at the beginning of every OLE file:
403   -MAGIC = b'\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1'
404   -
405   -#[PL]: added constants for Sector IDs (from AAF specifications)
406   -MAXREGSECT = 0xFFFFFFFA #: (-6) maximum SECT
407   -DIFSECT = 0xFFFFFFFC #: (-4) denotes a DIFAT sector in a FAT
408   -FATSECT = 0xFFFFFFFD #: (-3) denotes a FAT sector in a FAT
409   -ENDOFCHAIN = 0xFFFFFFFE #: (-2) end of a virtual stream chain
410   -FREESECT = 0xFFFFFFFF #: (-1) unallocated sector
411   -
412   -#[PL]: added constants for Directory Entry IDs (from AAF specifications)
413   -MAXREGSID = 0xFFFFFFFA #: (-6) maximum directory entry ID
414   -NOSTREAM = 0xFFFFFFFF #: (-1) unallocated directory entry
415   -
416   -#[PL] object types in storage (from AAF specifications)
417   -STGTY_EMPTY = 0 #: empty directory entry
418   -STGTY_STORAGE = 1 #: element is a storage object
419   -STGTY_STREAM = 2 #: element is a stream object
420   -STGTY_LOCKBYTES = 3 #: element is an ILockBytes object
421   -STGTY_PROPERTY = 4 #: element is an IPropertyStorage object
422   -STGTY_ROOT = 5 #: element is a root storage
423   -
424   -# Unknown size for a stream (used by OleStream):
425   -UNKNOWN_SIZE = 0x7FFFFFFF
426   -
427   -#
428   -# --------------------------------------------------------------------
429   -# property types
430   -
431   -VT_EMPTY=0; VT_NULL=1; VT_I2=2; VT_I4=3; VT_R4=4; VT_R8=5; VT_CY=6;
432   -VT_DATE=7; VT_BSTR=8; VT_DISPATCH=9; VT_ERROR=10; VT_BOOL=11;
433   -VT_VARIANT=12; VT_UNKNOWN=13; VT_DECIMAL=14; VT_I1=16; VT_UI1=17;
434   -VT_UI2=18; VT_UI4=19; VT_I8=20; VT_UI8=21; VT_INT=22; VT_UINT=23;
435   -VT_VOID=24; VT_HRESULT=25; VT_PTR=26; VT_SAFEARRAY=27; VT_CARRAY=28;
436   -VT_USERDEFINED=29; VT_LPSTR=30; VT_LPWSTR=31; VT_FILETIME=64;
437   -VT_BLOB=65; VT_STREAM=66; VT_STORAGE=67; VT_STREAMED_OBJECT=68;
438   -VT_STORED_OBJECT=69; VT_BLOB_OBJECT=70; VT_CF=71; VT_CLSID=72;
439   -VT_VECTOR=0x1000;
440   -
441   -# map property id to name (for debugging purposes)
442   -
443   -VT = {}
444   -for keyword, var in list(vars().items()):
445   - if keyword[:3] == "VT_":
446   - VT[var] = keyword
447   -
448   -#
449   -# --------------------------------------------------------------------
450   -# Some common document types (root.clsid fields)
451   -
452   -WORD_CLSID = "00020900-0000-0000-C000-000000000046"
453   -#TODO: check Excel, PPT, ...
454   -
455   -#[PL]: Defect levels to classify parsing errors - see OleFileIO._raise_defect()
456   -DEFECT_UNSURE = 10 # a case which looks weird, but not sure it's a defect
457   -DEFECT_POTENTIAL = 20 # a potential defect
458   -DEFECT_INCORRECT = 30 # an error according to specifications, but parsing
459   - # can go on
460   -DEFECT_FATAL = 40 # an error which cannot be ignored, parsing is
461   - # impossible
462   -
463   -# Minimal size of an empty OLE file, with 512-bytes sectors = 1536 bytes
464   -# (this is used in isOleFile and OleFile.open)
465   -MINIMAL_OLEFILE_SIZE = 1536
466   -
467   -#[PL] add useful constants to __all__:
468   -# for key in list(vars().keys()):
469   -# if key.startswith('STGTY_') or key.startswith('DEFECT_'):
470   -# __all__.append(key)
471   -
472   -
473   -#=== FUNCTIONS ===============================================================
474   -
475   -def isOleFile (filename):
476   - """
477   - Test if a file is an OLE container (according to the magic bytes in its header).
478   -
479   - .. note::
480   - This function only checks the first 8 bytes of the file, not the
481   - rest of the OLE structure.
482   -
483   - .. versionadded:: 0.16
484   -
485   - :param filename: filename, contents or file-like object of the OLE file (string-like or file-like object)
486   -
487   - - if filename is a string smaller than 1536 bytes, it is the path
488   - of the file to open. (bytes or unicode string)
489   - - if filename is a string longer than 1535 bytes, it is parsed
490   - as the content of an OLE file in memory. (bytes type only)
491   - - if filename is a file-like object (with read and seek methods),
492   - it is parsed as-is.
493   -
494   - :type filename: bytes or str or unicode or file
495   - :returns: True if OLE, False otherwise.
496   - :rtype: bool
497   - """
498   - # check if filename is a string-like or file-like object:
499   - if hasattr(filename, 'read'):
500   - # file-like object: use it directly
501   - header = filename.read(len(MAGIC))
502   - # just in case, seek back to start of file:
503   - filename.seek(0)
504   - elif isinstance(filename, bytes) and len(filename) >= MINIMAL_OLEFILE_SIZE:
505   - # filename is a bytes string containing the OLE file to be parsed:
506   - header = filename[:len(MAGIC)]
507   - else:
508   - # string-like object: filename of file on disk
509   - with open(filename, 'rb') as fp:
510   - header = fp.read(len(MAGIC))
511   - if header == MAGIC:
512   - return True
513   - else:
514   - return False
515   -
516   -
517   -if bytes is str:
518   - # version for Python 2.x
519   - def i8(c):
520   - return ord(c)
521   -else:
522   - # version for Python 3.x
523   - def i8(c):
524   - return c if c.__class__ is int else c[0]
525   -
526   -
527   -def i16(c, o = 0):
528   - """
529   - Converts a 2-bytes (16 bits) string to an integer.
530   -
531   - :param c: string containing bytes to convert
532   - :param o: offset of bytes to convert in string
533   - """
534   - return struct.unpack("<H", c[o:o+2])[0]
535   -
536   -
537   -def i32(c, o = 0):
538   - """
539   - Converts a 4-bytes (32 bits) string to an integer.
540   -
541   - :param c: string containing bytes to convert
542   - :param o: offset of bytes to convert in string
543   - """
544   - return struct.unpack("<I", c[o:o+4])[0]
545   -
546   -
547   -def _clsid(clsid):
548   - """
549   - Converts a CLSID to a human-readable string.
550   -
551   - :param clsid: string of length 16.
552   - """
553   - assert len(clsid) == 16
554   - # if clsid is only made of null bytes, return an empty string:
555   - # (PL: why not simply return the string with zeroes?)
556   - if not clsid.strip(b"\0"):
557   - return ""
558   - return (("%08X-%04X-%04X-%02X%02X-" + "%02X" * 6) %
559   - ((i32(clsid, 0), i16(clsid, 4), i16(clsid, 6)) +
560   - tuple(map(i8, clsid[8:16]))))
561   -
562   -
563   -
564   -def filetime2datetime(filetime):
565   - """
566   - convert FILETIME (64 bits int) to Python datetime.datetime
567   - """
568   - # TODO: manage exception when microseconds is too large
569   - # inspired from https://code.activestate.com/recipes/511425-filetime-to-datetime/
570   - _FILETIME_null_date = datetime.datetime(1601, 1, 1, 0, 0, 0)
571   - #log.debug('timedelta days=%d' % (filetime//(10*1000000*3600*24)))
572   - return _FILETIME_null_date + datetime.timedelta(microseconds=filetime//10)
573   -
574   -
575   -
576   -#=== CLASSES ==================================================================
577   -
578   -class OleMetadata:
579   - """
580   - class to parse and store metadata from standard properties of OLE files.
581   -
582   - Available attributes:
583   - codepage, title, subject, author, keywords, comments, template,
584   - last_saved_by, revision_number, total_edit_time, last_printed, create_time,
585   - last_saved_time, num_pages, num_words, num_chars, thumbnail,
586   - creating_application, security, codepage_doc, category, presentation_target,
587   - bytes, lines, paragraphs, slides, notes, hidden_slides, mm_clips,
588   - scale_crop, heading_pairs, titles_of_parts, manager, company, links_dirty,
589   - chars_with_spaces, unused, shared_doc, link_base, hlinks, hlinks_changed,
590   - version, dig_sig, content_type, content_status, language, doc_version
591   -
592   - Note: an attribute is set to None when not present in the properties of the
593   - OLE file.
594   -
595   - References for SummaryInformation stream:
596   -
597   - - https://msdn.microsoft.com/en-us/library/dd942545.aspx
598   - - https://msdn.microsoft.com/en-us/library/dd925819%28v=office.12%29.aspx
599   - - https://msdn.microsoft.com/en-us/library/windows/desktop/aa380376%28v=vs.85%29.aspx
600   - - https://msdn.microsoft.com/en-us/library/aa372045.aspx
601   - - http://sedna-soft.de/articles/summary-information-stream/
602   - - https://poi.apache.org/apidocs/org/apache/poi/hpsf/SummaryInformation.html
603   -
604   - References for DocumentSummaryInformation stream:
605   -
606   - - https://msdn.microsoft.com/en-us/library/dd945671%28v=office.12%29.aspx
607   - - https://msdn.microsoft.com/en-us/library/windows/desktop/aa380374%28v=vs.85%29.aspx
608   - - https://poi.apache.org/apidocs/org/apache/poi/hpsf/DocumentSummaryInformation.html
609   -
610   - new in version 0.25
611   - """
612   -
613   - # attribute names for SummaryInformation stream properties:
614   - # (ordered by property id, starting at 1)
615   - SUMMARY_ATTRIBS = ['codepage', 'title', 'subject', 'author', 'keywords', 'comments',
616   - 'template', 'last_saved_by', 'revision_number', 'total_edit_time',
617   - 'last_printed', 'create_time', 'last_saved_time', 'num_pages',
618   - 'num_words', 'num_chars', 'thumbnail', 'creating_application',
619   - 'security']
620   -
621   - # attribute names for DocumentSummaryInformation stream properties:
622   - # (ordered by property id, starting at 1)
623   - DOCSUM_ATTRIBS = ['codepage_doc', 'category', 'presentation_target', 'bytes', 'lines', 'paragraphs',
624   - 'slides', 'notes', 'hidden_slides', 'mm_clips',
625   - 'scale_crop', 'heading_pairs', 'titles_of_parts', 'manager',
626   - 'company', 'links_dirty', 'chars_with_spaces', 'unused', 'shared_doc',
627   - 'link_base', 'hlinks', 'hlinks_changed', 'version', 'dig_sig',
628   - 'content_type', 'content_status', 'language', 'doc_version']
629   -
630   - def __init__(self):
631   - """
632   - Constructor for OleMetadata
633   - All attributes are set to None by default
634   - """
635   - # properties from SummaryInformation stream
636   - self.codepage = None
637   - self.title = None
638   - self.subject = None
639   - self.author = None
640   - self.keywords = None
641   - self.comments = None
642   - self.template = None
643   - self.last_saved_by = None
644   - self.revision_number = None
645   - self.total_edit_time = None
646   - self.last_printed = None
647   - self.create_time = None
648   - self.last_saved_time = None
649   - self.num_pages = None
650   - self.num_words = None
651   - self.num_chars = None
652   - self.thumbnail = None
653   - self.creating_application = None
654   - self.security = None
655   - # properties from DocumentSummaryInformation stream
656   - self.codepage_doc = None
657   - self.category = None
658   - self.presentation_target = None
659   - self.bytes = None
660   - self.lines = None
661   - self.paragraphs = None
662   - self.slides = None
663   - self.notes = None
664   - self.hidden_slides = None
665   - self.mm_clips = None
666   - self.scale_crop = None
667   - self.heading_pairs = None
668   - self.titles_of_parts = None
669   - self.manager = None
670   - self.company = None
671   - self.links_dirty = None
672   - self.chars_with_spaces = None
673   - self.unused = None
674   - self.shared_doc = None
675   - self.link_base = None
676   - self.hlinks = None
677   - self.hlinks_changed = None
678   - self.version = None
679   - self.dig_sig = None
680   - self.content_type = None
681   - self.content_status = None
682   - self.language = None
683   - self.doc_version = None
684   -
685   -
686   - def parse_properties(self, olefile):
687   - """
688   - Parse standard properties of an OLE file, from the streams
689   - ``\\x05SummaryInformation`` and ``\\x05DocumentSummaryInformation``,
690   - if present.
691   - Properties are converted to strings, integers or python datetime objects.
692   - If a property is not present, its value is set to None.
693   - """
694   - # first set all attributes to None:
695   - for attrib in (self.SUMMARY_ATTRIBS + self.DOCSUM_ATTRIBS):
696   - setattr(self, attrib, None)
697   - if olefile.exists("\x05SummaryInformation"):
698   - # get properties from the stream:
699   - # (converting timestamps to python datetime, except total_edit_time,
700   - # which is property #10)
701   - props = olefile.getproperties("\x05SummaryInformation",
702   - convert_time=True, no_conversion=[10])
703   - # store them into this object's attributes:
704   - for i in range(len(self.SUMMARY_ATTRIBS)):
705   - # ids for standards properties start at 0x01, until 0x13
706   - value = props.get(i+1, None)
707   - setattr(self, self.SUMMARY_ATTRIBS[i], value)
708   - if olefile.exists("\x05DocumentSummaryInformation"):
709   - # get properties from the stream:
710   - props = olefile.getproperties("\x05DocumentSummaryInformation",
711   - convert_time=True)
712   - # store them into this object's attributes:
713   - for i in range(len(self.DOCSUM_ATTRIBS)):
714   - # ids for standards properties start at 0x01, until 0x13
715   - value = props.get(i+1, None)
716   - setattr(self, self.DOCSUM_ATTRIBS[i], value)
717   -
718   - def dump(self):
719   - """
720   - Dump all metadata, for debugging purposes.
721   - """
722   - print('Properties from SummaryInformation stream:')
723   - for prop in self.SUMMARY_ATTRIBS:
724   - value = getattr(self, prop)
725   - print('- %s: %s' % (prop, repr(value)))
726   - print('Properties from DocumentSummaryInformation stream:')
727   - for prop in self.DOCSUM_ATTRIBS:
728   - value = getattr(self, prop)
729   - print('- %s: %s' % (prop, repr(value)))
730   -
731   -
732   -#--- OleStream ---------------------------------------------------------------
733   -
734   -class OleStream(io.BytesIO):
735   - """
736   - OLE2 Stream
737   -
738   - Returns a read-only file object which can be used to read
739   - the contents of a OLE stream (instance of the BytesIO class).
740   - To open a stream, use the openstream method in the OleFile class.
741   -
742   - This function can be used with either ordinary streams,
743   - or ministreams, depending on the offset, sectorsize, and
744   - fat table arguments.
745   -
746   - Attributes:
747   -
748   - - size: actual size of data stream, after it was opened.
749   - """
750   - # FIXME: should store the list of sects obtained by following
751   - # the fat chain, and load new sectors on demand instead of
752   - # loading it all in one go.
753   -
754   - def __init__(self, fp, sect, size, offset, sectorsize, fat, filesize, olefileio):
755   - """
756   - Constructor for OleStream class.
757   -
758   - :param fp: file object, the OLE container or the MiniFAT stream
759   - :param sect: sector index of first sector in the stream
760   - :param size: total size of the stream
761   - :param offset: offset in bytes for the first FAT or MiniFAT sector
762   - :param sectorsize: size of one sector
763   - :param fat: array/list of sector indexes (FAT or MiniFAT)
764   - :param filesize: size of OLE file (for debugging)
765   - :param olefileio: OleFileIO object containing this stream
766   - :returns: a BytesIO instance containing the OLE stream
767   - """
768   - log.debug('OleStream.__init__:')
769   - log.debug(' sect=%d (%X), size=%d, offset=%d, sectorsize=%d, len(fat)=%d, fp=%s'
770   - %(sect,sect,size,offset,sectorsize,len(fat), repr(fp)))
771   - self.ole = olefileio
772   - if self.ole.fp.closed:
773   - raise OSError('Attempting to open a stream from a closed OLE File')
774   - #[PL] To detect malformed documents with FAT loops, we compute the
775   - # expected number of sectors in the stream:
776   - unknown_size = False
777   - if size == UNKNOWN_SIZE:
778   - # this is the case when called from OleFileIO._open(), and stream
779   - # size is not known in advance (for example when reading the
780   - # Directory stream). Then we can only guess maximum size:
781   - size = len(fat)*sectorsize
782   - # and we keep a record that size was unknown:
783   - unknown_size = True
784   - log.debug(' stream with UNKNOWN SIZE')
785   - nb_sectors = (size + (sectorsize-1)) // sectorsize
786   - log.debug('nb_sectors = %d' % nb_sectors)
787   - # This number should (at least) be less than the total number of
788   - # sectors in the given FAT:
789   - if nb_sectors > len(fat):
790   - self.ole._raise_defect(DEFECT_INCORRECT, 'malformed OLE document, stream too large')
791   - # optimization(?): data is first a list of strings, and join() is called
792   - # at the end to concatenate all in one string.
793   - # (this may not be really useful with recent Python versions)
794   - data = []
795   - # if size is zero, then first sector index should be ENDOFCHAIN:
796   - if size == 0 and sect != ENDOFCHAIN:
797   - log.debug('size == 0 and sect != ENDOFCHAIN:')
798   - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE sector index for empty stream')
799   - #[PL] A fixed-length for loop is used instead of an undefined while
800   - # loop to avoid DoS attacks:
801   - for i in range(nb_sectors):
802   - log.debug('Reading stream sector[%d] = %Xh' % (i, sect))
803   - # Sector index may be ENDOFCHAIN, but only if size was unknown
804   - if sect == ENDOFCHAIN:
805   - if unknown_size:
806   - log.debug('Reached ENDOFCHAIN sector for stream with unknown size')
807   - break
808   - else:
809   - # else this means that the stream is smaller than declared:
810   - log.debug('sect=ENDOFCHAIN before expected size')
811   - self.ole._raise_defect(DEFECT_INCORRECT, 'incomplete OLE stream')
812   - # sector index should be within FAT:
813   - if sect<0 or sect>=len(fat):
814   - log.debug('sect=%d (%X) / len(fat)=%d' % (sect, sect, len(fat)))
815   - log.debug('i=%d / nb_sectors=%d' %(i, nb_sectors))
816   -## tmp_data = b"".join(data)
817   -## f = open('test_debug.bin', 'wb')
818   -## f.write(tmp_data)
819   -## f.close()
820   -## log.debug('data read so far: %d bytes' % len(tmp_data))
821   - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE FAT, sector index out of range')
822   - # stop reading here if the exception is ignored:
823   - break
824   - #TODO: merge this code with OleFileIO.getsect() ?
825   - #TODO: check if this works with 4K sectors:
826   - try:
827   - fp.seek(offset + sectorsize * sect)
828   - except:
829   - log.debug('sect=%d, seek=%d, filesize=%d' %
830   - (sect, offset+sectorsize*sect, filesize))
831   - self.ole._raise_defect(DEFECT_INCORRECT, 'OLE sector index out of range')
832   - # stop reading here if the exception is ignored:
833   - break
834   - sector_data = fp.read(sectorsize)
835   - # [PL] check if there was enough data:
836   - # Note: if sector is the last of the file, sometimes it is not a
837   - # complete sector (of 512 or 4K), so we may read less than
838   - # sectorsize.
839   - if len(sector_data)!=sectorsize and sect!=(len(fat)-1):
840   - log.debug('sect=%d / len(fat)=%d, seek=%d / filesize=%d, len read=%d' %
841   - (sect, len(fat), offset+sectorsize*sect, filesize, len(sector_data)))
842   - log.debug('seek+len(read)=%d' % (offset+sectorsize*sect+len(sector_data)))
843   - self.ole._raise_defect(DEFECT_INCORRECT, 'incomplete OLE sector')
844   - data.append(sector_data)
845   - # jump to next sector in the FAT:
846   - try:
847   - sect = fat[sect] & 0xFFFFFFFF # JYTHON-WORKAROUND
848   - except IndexError:
849   - # [PL] if pointer is out of the FAT an exception is raised
850   - self.ole._raise_defect(DEFECT_INCORRECT, 'incorrect OLE FAT, sector index out of range')
851   - # stop reading here if the exception is ignored:
852   - break
853   - #[PL] Last sector should be a "end of chain" marker:
854   - # if sect != ENDOFCHAIN:
855   - # raise IOError('incorrect last sector index in OLE stream')
856   - data = b"".join(data)
857   - # Data is truncated to the actual stream size:
858   - if len(data) >= size:
859   - log.debug('Read data of length %d, truncated to stream size %d' % (len(data), size))
860   - data = data[:size]
861   - # actual stream size is stored for future use:
862   - self.size = size
863   - elif unknown_size:
864   - # actual stream size was not known, now we know the size of read
865   - # data:
866   - log.debug('Read data of length %d, the stream size was unknown' % len(data))
867   - self.size = len(data)
868   - else:
869   - # read data is less than expected:
870   - log.debug('Read data of length %d, less than expected stream size %d' % (len(data), size))
871   - # TODO: provide details in exception message
872   - self.size = len(data)
873   - self.ole._raise_defect(DEFECT_INCORRECT, 'OLE stream size is less than declared')
874   - # when all data is read in memory, BytesIO constructor is called
875   - io.BytesIO.__init__(self, data)
876   - # Then the OleStream object can be used as a read-only file object.
877   -
878   -
879   -#--- OleDirectoryEntry -------------------------------------------------------
880   -
881   -class OleDirectoryEntry:
882   -
883   - """
884   - OLE2 Directory Entry
885   - """
886   - #[PL] parsing code moved from OleFileIO.loaddirectory
887   -
888   - # struct to parse directory entries:
889   - # <: little-endian byte order, standard sizes
890   - # (note: this should guarantee that Q returns a 64 bits int)
891   - # 64s: string containing entry name in unicode UTF-16 (max 31 chars) + null char = 64 bytes
892   - # H: uint16, number of bytes used in name buffer, including null = (len+1)*2
893   - # B: uint8, dir entry type (between 0 and 5)
894   - # B: uint8, color: 0=black, 1=red
895   - # I: uint32, index of left child node in the red-black tree, NOSTREAM if none
896   - # I: uint32, index of right child node in the red-black tree, NOSTREAM if none
897   - # I: uint32, index of child root node if it is a storage, else NOSTREAM
898   - # 16s: CLSID, unique identifier (only used if it is a storage)
899   - # I: uint32, user flags
900   - # Q (was 8s): uint64, creation timestamp or zero
901   - # Q (was 8s): uint64, modification timestamp or zero
902   - # I: uint32, SID of first sector if stream or ministream, SID of 1st sector
903   - # of stream containing ministreams if root entry, 0 otherwise
904   - # I: uint32, total stream size in bytes if stream (low 32 bits), 0 otherwise
905   - # I: uint32, total stream size in bytes if stream (high 32 bits), 0 otherwise
906   - STRUCT_DIRENTRY = '<64sHBBIII16sIQQIII'
907   - # size of a directory entry: 128 bytes
908   - DIRENTRY_SIZE = 128
909   - assert struct.calcsize(STRUCT_DIRENTRY) == DIRENTRY_SIZE
910   -
911   -
912   - def __init__(self, entry, sid, olefile):
913   - """
914   - Constructor for an OleDirectoryEntry object.
915   - Parses a 128-bytes entry from the OLE Directory stream.
916   -
917   - :param entry : string (must be 128 bytes long)
918   - :param sid : index of this directory entry in the OLE file directory
919   - :param olefile: OleFileIO containing this directory entry
920   - """
921   - self.sid = sid
922   - # ref to olefile is stored for future use
923   - self.olefile = olefile
924   - # kids is a list of children entries, if this entry is a storage:
925   - # (list of OleDirectoryEntry objects)
926   - self.kids = []
927   - # kids_dict is a dictionary of children entries, indexed by their
928   - # name in lowercase: used to quickly find an entry, and to detect
929   - # duplicates
930   - self.kids_dict = {}
931   - # flag used to detect if the entry is referenced more than once in
932   - # directory:
933   - self.used = False
934   - # decode DirEntry
935   - (
936   - self.name_raw, # 64s: string containing entry name in unicode UTF-16 (max 31 chars) + null char = 64 bytes
937   - self.namelength, # H: uint16, number of bytes used in name buffer, including null = (len+1)*2
938   - self.entry_type,
939   - self.color,
940   - self.sid_left,
941   - self.sid_right,
942   - self.sid_child,
943   - clsid,
944   - self.dwUserFlags,
945   - self.createTime,
946   - self.modifyTime,
947   - self.isectStart,
948   - self.sizeLow,
949   - self.sizeHigh
950   - ) = struct.unpack(OleDirectoryEntry.STRUCT_DIRENTRY, entry)
951   - if self.entry_type not in [STGTY_ROOT, STGTY_STORAGE, STGTY_STREAM, STGTY_EMPTY]:
952   - olefile._raise_defect(DEFECT_INCORRECT, 'unhandled OLE storage type')
953   - # only first directory entry can (and should) be root:
954   - if self.entry_type == STGTY_ROOT and sid != 0:
955   - olefile._raise_defect(DEFECT_INCORRECT, 'duplicate OLE root entry')
956   - if sid == 0 and self.entry_type != STGTY_ROOT:
957   - olefile._raise_defect(DEFECT_INCORRECT, 'incorrect OLE root entry')
958   - #log.debug(struct.unpack(fmt_entry, entry[:len_entry]))
959   - # name should be at most 31 unicode characters + null character,
960   - # so 64 bytes in total (31*2 + 2):
961   - if self.namelength>64:
962   - olefile._raise_defect(DEFECT_INCORRECT, 'incorrect DirEntry name length >64 bytes')
963   - # if exception not raised, namelength is set to the maximum value:
964   - self.namelength = 64
965   - # only characters without ending null char are kept:
966   - self.name_utf16 = self.name_raw[:(self.namelength-2)]
967   - #TODO: check if the name is actually followed by a null unicode character ([MS-CFB] 2.6.1)
968   - #TODO: check if the name does not contain forbidden characters:
969   - # [MS-CFB] 2.6.1: "The following characters are illegal and MUST NOT be part of the name: '/', '\', ':', '!'."
970   - # name is converted from UTF-16LE to the path encoding specified in the OleFileIO:
971   - self.name = olefile._decode_utf16_str(self.name_utf16)
972   -
973   - log.debug('DirEntry SID=%d: %s' % (self.sid, repr(self.name)))
974   - log.debug(' - type: %d' % self.entry_type)
975   - log.debug(' - sect: %Xh' % self.isectStart)
976   - log.debug(' - SID left: %d, right: %d, child: %d' % (self.sid_left,
977   - self.sid_right, self.sid_child))
978   -
979   - # sizeHigh is only used for 4K sectors, it should be zero for 512 bytes
980   - # sectors, BUT apparently some implementations set it as 0xFFFFFFFF, 1
981   - # or some other value so it cannot be raised as a defect in general:
982   - if olefile.sectorsize == 512:
983   - if self.sizeHigh != 0 and self.sizeHigh != 0xFFFFFFFF:
984   - log.debug('sectorsize=%d, sizeLow=%d, sizeHigh=%d (%X)' %
985   - (olefile.sectorsize, self.sizeLow, self.sizeHigh, self.sizeHigh))
986   - olefile._raise_defect(DEFECT_UNSURE, 'incorrect OLE stream size')
987   - self.size = self.sizeLow
988   - else:
989   - self.size = self.sizeLow + (long(self.sizeHigh)<<32)
990   - log.debug(' - size: %d (sizeLow=%d, sizeHigh=%d)' % (self.size, self.sizeLow, self.sizeHigh))
991   -
992   - self.clsid = _clsid(clsid)
993   - # a storage should have a null size, BUT some implementations such as
994   - # Word 8 for Mac seem to allow non-null values => Potential defect:
995   - if self.entry_type == STGTY_STORAGE and self.size != 0:
996   - olefile._raise_defect(DEFECT_POTENTIAL, 'OLE storage with size>0')
997   - # check if stream is not already referenced elsewhere:
998   - if self.entry_type in (STGTY_ROOT, STGTY_STREAM) and self.size>0:
999   - if self.size < olefile.minisectorcutoff \
1000   - and self.entry_type==STGTY_STREAM: # only streams can be in MiniFAT
1001   - # ministream object
1002   - minifat = True
1003   - else:
1004   - minifat = False
1005   - olefile._check_duplicate_stream(self.isectStart, minifat)
1006   -
1007   -
1008   -
1009   - def build_storage_tree(self):
1010   - """
1011   - Read and build the red-black tree attached to this OleDirectoryEntry
1012   - object, if it is a storage.
1013   - Note that this method builds a tree of all subentries, so it should
1014   - only be called for the root object once.
1015   - """
1016   - log.debug('build_storage_tree: SID=%d - %s - sid_child=%d'
1017   - % (self.sid, repr(self.name), self.sid_child))
1018   - if self.sid_child != NOSTREAM:
1019   - # if child SID is not NOSTREAM, then this entry is a storage.
1020   - # Let's walk through the tree of children to fill the kids list:
1021   - self.append_kids(self.sid_child)
1022   -
1023   - # Note from OpenOffice documentation: the safest way is to
1024   - # recreate the tree because some implementations may store broken
1025   - # red-black trees...
1026   -
1027   - # in the OLE file, entries are sorted on (length, name).
1028   - # for convenience, we sort them on name instead:
1029   - # (see rich comparison methods in this class)
1030   - self.kids.sort()
1031   -
1032   -
1033   - def append_kids(self, child_sid):
1034   - """
1035   - Walk through red-black tree of children of this directory entry to add
1036   - all of them to the kids list. (recursive method)
1037   -
1038   - :param child_sid: index of child directory entry to use, or None when called
1039   - first time for the root. (only used during recursion)
1040   - """
1041   - log.debug('append_kids: child_sid=%d' % child_sid)
1042   - #[PL] this method was added to use simple recursion instead of a complex
1043   - # algorithm.
1044   - # if this is not a storage or a leaf of the tree, nothing to do:
1045   - if child_sid == NOSTREAM:
1046   - return
1047   - # check if child SID is in the proper range:
1048   - if child_sid<0 or child_sid>=len(self.olefile.direntries):
1049   - self.olefile._raise_defect(DEFECT_INCORRECT, 'OLE DirEntry index out of range')
1050   - else:
1051   - # get child direntry:
1052   - child = self.olefile._load_direntry(child_sid) #direntries[child_sid]
1053   - log.debug('append_kids: child_sid=%d - %s - sid_left=%d, sid_right=%d, sid_child=%d'
1054   - % (child.sid, repr(child.name), child.sid_left, child.sid_right, child.sid_child))
1055   - # the directory entries are organized as a red-black tree.
1056   - # (cf. Wikipedia for details)
1057   - # First walk through left side of the tree:
1058   - self.append_kids(child.sid_left)
1059   - # Check if its name is not already used (case-insensitive):
1060   - name_lower = child.name.lower()
1061   - if name_lower in self.kids_dict:
1062   - self.olefile._raise_defect(DEFECT_INCORRECT,
1063   - "Duplicate filename in OLE storage")
1064   - # Then the child_sid OleDirectoryEntry object is appended to the
1065   - # kids list and dictionary:
1066   - self.kids.append(child)
1067   - self.kids_dict[name_lower] = child
1068   - # Check if kid was not already referenced in a storage:
1069   - if child.used:
1070   - self.olefile._raise_defect(DEFECT_INCORRECT,
1071   - 'OLE Entry referenced more than once')
1072   - child.used = True
1073   - # Finally walk through right side of the tree:
1074   - self.append_kids(child.sid_right)
1075   - # Afterwards build kid's own tree if it's also a storage:
1076   - child.build_storage_tree()
1077   -
1078   -
1079   - def __eq__(self, other):
1080   - "Compare entries by name"
1081   - return self.name == other.name
1082   -
1083   - def __lt__(self, other):
1084   - "Compare entries by name"
1085   - return self.name < other.name
1086   -
1087   - def __ne__(self, other):
1088   - return not self.__eq__(other)
1089   -
1090   - def __le__(self, other):
1091   - return self.__eq__(other) or self.__lt__(other)
1092   -
1093   - # Reflected __lt__() and __le__() will be used for __gt__() and __ge__()
1094   -
1095   - #TODO: replace by the same function as MS implementation ?
1096   - # (order by name length first, then case-insensitive order)
1097   -
1098   -
1099   - def dump(self, tab = 0):
1100   - "Dump this entry, and all its subentries (for debug purposes only)"
1101   - TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)",
1102   - "(property)", "(root)"]
1103   - print(" "*tab + repr(self.name), TYPES[self.entry_type], end=' ')
1104   - if self.entry_type in (STGTY_STREAM, STGTY_ROOT):
1105   - print(self.size, "bytes", end=' ')
1106   - print()
1107   - if self.entry_type in (STGTY_STORAGE, STGTY_ROOT) and self.clsid:
1108   - print(" "*tab + "{%s}" % self.clsid)
1109   -
1110   - for kid in self.kids:
1111   - kid.dump(tab + 2)
1112   -
1113   -
1114   - def getmtime(self):
1115   - """
1116   - Return modification time of a directory entry.
1117   -
1118   - :returns: None if modification time is null, a python datetime object
1119   - otherwise (UTC timezone)
1120   -
1121   - new in version 0.26
1122   - """
1123   - if self.modifyTime == 0:
1124   - return None
1125   - return filetime2datetime(self.modifyTime)
1126   -
1127   -
1128   - def getctime(self):
1129   - """
1130   - Return creation time of a directory entry.
1131   -
1132   - :returns: None if modification time is null, a python datetime object
1133   - otherwise (UTC timezone)
1134   -
1135   - new in version 0.26
1136   - """
1137   - if self.createTime == 0:
1138   - return None
1139   - return filetime2datetime(self.createTime)
1140   -
1141   -
1142   -#--- OleFileIO ----------------------------------------------------------------
1143   -
1144   -class OleFileIO:
1145   - """
1146   - OLE container object
1147   -
1148   - This class encapsulates the interface to an OLE 2 structured
1149   - storage file. Use the listdir and openstream methods to
1150   - access the contents of this file.
1151   -
1152   - Object names are given as a list of strings, one for each subentry
1153   - level. The root entry should be omitted. For example, the following
1154   - code extracts all image streams from a Microsoft Image Composer file::
1155   -
1156   - ole = OleFileIO("fan.mic")
1157   -
1158   - for entry in ole.listdir():
1159   - if entry[1:2] == "Image":
1160   - fin = ole.openstream(entry)
1161   - fout = open(entry[0:1], "wb")
1162   - while True:
1163   - s = fin.read(8192)
1164   - if not s:
1165   - break
1166   - fout.write(s)
1167   -
1168   - You can use the viewer application provided with the Python Imaging
1169   - Library to view the resulting files (which happens to be standard
1170   - TIFF files).
1171   - """
1172   -
1173   - def __init__(self, filename=None, raise_defects=DEFECT_FATAL,
1174   - write_mode=False, debug=False, path_encoding=DEFAULT_PATH_ENCODING):
1175   - """
1176   - Constructor for the OleFileIO class.
1177   -
1178   - :param filename: file to open.
1179   -
1180   - - if filename is a string smaller than 1536 bytes, it is the path
1181   - of the file to open. (bytes or unicode string)
1182   - - if filename is a string longer than 1535 bytes, it is parsed
1183   - as the content of an OLE file in memory. (bytes type only)
1184   - - if filename is a file-like object (with read, seek and tell methods),
1185   - it is parsed as-is.
1186   -
1187   - :param raise_defects: minimal level for defects to be raised as exceptions.
1188   - (use DEFECT_FATAL for a typical application, DEFECT_INCORRECT for a
1189   - security-oriented application, see source code for details)
1190   -
1191   - :param write_mode: bool, if True the file is opened in read/write mode instead
1192   - of read-only by default.
1193   -
1194   - :param debug: bool, set debug mode (deprecated, not used anymore)
1195   -
1196   - :param path_encoding: None or str, name of the codec to use for path
1197   - names (streams and storages), or None for Unicode.
1198   - Unicode by default on Python 3+, UTF-8 on Python 2.x.
1199   - (new in olefile 0.42, was hardcoded to Latin-1 until olefile v0.41)
1200   - """
1201   - # minimal level for defects to be raised as exceptions:
1202   - self._raise_defects_level = raise_defects
1203   - #: list of defects/issues not raised as exceptions:
1204   - #: tuples of (exception type, message)
1205   - self.parsing_issues = []
1206   - self.write_mode = write_mode
1207   - self.path_encoding = path_encoding
1208   - self._filesize = None
1209   - self.fp = None
1210   - if filename:
1211   - self.open(filename, write_mode=write_mode)
1212   -
1213   -
1214   - def _raise_defect(self, defect_level, message, exception_type=IOError):
1215   - """
1216   - This method should be called for any defect found during file parsing.
1217   - It may raise an IOError exception according to the minimal level chosen
1218   - for the OleFileIO object.
1219   -
1220   - :param defect_level: defect level, possible values are:
1221   -
1222   - - DEFECT_UNSURE : a case which looks weird, but not sure it's a defect
1223   - - DEFECT_POTENTIAL : a potential defect
1224   - - DEFECT_INCORRECT : an error according to specifications, but parsing can go on
1225   - - DEFECT_FATAL : an error which cannot be ignored, parsing is impossible
1226   -
1227   - :param message: string describing the defect, used with raised exception.
1228   - :param exception_type: exception class to be raised, IOError by default
1229   - """
1230   - # added by [PL]
1231   - if defect_level >= self._raise_defects_level:
1232   - log.error(message)
1233   - raise exception_type(message)
1234   - else:
1235   - # just record the issue, no exception raised:
1236   - self.parsing_issues.append((exception_type, message))
1237   - log.warning(message)
1238   -
1239   -
1240   - def _decode_utf16_str(self, utf16_str, errors='replace'):
1241   - """
1242   - Decode a string encoded in UTF-16 LE format, as found in the OLE
1243   - directory or in property streams. Return a string encoded
1244   - according to the path_encoding specified for the OleFileIO object.
1245   -
1246   - :param utf16_str: bytes string encoded in UTF-16 LE format
1247   - :param errors: str, see python documentation for str.decode()
1248   - :return: str, encoded according to path_encoding
1249   - """
1250   - unicode_str = utf16_str.decode('UTF-16LE', errors)
1251   - if self.path_encoding:
1252   - # an encoding has been specified for path names:
1253   - return unicode_str.encode(self.path_encoding, errors)
1254   - else:
1255   - # path_encoding=None, return the Unicode string as-is:
1256   - return unicode_str
1257   -
1258   -
1259   - def open(self, filename, write_mode=False):
1260   - """
1261   - Open an OLE2 file in read-only or read/write mode.
1262   - Read and parse the header, FAT and directory.
1263   -
1264   - :param filename: string-like or file-like object, OLE file to parse
1265   -
1266   - - if filename is a string smaller than 1536 bytes, it is the path
1267   - of the file to open. (bytes or unicode string)
1268   - - if filename is a string longer than 1535 bytes, it is parsed
1269   - as the content of an OLE file in memory. (bytes type only)
1270   - - if filename is a file-like object (with read, seek and tell methods),
1271   - it is parsed as-is.
1272   -
1273   - :param write_mode: bool, if True the file is opened in read/write mode instead
1274   - of read-only by default. (ignored if filename is not a path)
1275   - """
1276   - self.write_mode = write_mode
1277   - #[PL] check if filename is a string-like or file-like object:
1278   - # (it is better to check for a read() method)
1279   - if hasattr(filename, 'read'):
1280   - #TODO: also check seek and tell methods?
1281   - # file-like object: use it directly
1282   - self.fp = filename
1283   - elif isinstance(filename, bytes) and len(filename) >= MINIMAL_OLEFILE_SIZE:
1284   - # filename is a bytes string containing the OLE file to be parsed:
1285   - # convert it to BytesIO
1286   - self.fp = io.BytesIO(filename)
1287   - else:
1288   - # string-like object: filename of file on disk
1289   - if self.write_mode:
1290   - # open file in mode 'read with update, binary'
1291   - # According to https://docs.python.org/2/library/functions.html#open
1292   - # 'w' would truncate the file, 'a' may only append on some Unixes
1293   - mode = 'r+b'
1294   - else:
1295   - # read-only mode by default
1296   - mode = 'rb'
1297   - self.fp = open(filename, mode)
1298   - # obtain the filesize by using seek and tell, which should work on most
1299   - # file-like objects:
1300   - #TODO: do it above, using getsize with filename when possible?
1301   - #TODO: fix code to fail with clear exception when filesize cannot be obtained
1302   - filesize=0
1303   - self.fp.seek(0, os.SEEK_END)
1304   - try:
1305   - filesize = self.fp.tell()
1306   - finally:
1307   - self.fp.seek(0)
1308   - self._filesize = filesize
1309   - log.debug('File size: %d bytes (%Xh)' % (self._filesize, self._filesize))
1310   -
1311   - # lists of streams in FAT and MiniFAT, to detect duplicate references
1312   - # (list of indexes of first sectors of each stream)
1313   - self._used_streams_fat = []
1314   - self._used_streams_minifat = []
1315   -
1316   - header = self.fp.read(512)
1317   -
1318   - if len(header) != 512 or header[:8] != MAGIC:
1319   - log.debug('Magic = %r instead of %r' % (header[:8], MAGIC))
1320   - self._raise_defect(DEFECT_FATAL, "not an OLE2 structured storage file")
1321   -
1322   - # [PL] header structure according to AAF specifications:
1323   - ##Header
1324   - ##struct StructuredStorageHeader { // [offset from start (bytes), length (bytes)]
1325   - ##BYTE _abSig[8]; // [00H,08] {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1,
1326   - ## // 0x1a, 0xe1} for current version
1327   - ##CLSID _clsid; // [08H,16] reserved must be zero (WriteClassStg/
1328   - ## // GetClassFile uses root directory class id)
1329   - ##USHORT _uMinorVersion; // [18H,02] minor version of the format: 33 is
1330   - ## // written by reference implementation
1331   - ##USHORT _uDllVersion; // [1AH,02] major version of the dll/format: 3 for
1332   - ## // 512-byte sectors, 4 for 4 KB sectors
1333   - ##USHORT _uByteOrder; // [1CH,02] 0xFFFE: indicates Intel byte-ordering
1334   - ##USHORT _uSectorShift; // [1EH,02] size of sectors in power-of-two;
1335   - ## // typically 9 indicating 512-byte sectors
1336   - ##USHORT _uMiniSectorShift; // [20H,02] size of mini-sectors in power-of-two;
1337   - ## // typically 6 indicating 64-byte mini-sectors
1338   - ##USHORT _usReserved; // [22H,02] reserved, must be zero
1339   - ##ULONG _ulReserved1; // [24H,04] reserved, must be zero
1340   - ##FSINDEX _csectDir; // [28H,04] must be zero for 512-byte sectors,
1341   - ## // number of SECTs in directory chain for 4 KB
1342   - ## // sectors
1343   - ##FSINDEX _csectFat; // [2CH,04] number of SECTs in the FAT chain
1344   - ##SECT _sectDirStart; // [30H,04] first SECT in the directory chain
1345   - ##DFSIGNATURE _signature; // [34H,04] signature used for transactions; must
1346   - ## // be zero. The reference implementation
1347   - ## // does not support transactions
1348   - ##ULONG _ulMiniSectorCutoff; // [38H,04] maximum size for a mini stream;
1349   - ## // typically 4096 bytes
1350   - ##SECT _sectMiniFatStart; // [3CH,04] first SECT in the MiniFAT chain
1351   - ##FSINDEX _csectMiniFat; // [40H,04] number of SECTs in the MiniFAT chain
1352   - ##SECT _sectDifStart; // [44H,04] first SECT in the DIFAT chain
1353   - ##FSINDEX _csectDif; // [48H,04] number of SECTs in the DIFAT chain
1354   - ##SECT _sectFat[109]; // [4CH,436] the SECTs of first 109 FAT sectors
1355   - ##};
1356   -
1357   - # [PL] header decoding:
1358   - # '<' indicates little-endian byte ordering for Intel (cf. struct module help)
1359   - fmt_header = '<8s16sHHHHHHLLLLLLLLLL'
1360   - header_size = struct.calcsize(fmt_header)
1361   - log.debug( "fmt_header size = %d, +FAT = %d" % (header_size, header_size + 109*4) )
1362   - header1 = header[:header_size]
1363   - (
1364   - self.header_signature,
1365   - self.header_clsid,
1366   - self.minor_version,
1367   - self.dll_version,
1368   - self.byte_order,
1369   - self.sector_shift,
1370   - self.mini_sector_shift,
1371   - self.reserved1,
1372   - self.reserved2,
1373   - self.num_dir_sectors,
1374   - self.num_fat_sectors,
1375   - self.first_dir_sector,
1376   - self.transaction_signature_number,
1377   - self.mini_stream_cutoff_size,
1378   - self.first_mini_fat_sector,
1379   - self.num_mini_fat_sectors,
1380   - self.first_difat_sector,
1381   - self.num_difat_sectors
1382   - ) = struct.unpack(fmt_header, header1)
1383   - log.debug( struct.unpack(fmt_header, header1))
1384   -
1385   - if self.header_signature != MAGIC:
1386   - # OLE signature should always be present
1387   - self._raise_defect(DEFECT_FATAL, "incorrect OLE signature")
1388   - if self.header_clsid != bytearray(16):
1389   - # according to AAF specs, CLSID should always be zero
1390   - self._raise_defect(DEFECT_INCORRECT, "incorrect CLSID in OLE header")
1391   - log.debug( "Minor Version = %d" % self.minor_version )
1392   - # TODO: according to MS-CFB, minor version should be 0x003E
1393   - log.debug( "DLL Version = %d (expected: 3 or 4)" % self.dll_version )
1394   - if self.dll_version not in [3, 4]:
1395   - # version 3: usual format, 512 bytes per sector
1396   - # version 4: large format, 4K per sector
1397   - self._raise_defect(DEFECT_INCORRECT, "incorrect DllVersion in OLE header")
1398   - log.debug( "Byte Order = %X (expected: FFFE)" % self.byte_order )
1399   - if self.byte_order != 0xFFFE:
1400   - # For now only common little-endian documents are handled correctly
1401   - self._raise_defect(DEFECT_INCORRECT, "incorrect ByteOrder in OLE header")
1402   - # TODO: add big-endian support for documents created on Mac ?
1403   - # But according to [MS-CFB] ? v20140502, ByteOrder MUST be 0xFFFE.
1404   - self.sector_size = 2**self.sector_shift
1405   - log.debug( "Sector Size = %d bytes (expected: 512 or 4096)" % self.sector_size )
1406   - if self.sector_size not in [512, 4096]:
1407   - self._raise_defect(DEFECT_INCORRECT, "incorrect sector_size in OLE header")
1408   - if (self.dll_version==3 and self.sector_size!=512) \
1409   - or (self.dll_version==4 and self.sector_size!=4096):
1410   - self._raise_defect(DEFECT_INCORRECT, "sector_size does not match DllVersion in OLE header")
1411   - self.mini_sector_size = 2**self.mini_sector_shift
1412   - log.debug( "MiniFAT Sector Size = %d bytes (expected: 64)" % self.mini_sector_size )
1413   - if self.mini_sector_size not in [64]:
1414   - self._raise_defect(DEFECT_INCORRECT, "incorrect mini_sector_size in OLE header")
1415   - if self.reserved1 != 0 or self.reserved2 != 0:
1416   - self._raise_defect(DEFECT_INCORRECT, "incorrect OLE header (non-null reserved bytes)")
1417   - log.debug( "Number of Directory sectors = %d" % self.num_dir_sectors )
1418   - # Number of directory sectors (only allowed if DllVersion != 3)
1419   - if self.sector_size==512 and self.num_dir_sectors!=0:
1420   - self._raise_defect(DEFECT_INCORRECT, "incorrect number of directory sectors in OLE header")
1421   - log.debug( "Number of FAT sectors = %d" % self.num_fat_sectors )
1422   - # num_fat_sectors = number of FAT sectors in the file
1423   - log.debug( "First Directory sector = %Xh" % self.first_dir_sector )
1424   - # first_dir_sector = 1st sector containing the directory
1425   - log.debug( "Transaction Signature Number = %d" % self.transaction_signature_number )
1426   - # Signature should be zero, BUT some implementations do not follow this
1427   - # rule => only a potential defect:
1428   - # (according to MS-CFB, may be != 0 for applications supporting file
1429   - # transactions)
1430   - if self.transaction_signature_number != 0:
1431   - self._raise_defect(DEFECT_POTENTIAL, "incorrect OLE header (transaction_signature_number>0)")
1432   - log.debug( "Mini Stream cutoff size = %Xh (expected: 1000h)" % self.mini_stream_cutoff_size )
1433   - # MS-CFB: This integer field MUST be set to 0x00001000. This field
1434   - # specifies the maximum size of a user-defined data stream allocated
1435   - # from the mini FAT and mini stream, and that cutoff is 4096 bytes.
1436   - # Any user-defined data stream larger than or equal to this cutoff size
1437   - # must be allocated as normal sectors from the FAT.
1438   - if self.mini_stream_cutoff_size != 0x1000:
1439   - self._raise_defect(DEFECT_INCORRECT, "incorrect mini_stream_cutoff_size in OLE header")
1440   - # if no exception is raised, the cutoff size is fixed to 0x1000
1441   - log.warning('Fixing the mini_stream_cutoff_size to 4096 (mandatory value) instead of %d' %
1442   - self.mini_stream_cutoff_size)
1443   - self.mini_stream_cutoff_size = 0x1000
1444   - # TODO: check if these values are OK
1445   - log.debug( "First MiniFAT sector = %Xh" % self.first_mini_fat_sector )
1446   - log.debug( "Number of MiniFAT sectors = %d" % self.num_mini_fat_sectors )
1447   - log.debug( "First DIFAT sector = %Xh" % self.first_difat_sector )
1448   - log.debug( "Number of DIFAT sectors = %d" % self.num_difat_sectors )
1449   -
1450   - # calculate the number of sectors in the file
1451   - # (-1 because header doesn't count)
1452   - self.nb_sect = ( (filesize + self.sector_size-1) // self.sector_size) - 1
1453   - log.debug( "Maximum number of sectors in the file: %d (%Xh)" % (self.nb_sect, self.nb_sect))
1454   - #TODO: change this test, because an OLE file MAY contain other data
1455   - # after the last sector.
1456   -
1457   - # file clsid
1458   - self.header_clsid = _clsid(header[8:24])
1459   -
1460   - #TODO: remove redundant attributes, and fix the code which uses them?
1461   - self.sectorsize = self.sector_size #1 << i16(header, 30)
1462   - self.minisectorsize = self.mini_sector_size #1 << i16(header, 32)
1463   - self.minisectorcutoff = self.mini_stream_cutoff_size # i32(header, 56)
1464   -
1465   - # check known streams for duplicate references (these are always in FAT,
1466   - # never in MiniFAT):
1467   - self._check_duplicate_stream(self.first_dir_sector)
1468   - # check MiniFAT only if it is not empty:
1469   - if self.num_mini_fat_sectors:
1470   - self._check_duplicate_stream(self.first_mini_fat_sector)
1471   - # check DIFAT only if it is not empty:
1472   - if self.num_difat_sectors:
1473   - self._check_duplicate_stream(self.first_difat_sector)
1474   -
1475   - # Load file allocation tables
1476   - self.loadfat(header)
1477   - # Load directory. This sets both the direntries list (ordered by sid)
1478   - # and the root (ordered by hierarchy) members.
1479   - self.loaddirectory(self.first_dir_sector)
1480   - self.ministream = None
1481   - self.minifatsect = self.first_mini_fat_sector
1482   -
1483   -
1484   - def close(self):
1485   - """
1486   - close the OLE file, to release the file object
1487   - """
1488   - self.fp.close()
1489   -
1490   -
1491   - def _check_duplicate_stream(self, first_sect, minifat=False):
1492   - """
1493   - Checks if a stream has not been already referenced elsewhere.
1494   - This method should only be called once for each known stream, and only
1495   - if stream size is not null.
1496   -
1497   - :param first_sect: int, index of first sector of the stream in FAT
1498   - :param minifat: bool, if True, stream is located in the MiniFAT, else in the FAT
1499   - """
1500   - if minifat:
1501   - log.debug('_check_duplicate_stream: sect=%Xh in MiniFAT' % first_sect)
1502   - used_streams = self._used_streams_minifat
1503   - else:
1504   - log.debug('_check_duplicate_stream: sect=%Xh in FAT' % first_sect)
1505   - # some values can be safely ignored (not a real stream):
1506   - if first_sect in (DIFSECT,FATSECT,ENDOFCHAIN,FREESECT):
1507   - return
1508   - used_streams = self._used_streams_fat
1509   - #TODO: would it be more efficient using a dict or hash values, instead
1510   - # of a list of long ?
1511   - if first_sect in used_streams:
1512   - self._raise_defect(DEFECT_INCORRECT, 'Stream referenced twice')
1513   - else:
1514   - used_streams.append(first_sect)
1515   -
1516   -
1517   - def dumpfat(self, fat, firstindex=0):
1518   - """
1519   - Display a part of FAT in human-readable form for debugging purposes
1520   - """
1521   - # dictionary to convert special FAT values in human-readable strings
1522   - VPL = 8 # values per line (8+1 * 8+1 = 81)
1523   - fatnames = {
1524   - FREESECT: "..free..",
1525   - ENDOFCHAIN: "[ END. ]",
1526   - FATSECT: "FATSECT ",
1527   - DIFSECT: "DIFSECT "
1528   - }
1529   - nbsect = len(fat)
1530   - nlines = (nbsect+VPL-1)//VPL
1531   - print("index", end=" ")
1532   - for i in range(VPL):
1533   - print("%8X" % i, end=" ")
1534   - print()
1535   - for l in range(nlines):
1536   - index = l*VPL
1537   - print("%6X:" % (firstindex+index), end=" ")
1538   - for i in range(index, index+VPL):
1539   - if i>=nbsect:
1540   - break
1541   - sect = fat[i]
1542   - aux = sect & 0xFFFFFFFF # JYTHON-WORKAROUND
1543   - if aux in fatnames:
1544   - name = fatnames[aux]
1545   - else:
1546   - if sect == i+1:
1547   - name = " --->"
1548   - else:
1549   - name = "%8X" % sect
1550   - print(name, end=" ")
1551   - print()
1552   -
1553   -
1554   - def dumpsect(self, sector, firstindex=0):
1555   - """
1556   - Display a sector in a human-readable form, for debugging purposes
1557   - """
1558   - VPL=8 # number of values per line (8+1 * 8+1 = 81)
1559   - tab = array.array(UINT32, sector)
1560   - if sys.byteorder == 'big':
1561   - tab.byteswap()
1562   - nbsect = len(tab)
1563   - nlines = (nbsect+VPL-1)//VPL
1564   - print("index", end=" ")
1565   - for i in range(VPL):
1566   - print("%8X" % i, end=" ")
1567   - print()
1568   - for l in range(nlines):
1569   - index = l*VPL
1570   - print("%6X:" % (firstindex+index), end=" ")
1571   - for i in range(index, index+VPL):
1572   - if i>=nbsect:
1573   - break
1574   - sect = tab[i]
1575   - name = "%8X" % sect
1576   - print(name, end=" ")
1577   - print()
1578   -
1579   - def sect2array(self, sect):
1580   - """
1581   - convert a sector to an array of 32 bits unsigned integers,
1582   - swapping bytes on big endian CPUs such as PowerPC (old Macs)
1583   - """
1584   - a = array.array(UINT32, sect)
1585   - # if CPU is big endian, swap bytes:
1586   - if sys.byteorder == 'big':
1587   - a.byteswap()
1588   - return a
1589   -
1590   -
1591   - def loadfat_sect(self, sect):
1592   - """
1593   - Adds the indexes of the given sector to the FAT
1594   -
1595   - :param sect: string containing the first FAT sector, or array of long integers
1596   - :returns: index of last FAT sector.
1597   - """
1598   - # a FAT sector is an array of ulong integers.
1599   - if isinstance(sect, array.array):
1600   - # if sect is already an array it is directly used
1601   - fat1 = sect
1602   - else:
1603   - # if it's a raw sector, it is parsed in an array
1604   - fat1 = self.sect2array(sect)
1605   - # Display the sector contents only if the logging level is debug:
1606   - if log.isEnabledFor(logging.DEBUG):
1607   - self.dumpsect(sect)
1608   - # The FAT is a sector chain starting at the first index of itself.
1609   - # initialize isect, just in case:
1610   - isect = None
1611   - for isect in fat1:
1612   - isect = isect & 0xFFFFFFFF # JYTHON-WORKAROUND
1613   - log.debug("isect = %X" % isect)
1614   - if isect == ENDOFCHAIN or isect == FREESECT:
1615   - # the end of the sector chain has been reached
1616   - log.debug("found end of sector chain")
1617   - break
1618   - # read the FAT sector
1619   - s = self.getsect(isect)
1620   - # parse it as an array of 32 bits integers, and add it to the
1621   - # global FAT array
1622   - nextfat = self.sect2array(s)
1623   - self.fat = self.fat + nextfat
1624   - return isect
1625   -
1626   -
1627   - def loadfat(self, header):
1628   - """
1629   - Load the FAT table.
1630   - """
1631   - # The 1st sector of the file contains sector numbers for the first 109
1632   - # FAT sectors, right after the header which is 76 bytes long.
1633   - # (always 109, whatever the sector size: 512 bytes = 76+4*109)
1634   - # Additional sectors are described by DIF blocks
1635   -
1636   - log.debug('Loading the FAT table, starting with the 1st sector after the header')
1637   - sect = header[76:512]
1638   - log.debug( "len(sect)=%d, so %d integers" % (len(sect), len(sect)//4) )
1639   - #fat = []
1640   - # [PL] FAT is an array of 32 bits unsigned ints, it's more effective
1641   - # to use an array than a list in Python.
1642   - # It's initialized as empty first:
1643   - self.fat = array.array(UINT32)
1644   - self.loadfat_sect(sect)
1645   - #self.dumpfat(self.fat)
1646   -## for i in range(0, len(sect), 4):
1647   -## ix = i32(sect, i)
1648   -## #[PL] if ix == -2 or ix == -1: # ix == 0xFFFFFFFE or ix == 0xFFFFFFFF:
1649   -## if ix == 0xFFFFFFFE or ix == 0xFFFFFFFF:
1650   -## break
1651   -## s = self.getsect(ix)
1652   -## #fat = fat + [i32(s, i) for i in range(0, len(s), 4)]
1653   -## fat = fat + array.array(UINT32, s)
1654   - if self.num_difat_sectors != 0:
1655   - log.debug('DIFAT is used, because file size > 6.8MB.')
1656   - # [PL] There's a DIFAT because file is larger than 6.8MB
1657   - # some checks just in case:
1658   - if self.num_fat_sectors <= 109:
1659   - # there must be at least 109 blocks in header and the rest in
1660   - # DIFAT, so number of sectors must be >109.
1661   - self._raise_defect(DEFECT_INCORRECT, 'incorrect DIFAT, not enough sectors')
1662   - if self.first_difat_sector >= self.nb_sect:
1663   - # initial DIFAT block index must be valid
1664   - self._raise_defect(DEFECT_FATAL, 'incorrect DIFAT, first index out of range')
1665   - log.debug( "DIFAT analysis..." )
1666   - # We compute the necessary number of DIFAT sectors :
1667   - # Number of pointers per DIFAT sector = (sectorsize/4)-1
1668   - # (-1 because the last pointer is the next DIFAT sector number)
1669   - nb_difat_sectors = (self.sectorsize//4)-1
1670   - # (if 512 bytes: each DIFAT sector = 127 pointers + 1 towards next DIFAT sector)
1671   - nb_difat = (self.num_fat_sectors-109 + nb_difat_sectors-1)//nb_difat_sectors
1672   - log.debug( "nb_difat = %d" % nb_difat )
1673   - if self.num_difat_sectors != nb_difat:
1674   - raise IOError('incorrect DIFAT')
1675   - isect_difat = self.first_difat_sector
1676   - for i in iterrange(nb_difat):
1677   - log.debug( "DIFAT block %d, sector %X" % (i, isect_difat) )
1678   - #TODO: check if corresponding FAT SID = DIFSECT
1679   - sector_difat = self.getsect(isect_difat)
1680   - difat = self.sect2array(sector_difat)
1681   - # Display the sector contents only if the logging level is debug:
1682   - if log.isEnabledFor(logging.DEBUG):
1683   - self.dumpsect(sector_difat)
1684   - self.loadfat_sect(difat[:nb_difat_sectors])
1685   - # last DIFAT pointer is next DIFAT sector:
1686   - isect_difat = difat[nb_difat_sectors]
1687   - log.debug( "next DIFAT sector: %X" % isect_difat )
1688   - # checks:
1689   - if isect_difat not in [ENDOFCHAIN, FREESECT]:
1690   - # last DIFAT pointer value must be ENDOFCHAIN or FREESECT
1691   - raise IOError('incorrect end of DIFAT')
1692   -## if len(self.fat) != self.num_fat_sectors:
1693   -## # FAT should contain num_fat_sectors blocks
1694   -## print("FAT length: %d instead of %d" % (len(self.fat), self.num_fat_sectors))
1695   -## raise IOError('incorrect DIFAT')
1696   - else:
1697   - log.debug('No DIFAT, because file size < 6.8MB.')
1698   - # since FAT is read from fixed-size sectors, it may contain more values
1699   - # than the actual number of sectors in the file.
1700   - # Keep only the relevant sector indexes:
1701   - if len(self.fat) > self.nb_sect:
1702   - log.debug('len(fat)=%d, shrunk to nb_sect=%d' % (len(self.fat), self.nb_sect))
1703   - self.fat = self.fat[:self.nb_sect]
1704   - log.debug('FAT references %d sectors / Maximum %d sectors in file' % (len(self.fat), self.nb_sect))
1705   - # Display the FAT contents only if the logging level is debug:
1706   - if log.isEnabledFor(logging.DEBUG):
1707   - log.debug('\nFAT:')
1708   - self.dumpfat(self.fat)
1709   -
1710   -
1711   - def loadminifat(self):
1712   - """
1713   - Load the MiniFAT table.
1714   - """
1715   - # MiniFAT is stored in a standard sub-stream, pointed to by a header
1716   - # field.
1717   - # NOTE: there are two sizes to take into account for this stream:
1718   - # 1) Stream size is calculated according to the number of sectors
1719   - # declared in the OLE header. This allocated stream may be more than
1720   - # needed to store the actual sector indexes.
1721   - # (self.num_mini_fat_sectors is the number of sectors of size self.sector_size)
1722   - stream_size = self.num_mini_fat_sectors * self.sector_size
1723   - # 2) Actually used size is calculated by dividing the MiniStream size
1724   - # (given by root entry size) by the size of mini sectors, *4 for
1725   - # 32 bits indexes:
1726   - nb_minisectors = (self.root.size + self.mini_sector_size-1) // self.mini_sector_size
1727   - used_size = nb_minisectors * 4
1728   - log.debug('loadminifat(): minifatsect=%d, nb FAT sectors=%d, used_size=%d, stream_size=%d, nb MiniSectors=%d' %
1729   - (self.minifatsect, self.num_mini_fat_sectors, used_size, stream_size, nb_minisectors))
1730   - if used_size > stream_size:
1731   - # This is not really a problem, but may indicate a wrong implementation:
1732   - self._raise_defect(DEFECT_INCORRECT, 'OLE MiniStream is larger than MiniFAT')
1733   - # In any case, first read stream_size:
1734   - s = self._open(self.minifatsect, stream_size, force_FAT=True).read()
1735   - #[PL] Old code replaced by an array:
1736   - #self.minifat = [i32(s, i) for i in range(0, len(s), 4)]
1737   - self.minifat = self.sect2array(s)
1738   - # Then shrink the array to used size, to avoid indexes out of MiniStream:
1739   - log.debug('MiniFAT shrunk from %d to %d sectors' % (len(self.minifat), nb_minisectors))
1740   - self.minifat = self.minifat[:nb_minisectors]
1741   - log.debug('loadminifat(): len=%d' % len(self.minifat))
1742   - # Display the FAT contents only if the logging level is debug:
1743   - if log.isEnabledFor(logging.DEBUG):
1744   - log.debug('\nMiniFAT:')
1745   - self.dumpfat(self.minifat)
1746   -
1747   - def getsect(self, sect):
1748   - """
1749   - Read given sector from file on disk.
1750   -
1751   - :param sect: int, sector index
1752   - :returns: a string containing the sector data.
1753   - """
1754   - # From [MS-CFB]: A sector number can be converted into a byte offset
1755   - # into the file by using the following formula:
1756   - # (sector number + 1) x Sector Size.
1757   - # This implies that sector #0 of the file begins at byte offset Sector
1758   - # Size, not at 0.
1759   -
1760   - # [PL] the original code in PIL was wrong when sectors are 4KB instead of
1761   - # 512 bytes:
1762   - #self.fp.seek(512 + self.sectorsize * sect)
1763   - #[PL]: added safety checks:
1764   - #print("getsect(%X)" % sect)
1765   - try:
1766   - self.fp.seek(self.sectorsize * (sect+1))
1767   - except:
1768   - log.debug('getsect(): sect=%X, seek=%d, filesize=%d' %
1769   - (sect, self.sectorsize*(sect+1), self._filesize))
1770   - self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range')
1771   - sector = self.fp.read(self.sectorsize)
1772   - if len(sector) != self.sectorsize:
1773   - log.debug('getsect(): sect=%X, read=%d, sectorsize=%d' %
1774   - (sect, len(sector), self.sectorsize))
1775   - self._raise_defect(DEFECT_FATAL, 'incomplete OLE sector')
1776   - return sector
1777   -
1778   -
1779   - def write_sect(self, sect, data, padding=b'\x00'):
1780   - """
1781   - Write given sector to file on disk.
1782   -
1783   - :param sect: int, sector index
1784   - :param data: bytes, sector data
1785   - :param padding: single byte, padding character if data < sector size
1786   - """
1787   - if not isinstance(data, bytes):
1788   - raise TypeError("write_sect: data must be a bytes string")
1789   - if not isinstance(padding, bytes) or len(padding)!=1:
1790   - raise TypeError("write_sect: padding must be a bytes string of 1 char")
1791   - #TODO: we could allow padding=None for no padding at all
1792   - try:
1793   - self.fp.seek(self.sectorsize * (sect+1))
1794   - except:
1795   - log.debug('write_sect(): sect=%X, seek=%d, filesize=%d' %
1796   - (sect, self.sectorsize*(sect+1), self._filesize))
1797   - self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range')
1798   - if len(data) < self.sectorsize:
1799   - # add padding
1800   - data += padding * (self.sectorsize - len(data))
1801   - elif len(data) < self.sectorsize:
1802   - raise ValueError("Data is larger than sector size")
1803   - self.fp.write(data)
1804   -
1805   -
1806   - def loaddirectory(self, sect):
1807   - """
1808   - Load the directory.
1809   -
1810   - :param sect: sector index of directory stream.
1811   - """
1812   - log.debug('Loading the Directory:')
1813   - # The directory is stored in a standard
1814   - # substream, independent of its size.
1815   -
1816   - # open directory stream as a read-only file:
1817   - # (stream size is not known in advance)
1818   - self.directory_fp = self._open(sect)
1819   -
1820   - #[PL] to detect malformed documents and avoid DoS attacks, the maximum
1821   - # number of directory entries can be calculated:
1822   - max_entries = self.directory_fp.size // 128
1823   - log.debug('loaddirectory: size=%d, max_entries=%d' %
1824   - (self.directory_fp.size, max_entries))
1825   -
1826   - # Create list of directory entries
1827   - #self.direntries = []
1828   - # We start with a list of "None" object
1829   - self.direntries = [None] * max_entries
1830   -## for sid in iterrange(max_entries):
1831   -## entry = fp.read(128)
1832   -## if not entry:
1833   -## break
1834   -## self.direntries.append(OleDirectoryEntry(entry, sid, self))
1835   - # load root entry:
1836   - root_entry = self._load_direntry(0)
1837   - # Root entry is the first entry:
1838   - self.root = self.direntries[0]
1839   - # TODO: read ALL directory entries (ignore bad entries?)
1840   - # TODO: adapt build_storage_tree to avoid duplicate reads
1841   - # for i in range(1, max_entries):
1842   - # self._load_direntry(i)
1843   - # read and build all storage trees, starting from the root:
1844   - self.root.build_storage_tree()
1845   -
1846   -
1847   - def _load_direntry (self, sid):
1848   - """
1849   - Load a directory entry from the directory.
1850   - This method should only be called once for each storage/stream when
1851   - loading the directory.
1852   -
1853   - :param sid: index of storage/stream in the directory.
1854   - :returns: a OleDirectoryEntry object
1855   -
1856   - :exception IOError: if the entry has always been referenced.
1857   - """
1858   - # check if SID is OK:
1859   - if sid<0 or sid>=len(self.direntries):
1860   - self._raise_defect(DEFECT_FATAL, "OLE directory index out of range")
1861   - # check if entry was already referenced:
1862   - if self.direntries[sid] is not None:
1863   - self._raise_defect(DEFECT_INCORRECT,
1864   - "double reference for OLE stream/storage")
1865   - # if exception not raised, return the object
1866   - return self.direntries[sid]
1867   - self.directory_fp.seek(sid * 128)
1868   - entry = self.directory_fp.read(128)
1869   - self.direntries[sid] = OleDirectoryEntry(entry, sid, self)
1870   - return self.direntries[sid]
1871   -
1872   -
1873   - def dumpdirectory(self):
1874   - """
1875   - Dump directory (for debugging only)
1876   - """
1877   - self.root.dump()
1878   -
1879   -
1880   - def _open(self, start, size = UNKNOWN_SIZE, force_FAT=False):
1881   - """
1882   - Open a stream, either in FAT or MiniFAT according to its size.
1883   - (openstream helper)
1884   -
1885   - :param start: index of first sector
1886   - :param size: size of stream (or nothing if size is unknown)
1887   - :param force_FAT: if False (default), stream will be opened in FAT or MiniFAT
1888   - according to size. If True, it will always be opened in FAT.
1889   - """
1890   - log.debug('OleFileIO.open(): sect=%Xh, size=%d, force_FAT=%s' %
1891   - (start, size, str(force_FAT)))
1892   - # stream size is compared to the mini_stream_cutoff_size threshold:
1893   - if size < self.minisectorcutoff and not force_FAT:
1894   - # ministream object
1895   - if not self.ministream:
1896   - # load MiniFAT if it wasn't already done:
1897   - self.loadminifat()
1898   - # The first sector index of the miniFAT stream is stored in the
1899   - # root directory entry:
1900   - size_ministream = self.root.size
1901   - log.debug('Opening MiniStream: sect=%Xh, size=%d' %
1902   - (self.root.isectStart, size_ministream))
1903   - self.ministream = self._open(self.root.isectStart,
1904   - size_ministream, force_FAT=True)
1905   - return OleStream(fp=self.ministream, sect=start, size=size,
1906   - offset=0, sectorsize=self.minisectorsize,
1907   - fat=self.minifat, filesize=self.ministream.size,
1908   - olefileio=self)
1909   - else:
1910   - # standard stream
1911   - return OleStream(fp=self.fp, sect=start, size=size,
1912   - offset=self.sectorsize,
1913   - sectorsize=self.sectorsize, fat=self.fat,
1914   - filesize=self._filesize,
1915   - olefileio=self)
1916   -
1917   -
1918   - def _list(self, files, prefix, node, streams=True, storages=False):
1919   - """
1920   - listdir helper
1921   -
1922   - :param files: list of files to fill in
1923   - :param prefix: current location in storage tree (list of names)
1924   - :param node: current node (OleDirectoryEntry object)
1925   - :param streams: bool, include streams if True (True by default) - new in v0.26
1926   - :param storages: bool, include storages if True (False by default) - new in v0.26
1927   - (note: the root storage is never included)
1928   - """
1929   - prefix = prefix + [node.name]
1930   - for entry in node.kids:
1931   - if entry.entry_type == STGTY_STORAGE:
1932   - # this is a storage
1933   - if storages:
1934   - # add it to the list
1935   - files.append(prefix[1:] + [entry.name])
1936   - # check its kids
1937   - self._list(files, prefix, entry, streams, storages)
1938   - elif entry.entry_type == STGTY_STREAM:
1939   - # this is a stream
1940   - if streams:
1941   - # add it to the list
1942   - files.append(prefix[1:] + [entry.name])
1943   - else:
1944   - self._raise_defect(DEFECT_INCORRECT, 'The directory tree contains an entry which is not a stream nor a storage.')
1945   -
1946   -
1947   - def listdir(self, streams=True, storages=False):
1948   - """
1949   - Return a list of streams and/or storages stored in this file
1950   -
1951   - :param streams: bool, include streams if True (True by default) - new in v0.26
1952   - :param storages: bool, include storages if True (False by default) - new in v0.26
1953   - (note: the root storage is never included)
1954   - :returns: list of stream and/or storage paths
1955   - """
1956   - files = []
1957   - self._list(files, [], self.root, streams, storages)
1958   - return files
1959   -
1960   -
1961   - def _find(self, filename):
1962   - """
1963   - Returns directory entry of given filename. (openstream helper)
1964   - Note: this method is case-insensitive.
1965   -
1966   - :param filename: path of stream in storage tree (except root entry), either:
1967   -
1968   - - a string using Unix path syntax, for example:
1969   - 'storage_1/storage_1.2/stream'
1970   - - or a list of storage filenames, path to the desired stream/storage.
1971   - Example: ['storage_1', 'storage_1.2', 'stream']
1972   -
1973   - :returns: sid of requested filename
1974   - :exception IOError: if file not found
1975   - """
1976   -
1977   - # if filename is a string instead of a list, split it on slashes to
1978   - # convert to a list:
1979   - if isinstance(filename, basestring):
1980   - filename = filename.split('/')
1981   - # walk across storage tree, following given path:
1982   - node = self.root
1983   - for name in filename:
1984   - for kid in node.kids:
1985   - if kid.name.lower() == name.lower():
1986   - break
1987   - else:
1988   - raise IOError("file not found")
1989   - node = kid
1990   - return node.sid
1991   -
1992   -
1993   - def openstream(self, filename):
1994   - """
1995   - Open a stream as a read-only file object (BytesIO).
1996   - Note: filename is case-insensitive.
1997   -
1998   - :param filename: path of stream in storage tree (except root entry), either:
1999   -
2000   - - a string using Unix path syntax, for example:
2001   - 'storage_1/storage_1.2/stream'
2002   - - or a list of storage filenames, path to the desired stream/storage.
2003   - Example: ['storage_1', 'storage_1.2', 'stream']
2004   -
2005   - :returns: file object (read-only)
2006   - :exception IOError: if filename not found, or if this is not a stream.
2007   - """
2008   - sid = self._find(filename)
2009   - entry = self.direntries[sid]
2010   - if entry.entry_type != STGTY_STREAM:
2011   - raise IOError("this file is not a stream")
2012   - return self._open(entry.isectStart, entry.size)
2013   -
2014   -
2015   - def write_stream(self, stream_name, data):
2016   - """
2017   - Write a stream to disk. For now, it is only possible to replace an
2018   - existing stream by data of the same size.
2019   -
2020   - :param stream_name: path of stream in storage tree (except root entry), either:
2021   -
2022   - - a string using Unix path syntax, for example:
2023   - 'storage_1/storage_1.2/stream'
2024   - - or a list of storage filenames, path to the desired stream/storage.
2025   - Example: ['storage_1', 'storage_1.2', 'stream']
2026   -
2027   - :param data: bytes, data to be written, must be the same size as the original
2028   - stream.
2029   - """
2030   - if not isinstance(data, bytes):
2031   - raise TypeError("write_stream: data must be a bytes string")
2032   - sid = self._find(stream_name)
2033   - entry = self.direntries[sid]
2034   - if entry.entry_type != STGTY_STREAM:
2035   - raise IOError("this is not a stream")
2036   - size = entry.size
2037   - if size != len(data):
2038   - raise ValueError("write_stream: data must be the same size as the existing stream")
2039   - if size < self.minisectorcutoff:
2040   - raise NotImplementedError("Writing a stream in MiniFAT is not implemented yet")
2041   - sect = entry.isectStart
2042   - # number of sectors to write
2043   - nb_sectors = (size + (self.sectorsize-1)) // self.sectorsize
2044   - log.debug('nb_sectors = %d' % nb_sectors)
2045   - for i in range(nb_sectors):
2046   -## try:
2047   -## self.fp.seek(offset + self.sectorsize * sect)
2048   -## except:
2049   -## log.debug('sect=%d, seek=%d' %
2050   -## (sect, offset+self.sectorsize*sect))
2051   -## raise IOError('OLE sector index out of range')
2052   - # extract one sector from data, the last one being smaller:
2053   - if i<(nb_sectors-1):
2054   - data_sector = data [i*self.sectorsize : (i+1)*self.sectorsize]
2055   - #TODO: comment this if it works
2056   - assert(len(data_sector)==self.sectorsize)
2057   - else:
2058   - data_sector = data [i*self.sectorsize:]
2059   - #TODO: comment this if it works
2060   - log.debug('write_stream: size=%d sectorsize=%d data_sector=%Xh size%%sectorsize=%d'
2061   - % (size, self.sectorsize, len(data_sector), size % self.sectorsize))
2062   - assert(len(data_sector) % self.sectorsize==size % self.sectorsize)
2063   - self.write_sect(sect, data_sector)
2064   -## self.fp.write(data_sector)
2065   - # jump to next sector in the FAT:
2066   - try:
2067   - sect = self.fat[sect]
2068   - except IndexError:
2069   - # [PL] if pointer is out of the FAT an exception is raised
2070   - raise IOError('incorrect OLE FAT, sector index out of range')
2071   - #[PL] Last sector should be a "end of chain" marker:
2072   - if sect != ENDOFCHAIN:
2073   - raise IOError('incorrect last sector index in OLE stream')
2074   -
2075   -
2076   - def get_type(self, filename):
2077   - """
2078   - Test if given filename exists as a stream or a storage in the OLE
2079   - container, and return its type.
2080   -
2081   - :param filename: path of stream in storage tree. (see openstream for syntax)
2082   - :returns: False if object does not exist, its entry type (>0) otherwise:
2083   -
2084   - - STGTY_STREAM: a stream
2085   - - STGTY_STORAGE: a storage
2086   - - STGTY_ROOT: the root entry
2087   - """
2088   - try:
2089   - sid = self._find(filename)
2090   - entry = self.direntries[sid]
2091   - return entry.entry_type
2092   - except:
2093   - return False
2094   -
2095   -
2096   - def getclsid(self, filename):
2097   - """
2098   - Return clsid of a stream/storage.
2099   -
2100   - :param filename: path of stream/storage in storage tree. (see openstream for
2101   - syntax)
2102   - :returns: Empty string if clsid is null, a printable representation of the clsid otherwise
2103   -
2104   - new in version 0.44
2105   - """
2106   - sid = self._find(filename)
2107   - entry = self.direntries[sid]
2108   - return entry.clsid
2109   -
2110   -
2111   - def getmtime(self, filename):
2112   - """
2113   - Return modification time of a stream/storage.
2114   -
2115   - :param filename: path of stream/storage in storage tree. (see openstream for
2116   - syntax)
2117   - :returns: None if modification time is null, a python datetime object
2118   - otherwise (UTC timezone)
2119   -
2120   - new in version 0.26
2121   - """
2122   - sid = self._find(filename)
2123   - entry = self.direntries[sid]
2124   - return entry.getmtime()
2125   -
2126   -
2127   - def getctime(self, filename):
2128   - """
2129   - Return creation time of a stream/storage.
2130   -
2131   - :param filename: path of stream/storage in storage tree. (see openstream for
2132   - syntax)
2133   - :returns: None if creation time is null, a python datetime object
2134   - otherwise (UTC timezone)
2135   -
2136   - new in version 0.26
2137   - """
2138   - sid = self._find(filename)
2139   - entry = self.direntries[sid]
2140   - return entry.getctime()
2141   -
2142   -
2143   - def exists(self, filename):
2144   - """
2145   - Test if given filename exists as a stream or a storage in the OLE
2146   - container.
2147   - Note: filename is case-insensitive.
2148   -
2149   - :param filename: path of stream in storage tree. (see openstream for syntax)
2150   - :returns: True if object exist, else False.
2151   - """
2152   - try:
2153   - sid = self._find(filename)
2154   - return True
2155   - except:
2156   - return False
2157   -
2158   -
2159   - def get_size(self, filename):
2160   - """
2161   - Return size of a stream in the OLE container, in bytes.
2162   -
2163   - :param filename: path of stream in storage tree (see openstream for syntax)
2164   - :returns: size in bytes (long integer)
2165   - :exception IOError: if file not found
2166   - :exception TypeError: if this is not a stream.
2167   - """
2168   - sid = self._find(filename)
2169   - entry = self.direntries[sid]
2170   - if entry.entry_type != STGTY_STREAM:
2171   - #TODO: Should it return zero instead of raising an exception ?
2172   - raise TypeError('object is not an OLE stream')
2173   - return entry.size
2174   -
2175   -
2176   - def get_rootentry_name(self):
2177   - """
2178   - Return root entry name. Should usually be 'Root Entry' or 'R' in most
2179   - implementations.
2180   - """
2181   - return self.root.name
2182   -
2183   -
2184   - def getproperties(self, filename, convert_time=False, no_conversion=None):
2185   - """
2186   - Return properties described in substream.
2187   -
2188   - :param filename: path of stream in storage tree (see openstream for syntax)
2189   - :param convert_time: bool, if True timestamps will be converted to Python datetime
2190   - :param no_conversion: None or list of int, timestamps not to be converted
2191   - (for example total editing time is not a real timestamp)
2192   -
2193   - :returns: a dictionary of values indexed by id (integer)
2194   - """
2195   - #REFERENCE: [MS-OLEPS] https://msdn.microsoft.com/en-us/library/dd942421.aspx
2196   - # make sure no_conversion is a list, just to simplify code below:
2197   - if no_conversion == None:
2198   - no_conversion = []
2199   - # stream path as a string to report exceptions:
2200   - streampath = filename
2201   - if not isinstance(streampath, str):
2202   - streampath = '/'.join(streampath)
2203   -
2204   - fp = self.openstream(filename)
2205   -
2206   - data = {}
2207   -
2208   - try:
2209   - # header
2210   - s = fp.read(28)
2211   - clsid = _clsid(s[8:24])
2212   -
2213   - # format id
2214   - s = fp.read(20)
2215   - fmtid = _clsid(s[:16])
2216   - fp.seek(i32(s, 16))
2217   -
2218   - # get section
2219   - s = b"****" + fp.read(i32(fp.read(4))-4)
2220   - # number of properties:
2221   - num_props = i32(s, 4)
2222   - except BaseException as exc:
2223   - # catch exception while parsing property header, and only raise
2224   - # a DEFECT_INCORRECT then return an empty dict, because this is not
2225   - # a fatal error when parsing the whole file
2226   - msg = 'Error while parsing properties header in stream %s: %s' % (
2227   - repr(streampath), exc)
2228   - self._raise_defect(DEFECT_INCORRECT, msg, type(exc))
2229   - return data
2230   -
2231   - # clamp num_props based on the data length
2232   - num_props = min(num_props, len(s) / 8)
2233   -
2234   - for i in iterrange(num_props):
2235   - property_id = 0 # just in case of an exception
2236   - try:
2237   - property_id = i32(s, 8+i*8)
2238   - offset = i32(s, 12+i*8)
2239   - property_type = i32(s, offset)
2240   -
2241   - log.debug('property id=%d: type=%d offset=%X' % (property_id, property_type, offset))
2242   -
2243   - # test for common types first (should perhaps use
2244   - # a dictionary instead?)
2245   -
2246   - if property_type == VT_I2: # 16-bit signed integer
2247   - value = i16(s, offset+4)
2248   - if value >= 32768:
2249   - value = value - 65536
2250   - elif property_type == VT_UI2: # 2-byte unsigned integer
2251   - value = i16(s, offset+4)
2252   - elif property_type in (VT_I4, VT_INT, VT_ERROR):
2253   - # VT_I4: 32-bit signed integer
2254   - # VT_ERROR: HRESULT, similar to 32-bit signed integer,
2255   - # see https://msdn.microsoft.com/en-us/library/cc230330.aspx
2256   - value = i32(s, offset+4)
2257   - elif property_type in (VT_UI4, VT_UINT): # 4-byte unsigned integer
2258   - value = i32(s, offset+4) # FIXME
2259   - elif property_type in (VT_BSTR, VT_LPSTR):
2260   - # CodePageString, see https://msdn.microsoft.com/en-us/library/dd942354.aspx
2261   - # size is a 32 bits integer, including the null terminator, and
2262   - # possibly trailing or embedded null chars
2263   - #TODO: if codepage is unicode, the string should be converted as such
2264   - count = i32(s, offset+4)
2265   - value = s[offset+8:offset+8+count-1]
2266   - # remove all null chars:
2267   - value = value.replace(b'\x00', b'')
2268   - elif property_type == VT_BLOB:
2269   - # binary large object (BLOB)
2270   - # see https://msdn.microsoft.com/en-us/library/dd942282.aspx
2271   - count = i32(s, offset+4)
2272   - value = s[offset+8:offset+8+count]
2273   - elif property_type == VT_LPWSTR:
2274   - # UnicodeString
2275   - # see https://msdn.microsoft.com/en-us/library/dd942313.aspx
2276   - # "the string should NOT contain embedded or additional trailing
2277   - # null characters."
2278   - count = i32(s, offset+4)
2279   - value = self._decode_utf16_str(s[offset+8:offset+8+count*2])
2280   - elif property_type == VT_FILETIME:
2281   - value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32)
2282   - # FILETIME is a 64-bit int: "number of 100ns periods
2283   - # since Jan 1,1601".
2284   - if convert_time and property_id not in no_conversion:
2285   - log.debug('Converting property #%d to python datetime, value=%d=%fs'
2286   - %(property_id, value, float(value)/10000000))
2287   - # convert FILETIME to Python datetime.datetime
2288   - # inspired from https://code.activestate.com/recipes/511425-filetime-to-datetime/
2289   - _FILETIME_null_date = datetime.datetime(1601, 1, 1, 0, 0, 0)
2290   - log.debug('timedelta days=%d' % (value//(10*1000000*3600*24)))
2291   - value = _FILETIME_null_date + datetime.timedelta(microseconds=value//10)
2292   - else:
2293   - # legacy code kept for backward compatibility: returns a
2294   - # number of seconds since Jan 1,1601
2295   - value = value // 10000000 # seconds
2296   - elif property_type == VT_UI1: # 1-byte unsigned integer
2297   - value = i8(s[offset+4])
2298   - elif property_type == VT_CLSID:
2299   - value = _clsid(s[offset+4:offset+20])
2300   - elif property_type == VT_CF:
2301   - # PropertyIdentifier or ClipboardData??
2302   - # see https://msdn.microsoft.com/en-us/library/dd941945.aspx
2303   - count = i32(s, offset+4)
2304   - value = s[offset+8:offset+8+count]
2305   - elif property_type == VT_BOOL:
2306   - # VARIANT_BOOL, 16 bits bool, 0x0000=Fals, 0xFFFF=True
2307   - # see https://msdn.microsoft.com/en-us/library/cc237864.aspx
2308   - value = bool(i16(s, offset+4))
2309   - else:
2310   - value = None # everything else yields "None"
2311   - log.debug('property id=%d: type=%d not implemented in parser yet' % (property_id, property_type))
2312   -
2313   - # missing: VT_EMPTY, VT_NULL, VT_R4, VT_R8, VT_CY, VT_DATE,
2314   - # VT_DECIMAL, VT_I1, VT_I8, VT_UI8,
2315   - # see https://msdn.microsoft.com/en-us/library/dd942033.aspx
2316   -
2317   - # FIXME: add support for VT_VECTOR
2318   - # VT_VECTOR is a 32 uint giving the number of items, followed by
2319   - # the items in sequence. The VT_VECTOR value is combined with the
2320   - # type of items, e.g. VT_VECTOR|VT_BSTR
2321   - # see https://msdn.microsoft.com/en-us/library/dd942011.aspx
2322   -
2323   - #print("%08x" % property_id, repr(value), end=" ")
2324   - #print("(%s)" % VT[i32(s, offset) & 0xFFF])
2325   -
2326   - data[property_id] = value
2327   - except BaseException as exc:
2328   - # catch exception while parsing each property, and only raise
2329   - # a DEFECT_INCORRECT, because parsing can go on
2330   - msg = 'Error while parsing property id %d in stream %s: %s' % (
2331   - property_id, repr(streampath), exc)
2332   - self._raise_defect(DEFECT_INCORRECT, msg, type(exc))
2333   -
2334   - return data
2335   -
2336   - def get_metadata(self):
2337   - """
2338   - Parse standard properties streams, return an OleMetadata object
2339   - containing all the available metadata.
2340   - (also stored in the metadata attribute of the OleFileIO object)
2341   -
2342   - new in version 0.25
2343   - """
2344   - self.metadata = OleMetadata()
2345   - self.metadata.parse_properties(self)
2346   - return self.metadata
2347   -
2348   -#
2349   -# --------------------------------------------------------------------
2350   -# This script can be used to dump the directory of any OLE2 structured
2351   -# storage file.
2352   -
2353   -if __name__ == "__main__":
2354   -
2355   - import sys, optparse
2356   -
2357   - DEFAULT_LOG_LEVEL = "warning" # Default log level
2358   - LOG_LEVELS = {
2359   - 'debug': logging.DEBUG,
2360   - 'info': logging.INFO,
2361   - 'warning': logging.WARNING,
2362   - 'error': logging.ERROR,
2363   - 'critical': logging.CRITICAL
2364   - }
2365   -
2366   - usage = 'usage: %prog [options] <filename> [filename2 ...]'
2367   - parser = optparse.OptionParser(usage=usage)
2368   - parser.add_option("-c", action="store_true", dest="check_streams",
2369   - help='check all streams (for debugging purposes)')
2370   - parser.add_option("-d", action="store_true", dest="debug_mode",
2371   - help='debug mode, shortcut for -l debug (displays a lot of debug information, for developers only)')
2372   - parser.add_option('-l', '--loglevel', dest="loglevel", action="store", default=DEFAULT_LOG_LEVEL,
2373   - help="logging level debug/info/warning/error/critical (default=%default)")
2374   -
2375   - (options, args) = parser.parse_args()
2376   -
2377   - print('olefile version %s %s - https://www.decalage.info/en/olefile\n' % (__version__, __date__))
2378   -
2379   - # Print help if no arguments are passed
2380   - if len(args) == 0:
2381   - print(__doc__)
2382   - parser.print_help()
2383   - sys.exit()
2384   -
2385   - if options.debug_mode:
2386   - options.loglevel = 'debug'
2387   -
2388   - # setup logging to the console
2389   - logging.basicConfig(level=LOG_LEVELS[options.loglevel], format='%(levelname)-8s %(message)s')
2390   -
2391   - # also enable the module's logger:
2392   - enable_logging()
2393   -
2394   - for filename in args:
2395   - try:
2396   - ole = OleFileIO(filename)#, raise_defects=DEFECT_INCORRECT)
2397   - print("-" * 68)
2398   - print(filename)
2399   - print("-" * 68)
2400   - ole.dumpdirectory()
2401   - for streamname in ole.listdir():
2402   - if streamname[-1][0] == "\005":
2403   - print("%r: properties" % streamname)
2404   - try:
2405   - props = ole.getproperties(streamname, convert_time=True)
2406   - props = sorted(props.items())
2407   - for k, v in props:
2408   - #[PL]: avoid to display too large or binary values:
2409   - if isinstance(v, (basestring, bytes)):
2410   - if len(v) > 50:
2411   - v = v[:50]
2412   - if isinstance(v, bytes):
2413   - # quick and dirty binary check:
2414   - for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20,
2415   - 21,22,23,24,25,26,27,28,29,30,31):
2416   - if c in bytearray(v):
2417   - v = '(binary data)'
2418   - break
2419   - print(" ", k, v)
2420   - except:
2421   - log.exception('Error while parsing property stream %r' % streamname)
2422   -
2423   - if options.check_streams:
2424   - # Read all streams to check if there are errors:
2425   - print('\nChecking streams...')
2426   - for streamname in ole.listdir():
2427   - # print name using repr() to convert binary chars to \xNN:
2428   - print('-', repr('/'.join(streamname)),'-', end=' ')
2429   - st_type = ole.get_type(streamname)
2430   - if st_type == STGTY_STREAM:
2431   - print('size %d' % ole.get_size(streamname))
2432   - # just try to read stream in memory:
2433   - ole.openstream(streamname)
2434   - else:
2435   - print('NOT a stream : type=%d' % st_type)
2436   - print()
2437   -
2438   -## for streamname in ole.listdir():
2439   -## # print name using repr() to convert binary chars to \xNN:
2440   -## print('-', repr('/'.join(streamname)),'-', end=' ')
2441   -## print(ole.getmtime(streamname))
2442   -## print()
2443   -
2444   - print('Modification/Creation times of all directory entries:')
2445   - for entry in ole.direntries:
2446   - if entry is not None:
2447   - print('- %s: mtime=%s ctime=%s' % (entry.name,
2448   - entry.getmtime(), entry.getctime()))
2449   - print()
2450   -
2451   - # parse and display metadata:
2452   - try:
2453   - meta = ole.get_metadata()
2454   - meta.dump()
2455   - except:
2456   - log.exception('Error while parsing metadata')
2457   - print()
2458   - #[PL] Test a few new methods:
2459   - root = ole.get_rootentry_name()
2460   - print('Root entry name: "%s"' % root)
2461   - if ole.exists('worddocument'):
2462   - print("This is a Word document.")
2463   - print("type of stream 'WordDocument':", ole.get_type('worddocument'))
2464   - print("size :", ole.get_size('worddocument'))
2465   - if ole.exists('macros/vba'):
2466   - print("This document may contain VBA macros.")
2467   -
2468   - # print parsing issues:
2469   - print('\nNon-fatal issues raised during parsing:')
2470   - if ole.parsing_issues:
2471   - for exctype, msg in ole.parsing_issues:
2472   - print('- %s: %s' % (exctype.__name__, msg))
2473   - else:
2474   - print('None')
2475   - except:
2476   - log.exception('Error while parsing file %r' % filename)
2477   -
2478   -# this code was developed while listening to The Wedding Present "Sea Monsters"
oletools/thirdparty/tablestream/tablestream.py
... ... @@ -19,7 +19,7 @@ License: BSD, see source code or documentation
19 19  
20 20 #=== LICENSE ==================================================================
21 21  
22   -# tablestream is copyright (c) 2015-2016 Philippe Lagadec (http://www.decalage.info)
  22 +# tablestream is copyright (c) 2015-2018 Philippe Lagadec (http://www.decalage.info)
23 23 # All rights reserved.
24 24 #
25 25 # Redistribution and use in source and binary forms, with or without modification,
... ... @@ -54,8 +54,9 @@ from __future__ import print_function
54 54 # 2016-07-31 v0.06 PL: - handle newline characters properly in each cell
55 55 # 2016-08-28 v0.07 PL: - support for both Python 2.6+ and 3.x
56 56 # - all cells are converted to unicode
  57 +# 2018-09-22 v0.08 PL: - removed mention to oletools' thirdparty folder
57 58  
58   -__version__ = '0.07'
  59 +__version__ = '0.08'
59 60  
60 61 #------------------------------------------------------------------------------
61 62 # TODO:
... ... @@ -70,15 +71,6 @@ __version__ = &#39;0.07&#39;
70 71 import textwrap
71 72 import sys, os
72 73  
73   -# add the thirdparty subfolder to sys.path (absolute+normalized path):
74   -_thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__)))
75   -# print('_thismodule_dir = %r' % _thismodule_dir)
76   -# assumption: this module is in a subfolder of thirdparty:
77   -_thirdparty_dir = os.path.normpath(os.path.join(_thismodule_dir, '..'))
78   -# print('_thirdparty_dir = %r' % _thirdparty_dir)
79   -if not _thirdparty_dir in sys.path:
80   - sys.path.insert(0, _thirdparty_dir)
81   -
82 74 import colorclass
83 75  
84 76 # On Windows, colorclass needs to be enabled:
... ...
oletools/xls_parser.py
... ... @@ -5,7 +5,7 @@ Read storages, (sub-)streams, records from xls file
5 5 #
6 6 # === LICENSE ==================================================================
7 7  
8   -# xls_parser is copyright (c) 2014-2017 Philippe Lagadec (http://www.decalage.info)
  8 +# xls_parser is copyright (c) 2014-2018 Philippe Lagadec (http://www.decalage.info)
9 9 # All rights reserved.
10 10 #
11 11 # Redistribution and use in source and binary forms, with or without modification,
... ... @@ -86,14 +86,16 @@ def is_xls(filename):
86 86 returns True if given file is an ole file and contains a Workbook stream
87 87  
88 88 todo: could further check that workbook stream starts with a globals
89   - substream
  89 + substream.
  90 + See also: oleid.OleID.check_excel
90 91 """
91 92 try:
92 93 for stream in XlsFile(filename).iter_streams():
93 94 if isinstance(stream, WorkbookStream):
94 95 return True
95 96 except Exception:
96   - return False
  97 + pass
  98 + return False
97 99  
98 100  
99 101 def read_unicode(data, start_idx, n_chars):
... ... @@ -130,6 +132,8 @@ class XlsFile(record_base.OleRecordFile):
130 132 @classmethod
131 133 def stream_class_for_name(cls, stream_name):
132 134 """ helper for iter_streams """
  135 + if stream_name == 'Workbook':
  136 + return WorkbookStream
133 137 return XlsStream
134 138  
135 139  
... ...
requirements.txt 0 → 100644
  1 +pyparsing>=2.2.0
  2 +olefile>=0.45
... ...
setup.py
... ... @@ -24,6 +24,10 @@ to install this package.
24 24 # 2017-01-18 v0.51 PL: - added package zipfile27 (issue #121)
25 25 # 2017-10-18 v0.52 PL: - added msodde
26 26 # 2018-03-19 v0.52.3 PL: - added install_requires, removed thirdparty.pyparsing
  27 +# 2018-09-11 v0.54 PL: - olefile is now a dependency
  28 +# 2018-09-15 PL: - easygui is now a dependency
  29 +# 2018-09-22 PL: - colorclass is now a dependency
  30 +# 2018-10-27 PL: - fixed issue #359 (bug when importing log_helper)
27 31  
28 32 #--- TODO ---------------------------------------------------------------------
29 33  
... ... @@ -43,7 +47,7 @@ import os, fnmatch
43 47 #--- METADATA -----------------------------------------------------------------
44 48  
45 49 name = "oletools"
46   -version = '0.53'
  50 +version = '0.54dev4'
47 51 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"
48 52 long_desc = open('oletools/README.rst').read()
49 53 author = "Philippe Lagadec"
... ... @@ -52,7 +56,7 @@ url = &quot;http://www.decalage.info/python/oletools&quot;
52 56 license = "BSD"
53 57 download_url = "https://github.com/decalage2/oletools/releases"
54 58  
55   -# see https://pypi.python.org/pypi?%3Aaction=list_classifiers
  59 +# see https://pypi.org/pypi?%3Aaction=list_classifiers
56 60 classifiers=[
57 61 "Development Status :: 4 - Beta",
58 62 "Intended Audience :: Developers",
... ... @@ -78,14 +82,12 @@ classifiers=[
78 82 packages=[
79 83 "oletools",
80 84 "oletools.common",
  85 + "oletools.common.log_helper",
81 86 'oletools.thirdparty',
82   - 'oletools.thirdparty.olefile',
83   - 'oletools.thirdparty.easygui',
84 87 'oletools.thirdparty.xxxswf',
85 88 'oletools.thirdparty.prettytable',
86 89 'oletools.thirdparty.xglob',
87 90 'oletools.thirdparty.DridexUrlDecoder',
88   - 'oletools.thirdparty.colorclass',
89 91 'oletools.thirdparty.tablestream',
90 92 'oletools.thirdparty.zipfile27',
91 93 ]
... ... @@ -163,16 +165,9 @@ package_data={
163 165 + rglob('oletools/doc', 'doc', '*.md')
164 166 + rglob('oletools/doc', 'doc', '*.png'),
165 167  
166   - 'oletools.thirdparty.olefile': [
167   - 'README.txt',
168   - 'LICENSE.txt',
169   - ],
170 168 'oletools.thirdparty.xglob': [
171 169 'LICENSE.txt',
172 170 ],
173   - 'oletools.thirdparty.easygui': [
174   - 'LICENSE.txt',
175   - ],
176 171 'oletools.thirdparty.xxxswf': [
177 172 'LICENSE.txt',
178 173 ],
... ... @@ -182,9 +177,6 @@ package_data={
182 177 'oletools.thirdparty.DridexUrlDecoder': [
183 178 'LICENSE.txt',
184 179 ],
185   - 'oletools.thirdparty.colorclass': [
186   - 'LICENSE.txt',
187   - ],
188 180 'oletools.thirdparty.zipfile27': [
189 181 'LICENSE.txt',
190 182 ],
... ... @@ -287,6 +279,7 @@ entry_points = {
287 279 'rtfobj=oletools.rtfobj:main',
288 280 'oleobj=oletools.oleobj:main',
289 281 'msodde=oletools.msodde:main',
  282 + 'olefile=olefile.olefile:main',
290 283 ],
291 284 }
292 285  
... ... @@ -320,7 +313,12 @@ def main():
320 313 entry_points=entry_points,
321 314 test_suite="tests",
322 315 # scripts=scripts,
323   - install_requires=["pyparsing"],
  316 + install_requires=[
  317 + "pyparsing>=2.2.0",
  318 + "olefile>=0.46",
  319 + "easygui",
  320 + 'colorclass',
  321 + ],
324 322 )
325 323  
326 324  
... ...
oletools/thirdparty/easygui/__init__.py renamed to tests/common/__init__.py
tests/json/__init__.py renamed to tests/common/log_helper/__init__.py
tests/common/log_helper/log_helper_test_imported.py 0 → 100644
  1 +"""
  2 +Dummy file that logs messages, meant to be imported
  3 +by the main test file
  4 +"""
  5 +
  6 +from oletools.common.log_helper import log_helper
  7 +import logging
  8 +
  9 +DEBUG_MESSAGE = 'imported: debug log'
  10 +INFO_MESSAGE = 'imported: info log'
  11 +WARNING_MESSAGE = 'imported: warning log'
  12 +ERROR_MESSAGE = 'imported: error log'
  13 +CRITICAL_MESSAGE = 'imported: critical log'
  14 +
  15 +logger = log_helper.get_or_create_silent_logger('test_imported', logging.ERROR)
  16 +
  17 +
  18 +def log():
  19 + logger.debug(DEBUG_MESSAGE)
  20 + logger.info(INFO_MESSAGE)
  21 + logger.warning(WARNING_MESSAGE)
  22 + logger.error(ERROR_MESSAGE)
  23 + logger.critical(CRITICAL_MESSAGE)
... ...
tests/common/log_helper/log_helper_test_main.py 0 → 100644
  1 +""" Test log_helpers """
  2 +
  3 +import sys
  4 +from tests.common.log_helper import log_helper_test_imported
  5 +from oletools.common.log_helper import log_helper
  6 +
  7 +DEBUG_MESSAGE = 'main: debug log'
  8 +INFO_MESSAGE = 'main: info log'
  9 +WARNING_MESSAGE = 'main: warning log'
  10 +ERROR_MESSAGE = 'main: error log'
  11 +CRITICAL_MESSAGE = 'main: critical log'
  12 +
  13 +logger = log_helper.get_or_create_silent_logger('test_main')
  14 +
  15 +
  16 +def init_logging_and_log(args):
  17 + """
  18 + Try to cover possible logging scenarios. For each scenario covered, here's the expected args and outcome:
  19 + - Log without enabling: ['<level>']
  20 + * logging when being imported - should never print
  21 + - Log as JSON without enabling: ['as-json', '<level>']
  22 + * logging as JSON when being imported - should never print
  23 + - Enable and log: ['enable', '<level>']
  24 + * logging when being run as script - should log messages
  25 + - Enable and log as JSON: ['as-json', 'enable', '<level>']
  26 + * logging as JSON when being run as script - should log messages as JSON
  27 + - Enable, log as JSON and throw: ['enable', 'as-json', 'throw', '<level>']
  28 + * should produce JSON-compatible output, even after an unhandled exception
  29 + """
  30 +
  31 + # the level should always be the last argument passed
  32 + level = args[-1]
  33 + use_json = 'as-json' in args
  34 + throw = 'throw' in args
  35 +
  36 + if 'enable' in args:
  37 + log_helper.enable_logging(use_json, level, stream=sys.stdout)
  38 +
  39 + _log()
  40 +
  41 + if throw:
  42 + raise Exception('An exception occurred before ending the logging')
  43 +
  44 + log_helper.end_logging()
  45 +
  46 +
  47 +def _log():
  48 + logger.debug(DEBUG_MESSAGE)
  49 + logger.info(INFO_MESSAGE)
  50 + logger.warning(WARNING_MESSAGE)
  51 + logger.error(ERROR_MESSAGE)
  52 + logger.critical(CRITICAL_MESSAGE)
  53 + log_helper_test_imported.log()
  54 +
  55 +
  56 +if __name__ == '__main__':
  57 + init_logging_and_log(sys.argv[1:])
... ...
tests/common/log_helper/test_log_helper.py 0 → 100644
  1 +""" Test the log helper
  2 +
  3 +This tests the generic log helper.
  4 +Check if it handles imported modules correctly
  5 +and that the default silent logger won't log when nothing is enabled
  6 +"""
  7 +
  8 +import unittest
  9 +import sys
  10 +import json
  11 +import subprocess
  12 +from tests.common.log_helper import log_helper_test_main
  13 +from tests.common.log_helper import log_helper_test_imported
  14 +from os.path import dirname, join, relpath, abspath
  15 +
  16 +# this is the common base of "tests" and "oletools" dirs
  17 +ROOT_DIRECTORY = abspath(join(__file__, '..', '..', '..', '..'))
  18 +TEST_FILE = relpath(join(dirname(__file__), 'log_helper_test_main.py'), ROOT_DIRECTORY)
  19 +PYTHON_EXECUTABLE = sys.executable
  20 +
  21 +MAIN_LOG_MESSAGES = [
  22 + log_helper_test_main.DEBUG_MESSAGE,
  23 + log_helper_test_main.INFO_MESSAGE,
  24 + log_helper_test_main.WARNING_MESSAGE,
  25 + log_helper_test_main.ERROR_MESSAGE,
  26 + log_helper_test_main.CRITICAL_MESSAGE
  27 +]
  28 +
  29 +
  30 +class TestLogHelper(unittest.TestCase):
  31 + def test_it_doesnt_log_when_not_enabled(self):
  32 + output = self._run_test(['debug'])
  33 + self.assertTrue(len(output) == 0)
  34 +
  35 + def test_it_doesnt_log_json_when_not_enabled(self):
  36 + output = self._run_test(['as-json', 'debug'])
  37 + self.assertTrue(len(output) == 0)
  38 +
  39 + def test_logs_when_enabled(self):
  40 + output = self._run_test(['enable', 'warning'])
  41 +
  42 + expected_messages = [
  43 + log_helper_test_main.WARNING_MESSAGE,
  44 + log_helper_test_main.ERROR_MESSAGE,
  45 + log_helper_test_main.CRITICAL_MESSAGE,
  46 + log_helper_test_imported.WARNING_MESSAGE,
  47 + log_helper_test_imported.ERROR_MESSAGE,
  48 + log_helper_test_imported.CRITICAL_MESSAGE
  49 + ]
  50 +
  51 + for msg in expected_messages:
  52 + self.assertIn(msg, output)
  53 +
  54 + def test_logs_json_when_enabled(self):
  55 + output = self._run_test(['enable', 'as-json', 'critical'])
  56 +
  57 + self._assert_json_messages(output, [
  58 + log_helper_test_main.CRITICAL_MESSAGE,
  59 + log_helper_test_imported.CRITICAL_MESSAGE
  60 + ])
  61 +
  62 + def test_json_correct_on_exceptions(self):
  63 + """
  64 + Test that even on unhandled exceptions our JSON is always correct
  65 + """
  66 + output = self._run_test(['enable', 'as-json', 'throw', 'critical'], False)
  67 + self._assert_json_messages(output, [
  68 + log_helper_test_main.CRITICAL_MESSAGE,
  69 + log_helper_test_imported.CRITICAL_MESSAGE
  70 + ])
  71 +
  72 + def _assert_json_messages(self, output, messages):
  73 + try:
  74 + json_data = json.loads(output)
  75 + self.assertEquals(len(json_data), len(messages))
  76 +
  77 + for i in range(len(messages)):
  78 + self.assertEquals(messages[i], json_data[i]['msg'])
  79 + except ValueError:
  80 + self.fail('Invalid json:\n' + output)
  81 +
  82 + self.assertNotEqual(len(json_data), 0, msg='Output was empty')
  83 +
  84 + def _run_test(self, args, should_succeed=True):
  85 + """
  86 + Use subprocess to better simulate the real scenario and avoid
  87 + logging conflicts when running multiple tests (since logging depends on singletons,
  88 + we might get errors or false positives between sequential tests runs)
  89 + """
  90 + child = subprocess.Popen(
  91 + [PYTHON_EXECUTABLE, TEST_FILE] + args,
  92 + shell=False,
  93 + env={'PYTHONPATH': ROOT_DIRECTORY},
  94 + universal_newlines=True,
  95 + cwd=ROOT_DIRECTORY,
  96 + stdin=None,
  97 + stdout=subprocess.PIPE,
  98 + stderr=subprocess.PIPE
  99 + )
  100 + (output, output_err) = child.communicate()
  101 +
  102 + if not isinstance(output, str):
  103 + output = output.decode('utf-8')
  104 +
  105 + self.assertEquals(child.returncode == 0, should_succeed)
  106 +
  107 + return output.strip()
  108 +
  109 +
  110 +# just in case somebody calls this file as a script
  111 +if __name__ == '__main__':
  112 + unittest.main()
... ...
tests/json/test_output.py deleted
1   -""" Test validity of json output
2   -
3   -Some scripts have a json output flag. Verify that at default log levels output
4   -can be captured as-is and parsed by a json parser -- checking the return code
5   -if desired.
6   -"""
7   -
8   -import unittest
9   -import sys
10   -import json
11   -import os
12   -from os.path import join
13   -from oletools import msodde
14   -from tests.test_utils import OutputCapture, DATA_BASE_DIR
15   -
16   -if sys.version_info[0] <= 2:
17   - from oletools import olevba
18   -else:
19   - from oletools import olevba3 as olevba
20   -
21   -
22   -class TestValidJson(unittest.TestCase):
23   - """
24   - Ensure that script output is valid json.
25   - If check_return_code is True we also ignore the output
26   - of runs that didn't succeed.
27   - """
28   -
29   - @staticmethod
30   - def iter_test_files():
31   - """ Iterate over all test files in DATA_BASE_DIR """
32   - for dirpath, _, filenames in os.walk(DATA_BASE_DIR):
33   - for filename in filenames:
34   - yield join(dirpath, filename)
35   -
36   - def run_and_parse(self, program, args, print_output=False, check_return_code=True):
37   - """ run single program with single file and parse output """
38   - with OutputCapture() as capturer: # capture stdout
39   - try:
40   - return_code = program(args)
41   - except Exception:
42   - return_code = 1 # would result in non-zero exit
43   - except SystemExit as se:
44   - return_code = se.code or 0 # se.code can be None
45   - if check_return_code and return_code is not 0:
46   - if print_output:
47   - print('Command failed ({0}) -- not parsing output'
48   - .format(return_code))
49   - return [] # no need to test
50   -
51   - self.assertNotEqual(return_code, None,
52   - msg='self-test fail: return_code not set')
53   -
54   - # now test output
55   - if print_output:
56   - print(capturer.get_data())
57   - try:
58   - json_data = json.loads(capturer.get_data())
59   - except ValueError:
60   - self.fail('Invalid json:\n' + capturer.get_data())
61   - self.assertNotEqual(len(json_data), 0, msg='Output was empty')
62   - return json_data
63   -
64   - def run_all_files(self, program, args_without_filename, print_output=False):
65   - """ run test for a single program over all test files """
66   - n_files = 0
67   - for testfile in self.iter_test_files(): # loop over all input
68   - args = args_without_filename + [testfile, ]
69   - self.run_and_parse(program, args, print_output)
70   - n_files += 1
71   - self.assertNotEqual(n_files, 0,
72   - msg='self-test fail: No test files found')
73   -
74   - def test_msodde(self):
75   - """ Test msodde.py """
76   - self.run_all_files(msodde.main, ['-j', ])
77   -
78   - def test_olevba(self):
79   - """ Test olevba.py with default args """
80   - self.run_all_files(olevba.main, ['-j', ])
81   -
82   - def test_olevba_analysis(self):
83   - """ Test olevba.py with -a """
84   - self.run_all_files(olevba.main, ['-j', '-a', ])
85   -
86   - def test_olevba_recurse(self):
87   - """ Test olevba.py with -r """
88   - json_data = self.run_and_parse(olevba.main,
89   - ['-j', '-r', join(DATA_BASE_DIR, '*')],
90   - check_return_code=False)
91   - self.assertNotEqual(len(json_data), 0,
92   - msg='olevba[3] returned non-zero or no output')
93   - self.assertNotEqual(json_data[-1]['n_processed'], 0,
94   - msg='self-test fail: No test files found!')
95   -
96   -
97   -# just in case somebody calls this file as a script
98   -if __name__ == '__main__':
99   - unittest.main()
tests/msodde/test_basic.py
... ... @@ -10,15 +10,14 @@ from __future__ import print_function
10 10  
11 11 import unittest
12 12 from oletools import msodde
13   -from tests.test_utils import OutputCapture, DATA_BASE_DIR as BASE_DIR
14   -import shlex
  13 +from tests.test_utils import DATA_BASE_DIR as BASE_DIR
  14 +import os
15 15 from os.path import join
16 16 from traceback import print_exc
17 17  
18 18  
19 19 class TestReturnCode(unittest.TestCase):
20 20 """ check return codes and exception behaviour (not text output) """
21   -
22 21 def test_valid_doc(self):
23 22 """ check that a valid doc file leads to 0 exit status """
24 23 for filename in (
... ... @@ -57,89 +56,89 @@ class TestReturnCode(unittest.TestCase):
57 56 """ check that text file argument leads to non-zero exit status """
58 57 self.do_test_validity(join(BASE_DIR, 'basic/text'), True)
59 58  
  59 + def test_encrypted(self):
  60 + """
  61 + check that encrypted files lead to non-zero exit status
  62 +
  63 + Currently, only the encryption applied by Office 2010 (CryptoApi RC4
  64 + Encryption) is tested.
  65 + """
  66 + CRYPT_DIR = join(BASE_DIR, 'encrypted')
  67 + ADD_ARGS = '', '-j', '-d', '-f', '-a'
  68 + for filename in os.listdir(CRYPT_DIR):
  69 + full_name = join(CRYPT_DIR, filename)
  70 + for args in ADD_ARGS:
  71 + self.do_test_validity(args + ' ' + full_name, True)
  72 +
60 73 def do_test_validity(self, args, expect_error=False):
61 74 """ helper for test_valid_doc[x] """
62   - args = shlex.split(args)
63   - return_code = -1
64 75 have_exception = False
65 76 try:
66   - return_code = msodde.main(args)
  77 + msodde.process_file(args, msodde.FIELD_FILTER_BLACKLIST)
67 78 except Exception:
68 79 have_exception = True
69 80 print_exc()
70 81 except SystemExit as exc: # sys.exit() was called
71   - return_code = exc.code
  82 + have_exception = True
72 83 if exc.code is None:
73   - return_code = 0
  84 + have_exception = False
74 85  
75   - self.assertEqual(expect_error, have_exception or (return_code != 0),
76   - msg='Args={0}, expect={1}, exc={2}, return={3}'
77   - .format(args, expect_error, have_exception,
78   - return_code))
  86 + self.assertEqual(expect_error, have_exception,
  87 + msg='Args={0}, expect={1}, exc={2}'
  88 + .format(args, expect_error, have_exception))
79 89  
80 90  
81 91 class TestDdeLinks(unittest.TestCase):
82 92 """ capture output of msodde and check dde-links are found correctly """
83 93  
84   - def get_dde_from_output(self, capturer):
  94 + @staticmethod
  95 + def get_dde_from_output(output):
85 96 """ helper to read dde links from captured output
86   -
87   - duplicate in tests/msodde/test_csv
88 97 """
89   - have_start_line = False
90   - result = []
91   - for line in capturer:
92   - if not line.strip():
93   - continue # skip empty lines
94   - if have_start_line:
95   - result.append(line)
96   - elif line == 'DDE Links:':
97   - have_start_line = True
98   -
99   - self.assertTrue(have_start_line) # ensure output was complete
100   - return result
  98 + return [o for o in output.splitlines()]
101 99  
102 100 def test_with_dde(self):
103 101 """ check that dde links appear on stdout """
104 102 filename = 'dde-test-from-office2003.doc'
105   - with OutputCapture() as capturer:
106   - msodde.main([join(BASE_DIR, 'msodde', filename)])
107   - self.assertNotEqual(len(self.get_dde_from_output(capturer)), 0,
  103 + output = msodde.process_file(
  104 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST)
  105 + self.assertNotEqual(len(self.get_dde_from_output(output)), 0,
108 106 msg='Found no dde links in output of ' + filename)
109 107  
110 108 def test_no_dde(self):
111 109 """ check that no dde links appear on stdout """
112 110 filename = 'harmless-clean.doc'
113   - with OutputCapture() as capturer:
114   - msodde.main([join(BASE_DIR, 'msodde', filename)])
115   - self.assertEqual(len(self.get_dde_from_output(capturer)), 0,
  111 + output = msodde.process_file(
  112 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST)
  113 + self.assertEqual(len(self.get_dde_from_output(output)), 0,
116 114 msg='Found dde links in output of ' + filename)
117 115  
118 116 def test_with_dde_utf16le(self):
119 117 """ check that dde links appear on stdout """
120 118 filename = 'dde-test-from-office2013-utf_16le-korean.doc'
121   - with OutputCapture() as capturer:
122   - msodde.main([join(BASE_DIR, 'msodde', filename)])
123   - self.assertNotEqual(len(self.get_dde_from_output(capturer)), 0,
  119 + output = msodde.process_file(
  120 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST)
  121 + self.assertNotEqual(len(self.get_dde_from_output(output)), 0,
124 122 msg='Found no dde links in output of ' + filename)
125 123  
126 124 def test_excel(self):
127 125 """ check that dde links are found in excel 2007+ files """
128 126 expect = ['DDE-Link cmd /c calc.exe', ]
129 127 for extn in 'xlsx', 'xlsm', 'xlsb':
130   - with OutputCapture() as capturer:
131   - msodde.main([join(BASE_DIR, 'msodde', 'dde-test.' + extn), ])
132   - self.assertEqual(expect, self.get_dde_from_output(capturer),
  128 + output = msodde.process_file(
  129 + join(BASE_DIR, 'msodde', 'dde-test.' + extn), msodde.FIELD_FILTER_BLACKLIST)
  130 +
  131 + self.assertEqual(expect, self.get_dde_from_output(output),
133 132 msg='unexpected output for dde-test.{0}: {1}'
134   - .format(extn, capturer.get_data()))
  133 + .format(extn, output))
135 134  
136 135 def test_xml(self):
137 136 """ check that dde in xml from word / excel is found """
138 137 for name_part in 'excel2003', 'word2003', 'word2007':
139 138 filename = 'dde-in-' + name_part + '.xml'
140   - with OutputCapture() as capturer:
141   - msodde.main([join(BASE_DIR, 'msodde', filename), ])
142   - links = self.get_dde_from_output(capturer)
  139 + output = msodde.process_file(
  140 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST)
  141 + links = self.get_dde_from_output(output)
143 142 self.assertEqual(len(links), 1, 'found {0} dde-links in {1}'
144 143 .format(len(links), filename))
145 144 self.assertTrue('cmd' in links[0], 'no "cmd" in dde-link for {0}'
... ... @@ -150,16 +149,16 @@ class TestDdeLinks(unittest.TestCase):
150 149 def test_clean_rtf_blacklist(self):
151 150 """ find a lot of hyperlinks in rtf spec """
152 151 filename = 'RTF-Spec-1.7.rtf'
153   - with OutputCapture() as capturer:
154   - msodde.main([join(BASE_DIR, 'msodde', filename)])
155   - self.assertEqual(len(self.get_dde_from_output(capturer)), 1413)
  152 + output = msodde.process_file(
  153 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_BLACKLIST)
  154 + self.assertEqual(len(self.get_dde_from_output(output)), 1413)
156 155  
157 156 def test_clean_rtf_ddeonly(self):
158 157 """ find no dde links in rtf spec """
159 158 filename = 'RTF-Spec-1.7.rtf'
160   - with OutputCapture() as capturer:
161   - msodde.main(['-d', join(BASE_DIR, 'msodde', filename)])
162   - self.assertEqual(len(self.get_dde_from_output(capturer)), 0,
  159 + output = msodde.process_file(
  160 + join(BASE_DIR, 'msodde', filename), msodde.FIELD_FILTER_DDE)
  161 + self.assertEqual(len(self.get_dde_from_output(output)), 0,
163 162 msg='Found dde links in output of ' + filename)
164 163  
165 164  
... ...
tests/msodde/test_csv.py
... ... @@ -9,7 +9,7 @@ import os
9 9 from os.path import join
10 10  
11 11 from oletools import msodde
12   -from tests.test_utils import OutputCapture, DATA_BASE_DIR
  12 +from tests.test_utils import DATA_BASE_DIR
13 13  
14 14  
15 15 class TestCSV(unittest.TestCase):
... ... @@ -49,7 +49,7 @@ class TestCSV(unittest.TestCase):
49 49  
50 50 sample = \
51 51 prefix.format(quote=quote, delim=delim) + \
52   - quote + sample_core + quote + \
  52 + quote + sample_core + quote + delim + \
53 53 suffix.format(quote=quote, delim=delim)
54 54 output = self.write_and_run(sample)
55 55 n_links = len(self.get_dde_from_output(output))
... ... @@ -69,11 +69,8 @@ class TestCSV(unittest.TestCase):
69 69 def test_file(self):
70 70 """ test simple small example file """
71 71 filename = join(DATA_BASE_DIR, 'msodde', 'dde-in-csv.csv')
72   - with OutputCapture() as capturer:
73   - capturer.reload_module(msodde) # re-create logger
74   - ret_code = msodde.main([filename, ])
75   - self.assertEqual(ret_code, 0)
76   - links = self.get_dde_from_output(capturer)
  72 + output = msodde.process_file(filename, msodde.FIELD_FILTER_BLACKLIST)
  73 + links = self.get_dde_from_output(output)
77 74 self.assertEqual(len(links), 1)
78 75 self.assertEqual(links[0],
79 76 r"cmd '/k \..\..\..\Windows\System32\calc.exe'")
... ... @@ -91,12 +88,10 @@ class TestCSV(unittest.TestCase):
91 88 if self.DO_DEBUG:
92 89 args += ['-l', 'debug']
93 90  
94   - with OutputCapture() as capturer:
95   - capturer.reload_module(msodde) # re-create logger
96   - ret_code = msodde.main(args)
97   - self.assertEqual(ret_code, 0, 'checking sample resulted in '
98   - 'error:\n' + sample_text)
99   - return capturer
  91 + processed_args = msodde.process_args(args)
  92 +
  93 + return msodde.process_file(
  94 + processed_args.filepath, processed_args.field_filter_mode)
100 95  
101 96 except Exception:
102 97 raise
... ... @@ -111,25 +106,11 @@ class TestCSV(unittest.TestCase):
111 106 os.remove(filename)
112 107 filename = None # just in case
113 108  
114   - def get_dde_from_output(self, capturer):
  109 + @staticmethod
  110 + def get_dde_from_output(output):
115 111 """ helper to read dde links from captured output
116   -
117   - duplicate in tests/msodde/test_basic
118 112 """
119   - have_start_line = False
120   - result = []
121   - for line in capturer:
122   - if self.DO_DEBUG:
123   - print('captured: ' + line)
124   - if not line.strip():
125   - continue # skip empty lines
126   - if have_start_line:
127   - result.append(line)
128   - elif line == 'DDE Links:':
129   - have_start_line = True
130   -
131   - self.assertTrue(have_start_line) # ensure output was complete
132   - return result
  113 + return [o for o in output.splitlines()]
133 114  
134 115 def test_regex(self):
135 116 """ check that regex captures other ways to include dde commands
... ...
tests/oleid/test_basic.py 0 → 100644
  1 +"""
  2 +Test basic functionality of oleid
  3 +
  4 +Should work with python2 and python3!
  5 +"""
  6 +
  7 +import unittest
  8 +import os
  9 +from os.path import join, relpath, splitext
  10 +from oletools import oleid
  11 +
  12 +# Directory with test data, independent of current working directory
  13 +from tests.test_utils import DATA_BASE_DIR
  14 +
  15 +
  16 +class TestOleIDBasic(unittest.TestCase):
  17 + """Test basic functionality of OleID"""
  18 +
  19 + def test_all(self):
  20 + """Run all file in test-data through oleid and compare to known ouput"""
  21 + # this relies on order of indicators being constant, could relax that
  22 + # Also requires that files have the correct suffixes (no rtf in doc)
  23 + NON_OLE_SUFFIXES = ('.xml', '.csv', '.rtf', '')
  24 + NON_OLE_VALUES = (False, )
  25 + WORD = b'Microsoft Office Word'
  26 + PPT = b'Microsoft Office PowerPoint'
  27 + EXCEL = b'Microsoft Excel'
  28 + CRYPT = (True, False, 'unknown', True, False, False, False, False,
  29 + False, False, 0)
  30 + OLE_VALUES = {
  31 + 'oleobj/sample_with_lnk_file.doc': (True, True, WORD, False, True,
  32 + False, False, False, False,
  33 + True, 0),
  34 + 'oleobj/embedded-simple-2007.xlsb': (False,),
  35 + 'oleobj/embedded-simple-2007.docm': (False,),
  36 + 'oleobj/embedded-simple-2007.xltx': (False,),
  37 + 'oleobj/embedded-simple-2007.xlam': (False,),
  38 + 'oleobj/embedded-simple-2007.dotm': (False,),
  39 + 'oleobj/sample_with_lnk_file.ppt': (True, True, PPT, False, False,
  40 + False, False, True, False,
  41 + False, 0),
  42 + 'oleobj/embedded-simple-2007.xlsx': (False,),
  43 + 'oleobj/embedded-simple-2007.xlsm': (False,),
  44 + 'oleobj/embedded-simple-2007.ppsx': (False,),
  45 + 'oleobj/embedded-simple-2007.pps': (True, True, PPT, False, False,
  46 + False, False, True, False,
  47 + False, 0),
  48 + 'oleobj/embedded-simple-2007.xla': (True, True, EXCEL, False,
  49 + False, False, True, False,
  50 + False, False, 0),
  51 + 'oleobj/sample_with_calc_embedded.doc': (True, True, WORD, False,
  52 + True, False, False, False,
  53 + False, True, 0),
  54 + 'oleobj/embedded-unicode-2007.docx': (False,),
  55 + 'oleobj/embedded-unicode.doc': (True, True, WORD, False, True,
  56 + False, False, False, False, True,
  57 + 0),
  58 + 'oleobj/embedded-simple-2007.doc': (True, True, WORD, False, True,
  59 + False, False, False, False,
  60 + True, 0),
  61 + 'oleobj/embedded-simple-2007.xls': (True, True, EXCEL, False,
  62 + False, False, True, False,
  63 + False, False, 0),
  64 + 'oleobj/embedded-simple-2007.dot': (True, True, WORD, False, True,
  65 + False, False, False, False,
  66 + True, 0),
  67 + 'oleobj/sample_with_lnk_to_calc.doc': (True, True, WORD, False,
  68 + True, False, False, False,
  69 + False, True, 0),
  70 + 'oleobj/embedded-simple-2007.ppt': (True, True, PPT, False, False,
  71 + False, False, True, False,
  72 + False, 0),
  73 + 'oleobj/sample_with_lnk_file.pps': (True, True, PPT, False, False,
  74 + False, False, True, False,
  75 + False, 0),
  76 + 'oleobj/embedded-simple-2007.pptx': (False,),
  77 + 'oleobj/embedded-simple-2007.ppsm': (False,),
  78 + 'oleobj/embedded-simple-2007.dotx': (False,),
  79 + 'oleobj/embedded-simple-2007.pptm': (False,),
  80 + 'oleobj/embedded-simple-2007.xlt': (True, True, EXCEL, False,
  81 + False, False, True, False,
  82 + False, False, 0),
  83 + 'oleobj/embedded-simple-2007.docx': (False,),
  84 + 'oleobj/embedded-simple-2007.potx': (False,),
  85 + 'oleobj/embedded-simple-2007.pot': (True, True, PPT, False, False,
  86 + False, False, True, False,
  87 + False, 0),
  88 + 'oleobj/embedded-simple-2007.xltm': (False,),
  89 + 'oleobj/embedded-simple-2007.potm': (False,),
  90 + 'encrypted/encrypted.xlsx': CRYPT,
  91 + 'encrypted/encrypted.docm': CRYPT,
  92 + 'encrypted/encrypted.docx': CRYPT,
  93 + 'encrypted/encrypted.pptm': CRYPT,
  94 + 'encrypted/encrypted.xlsb': CRYPT,
  95 + 'encrypted/encrypted.xls': (True, True, EXCEL, True, False, False,
  96 + True, False, False, False, 0),
  97 + 'encrypted/encrypted.ppt': (True, False, 'unknown', True, False,
  98 + False, False, True, False, False, 0),
  99 + 'encrypted/encrypted.pptx': CRYPT,
  100 + 'encrypted/encrypted.xlsm': CRYPT,
  101 + 'encrypted/encrypted.doc': (True, True, WORD, True, True, False,
  102 + False, False, False, False, 0),
  103 + 'msodde/harmless-clean.docm': (False,),
  104 + 'msodde/dde-in-csv.csv': (False,),
  105 + 'msodde/dde-test-from-office2013-utf_16le-korean.doc':
  106 + (True, True, WORD, False, True, False, False, False, False,
  107 + False, 0),
  108 + 'msodde/harmless-clean.doc': (True, True, WORD, False, True, False,
  109 + False, False, False, False, 0),
  110 + 'msodde/dde-test.docm': (False,),
  111 + 'msodde/dde-test.xlsb': (False,),
  112 + 'msodde/dde-test.xlsm': (False,),
  113 + 'msodde/dde-test.docx': (False,),
  114 + 'msodde/dde-test.xlsx': (False,),
  115 + 'msodde/dde-test-from-office2003.doc': (True, True, WORD, False,
  116 + True, False, False, False,
  117 + False, False, 0),
  118 + 'msodde/dde-test-from-office2016.doc': (True, True, WORD, False,
  119 + True, False, False, False,
  120 + False, False, 0),
  121 + 'msodde/harmless-clean.docx': (False,),
  122 + 'oleform/oleform-PR314.docm': (False,),
  123 + 'basic/encrypted.docx': CRYPT,
  124 + }
  125 +
  126 + indicator_names = []
  127 + for base_dir, _, files in os.walk(DATA_BASE_DIR):
  128 + for filename in files:
  129 + full_path = join(base_dir, filename)
  130 + name = relpath(full_path, DATA_BASE_DIR)
  131 + values = tuple(indicator.value for indicator in
  132 + oleid.OleID(full_path).check())
  133 + if len(indicator_names) < 2: # not initialized with ole yet
  134 + indicator_names = tuple(indicator.name for indicator in
  135 + oleid.OleID(full_path).check())
  136 + suffix = splitext(filename)[1]
  137 + if suffix in NON_OLE_SUFFIXES:
  138 + self.assertEqual(values, NON_OLE_VALUES,
  139 + msg='For non-ole file {} expected {}, '
  140 + 'not {}'.format(name, NON_OLE_VALUES,
  141 + values))
  142 + continue
  143 + try:
  144 + self.assertEqual(values, OLE_VALUES[name],
  145 + msg='Wrong detail values for {}:\n'
  146 + ' Names {}\n Found {}\n Expect {}'
  147 + .format(name, indicator_names, values,
  148 + OLE_VALUES[name]))
  149 + except KeyError:
  150 + print('Should add oleid output for {} to {} ({})'
  151 + .format(name, __name__, values[3:]))
  152 +
  153 +# just in case somebody calls this file as a script
  154 +if __name__ == '__main__':
  155 + unittest.main()
... ...
tests/oleobj/test_external_links.py 0 → 100644
  1 +""" Test that oleobj detects external links in relationships files.
  2 +"""
  3 +
  4 +import unittest
  5 +import os
  6 +from os import path
  7 +
  8 +# Directory with test data, independent of current working directory
  9 +from tests.test_utils import DATA_BASE_DIR
  10 +from oletools import oleobj
  11 +
  12 +BASE_DIR = path.join(DATA_BASE_DIR, 'oleobj', 'external_link')
  13 +
  14 +
  15 +class TestExternalLinks(unittest.TestCase):
  16 + def test_external_links(self):
  17 + """
  18 + loop through sample files asserting that external links are found
  19 + """
  20 +
  21 + for dirpath, _, filenames in os.walk(BASE_DIR):
  22 + for filename in filenames:
  23 + file_path = path.join(dirpath, filename)
  24 +
  25 + ret_val = oleobj.main([file_path])
  26 + self.assertEqual(ret_val, oleobj.RETURN_DID_DUMP)
  27 +
  28 +
  29 +# just in case somebody calls this file as a script
  30 +if __name__ == '__main__':
  31 + unittest.main()
... ...
tests/olevba/__init__.py 0 → 100644
tests/olevba/test_basic.py 0 → 100644
  1 +"""
  2 +Test basic functionality of olevba[3]
  3 +"""
  4 +
  5 +import unittest
  6 +import sys
  7 +if sys.version_info.major <= 2:
  8 + from oletools import olevba
  9 +else:
  10 + from oletools import olevba3 as olevba
  11 +import os
  12 +from os.path import join
  13 +
  14 +# Directory with test data, independent of current working directory
  15 +from tests.test_utils import DATA_BASE_DIR
  16 +
  17 +
  18 +class TestOlevbaBasic(unittest.TestCase):
  19 + """Tests olevba basic functionality"""
  20 +
  21 + def test_crypt_return(self):
  22 + """
  23 + Tests that encrypted files give a certain return code.
  24 +
  25 + Currently, only the encryption applied by Office 2010 (CryptoApi RC4
  26 + Encryption) is tested.
  27 + """
  28 + CRYPT_DIR = join(DATA_BASE_DIR, 'encrypted')
  29 + CRYPT_RETURN_CODE = 9
  30 + ADD_ARGS = [], ['-d', ], ['-a', ], ['-j', ], ['-t', ]
  31 + for filename in os.listdir(CRYPT_DIR):
  32 + full_name = join(CRYPT_DIR, filename)
  33 + for args in ADD_ARGS:
  34 + try:
  35 + ret_code = olevba.main(args + [full_name, ])
  36 + except SystemExit as se:
  37 + ret_code = se.code or 0 # se.code can be None
  38 + self.assertEqual(ret_code, CRYPT_RETURN_CODE,
  39 + msg='Wrong return code {} for args {}'
  40 + .format(ret_code, args + [filename, ]))
  41 +
  42 +
  43 +# just in case somebody calls this file as a script
  44 +if __name__ == '__main__':
  45 + unittest.main()
... ...
tests/ooxml/test_basic.py
... ... @@ -5,7 +5,7 @@ import unittest
5 5 import os
6 6 from os.path import join, splitext
7 7 from tests.test_utils import DATA_BASE_DIR
8   -from oletools.thirdparty.olefile import isOleFile
  8 +from olefile import isOleFile
9 9 from oletools import ooxml
10 10 import logging
11 11  
... ...
tests/test-data/encrypted/encrypted.doc 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.docm 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.docx 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.ppt 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.pptm 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.pptx 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.xls 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.xlsb 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.xlsm 0 → 100644
No preview for this file type
tests/test-data/encrypted/encrypted.xlsx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.docx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.dotx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.potx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.ppsx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.pptx 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsb 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsm 0 → 100644
No preview for this file type
tests/test-data/oleobj/external_link/sample_with_external_link_to_doc.xlsx 0 → 100644
No preview for this file type
tests/test_utils/__init__.py
1   -from .output_capture import OutputCapture
2   -
3 1 from os.path import dirname, join
4 2  
5 3 # Directory with test data, independent of current working directory
... ...
tests/test_utils/output_capture.py deleted
1   -""" class OutputCapture to test what scripts print to stdout """
2   -
3   -from __future__ import print_function
4   -import sys
5   -import logging
6   -
7   -
8   -# python 2/3 version conflict:
9   -if sys.version_info.major <= 2:
10   - from StringIO import StringIO
11   - # reload is a builtin
12   -else:
13   - from io import StringIO
14   - if sys.version_info.minor < 4:
15   - from imp import reload
16   - else:
17   - from importlib import reload
18   -
19   -
20   -class OutputCapture:
21   - """ context manager that captures stdout
22   -
23   - use as follows::
24   -
25   - with OutputCapture() as capturer:
26   - run_my_script(some_args)
27   -
28   - # either test line-by-line ...
29   - for line in capturer:
30   - some_test(line)
31   - # ...or test all output in one go
32   - some_test(capturer.get_data())
33   -
34   - In order to solve issues with old logger instances still remembering closed
35   - StringIO instances as "their" stdout, logging is shutdown and restarted
36   - upon entering this Context Manager. This means that you may have to reload
37   - your module, as well.
38   - """
39   -
40   - def __init__(self):
41   - self.buffer = StringIO()
42   - self.orig_stdout = None
43   - self.data = None
44   -
45   - def __enter__(self):
46   - # Avoid problems with old logger instances that still remember an old
47   - # closed StringIO as their sys.stdout
48   - logging.shutdown()
49   - reload(logging)
50   -
51   - # replace sys.stdout with own buffer.
52   - self.orig_stdout = sys.stdout
53   - sys.stdout = self.buffer
54   - return self
55   -
56   - def __exit__(self, exc_type, exc_value, traceback):
57   - sys.stdout = self.orig_stdout # re-set to original
58   - self.data = self.buffer.getvalue()
59   - self.buffer.close() # close buffer
60   - self.buffer = None
61   -
62   - if exc_type: # there has been an error
63   - print('Got error during output capture!')
64   - print('Print captured output and re-raise:')
65   - for line in self.data.splitlines():
66   - print(line.rstrip()) # print output before re-raising
67   -
68   - def get_data(self):
69   - """ retrieve all the captured data """
70   - if self.buffer is not None:
71   - return self.buffer.getvalue()
72   - elif self.data is not None:
73   - return self.data
74   - else: # should not be possible
75   - raise RuntimeError('programming error or someone messed with data!')
76   -
77   - def __iter__(self):
78   - for line in self.get_data().splitlines():
79   - yield line
80   -
81   - def reload_module(self, mod):
82   - """ Wrapper around reload function for different python versions """
83   - return reload(mod)