Created
July 3, 2019 21:24
-
-
Save chapinb/99bb40b535fc49870b2b5f31808f6779 to your computer and use it in GitHub Desktop.
Checking NTUSER.DAT files for documents with enabled macros
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Script to check the TrustRecords key for documents with enabled macros | |
Prior research/tools: | |
- http://az4n6.blogspot.com/2016/02/more-on-trust-records-macros-and.html | |
- http://windowsir.blogspot.com/2012/07/links-and-updates. | |
Other tools support parsing this key (ie RegRipper plugin TrustRecords) though | |
it's always useful to have more options to parse an artifact. This is just | |
another take on extracting value from this registry key with the hope of | |
getting more folks to check for this value during investigations. | |
TODO | |
==== | |
* Additional testing to look for other meanings within binary values | |
* Testing to validate timestamp stored in registry value (previously documented | |
as document creation time) | |
* Add support for registry log files supported by Yarp | |
* CSV/Other output support | |
* Documentation for use as an imported library/module | |
* Increased logging/error handling | |
""" | |
import argparse | |
import sys | |
import os | |
import logging | |
from datetime import datetime | |
from datetime import timedelta | |
import struct | |
# Install using: pip install https://github.com/msuhanov/yarp/archive/1.0.28.tar.gz | |
from yarp import Registry | |
""" | |
Copyright 2019 Chapin Bryce | |
Permission is hereby granted, free of charge, to any person | |
obtaining a copy of this software and associated documentation | |
files (the "Software"), to deal in the Software without | |
restriction, including without limitation the rights to use, copy, | |
modify, merge, publish, distribute, sublicense, and/or sell copies | |
of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES | |
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | |
DEALINGS IN THE SOFTWARE. | |
""" | |
__author__ = 'Chapin Bryce' | |
__date__ = 20190703 | |
__license__ = 'MIT Copyright 2019 Chapin Bryce' | |
__desc__ = '''Script to parse values about document macro usage''' | |
logger = None | |
macro_enabled_val = 2147483647 | |
def setup_logging(log_path=__file__.rsplit('.', 1)[0]+'.log'): | |
"""Function to setup logging configuration and test it.""" | |
# Allow us to modify the `logger` variable within a function | |
global logger | |
# Set logger object, uses module's name | |
logger = logging.getLogger(name=__file__) | |
# Set default logger level to DEBUG. You can change this later | |
logger.setLevel(logging.DEBUG) | |
# Logging formatter. Best to keep consistent for most usecases | |
log_format = logging.Formatter( | |
'%(asctime)s %(filename)s %(levelname)s %(module)s ' | |
'%(funcName)s %(lineno)d %(message)s') | |
# Setup STDERR logging, allowing you uninterrupted | |
# STDOUT redirection | |
stderr_handle = logging.StreamHandler(stream=sys.stderr) | |
stderr_handle.setLevel(logging.INFO) | |
stderr_handle.setFormatter(log_format) | |
# Setup file logging | |
file_handle = logging.FileHandler(log_path, 'a') | |
file_handle.setLevel(logging.DEBUG) | |
file_handle.setFormatter(log_format) | |
# Add handles | |
logger.addHandler(stderr_handle) | |
logger.addHandler(file_handle) | |
def get_office_versions(reghive): | |
"""Get Office versions within an open Registry hive | |
Args: | |
reghive (yarp.Registry.RegistryHive): Open NTUSER.DAT registry hive | |
Yields: | |
(str): Office version number (ie. '15.0') | |
""" | |
office_versions = reghive.find_key('Software\\Microsoft\\Office') | |
for subkey in office_versions.subkeys(): | |
key_name = subkey.name() | |
is_ver_num = False | |
try: | |
float_val = float(key_name) | |
is_ver_num = True | |
except ValueError as e: | |
is_ver_num = False | |
if is_ver_num: | |
yield key_name | |
def parse_trust_records(reghive): | |
"""Parse trust record values from the root of an open Registry hive | |
Args: | |
reghive (yarp.Registry.RegistryHive): Open NTUSER.DAT registry hive | |
Yields: | |
(dict): document name, date, and whether macros were enabled | |
""" | |
trust_record_path = 'Software\\Microsoft\\Office\\{OFFICE_VERSION}' \ | |
'\\Word\\Security\\Trusted Documents\\TrustRecords' | |
for office_version in get_office_versions(reghive): | |
trust_rec_key = reghive.find_key(trust_record_path.format( | |
OFFICE_VERSION=office_version)) | |
if not trust_rec_key: | |
continue # If office version doesnt have the TrustRecords key, continue | |
for rec in trust_rec_key.values(): | |
date_val, macro_enabled = struct.unpack('q12xI', rec.data()) | |
us = date_val/10.0 | |
dt_date = datetime(1601,1,1) + timedelta(microseconds=us) | |
yield { | |
'doc': rec.name(), | |
'dt': dt_date.isoformat(), | |
'macro': macro_enabled == macro_enabled_val | |
} | |
def main(reg_file): | |
open_hive = Registry.RegistryHive(reg_file) | |
fmt_str = "{dt:20} | {macro:14} | {doc}" | |
print(fmt_str.format(dt="Date Val", macro="Macro Enabled", doc="Document Path")) | |
print('-'*55) | |
for doc in parse_trust_records(open_hive): | |
print(fmt_str.format(**doc)) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
description='Sample Argparse', | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter, | |
epilog=f"Built by {__author__}, v.{__date__}" | |
) | |
parser.add_argument('REG_FILE', help='Path to NTUSER.DAT file to parse', | |
type=argparse.FileType('rb')) | |
parser.add_argument('-l', '--log', help='Path to log file', | |
default=__file__.rsplit('.', 1)[0]+'.log') | |
args = parser.parse_args() | |
setup_logging(args.log) | |
logger.info("Starting script") | |
main(args.REG_FILE) | |
logger.info("Script complete") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment