{"repo": "obsidianforensics/hindsight", "pull_number": 44, "instance_id": "obsidianforensics__hindsight-44", "issue_numbers": "", "base_commit": "191ed9a1dafd223610dd116377675b19b16ba885", "patch": "diff --git a/hindsight.py b/hindsight.py\n--- a/hindsight.py\n+++ b/hindsight.py\n@@ -1,4 +1,4 @@\n-#!/usr/bin/env python\n+#!/usr/bin/env python3\n \n \"\"\"Hindsight - Internet history forensics for Google Chrome/Chromium.\n \n@@ -24,8 +24,8 @@\n try:\n import pytz\n except ImportError:\n- print(\"Couldn't import module 'pytz'; all timestamps in XLSX output will be in examiner local time ({}).\"\n- .format(time.tzname[time.daylight]))\n+ print(f'Couldn\\'t import module \\'pytz\\'; all timestamps in XLSX output '\n+ f'will be in examiner local time ({time.tzname[time.daylight]}).')\n \n \n def parse_arguments(analysis_session):\n@@ -36,17 +36,17 @@ def parse_arguments(analysis_session):\n against the data, and then outputs the results in a spreadsheet. '''.format(pyhindsight.__version__)\n \n epi = '''\n-Example: C:\\>hindsight.py -i \"C:\\Users\\Ryan\\AppData\\Local\\Google\\Chrome\\User Data\\Default\" -o test_case\n+Example: C:\\>hindsight.py -i \"C:\\\\Users\\Ryan\\AppData\\Local\\Google\\Chrome\\\\User Data\\Default\" -o test_case\n \n The Chrome data folder default locations are:\n WinXP: \\Local Settings\\Application Data\\Google\\Chrome\n- \\User Data\\Default\\\\\n- Vista/7/8/10: \\AppData\\Local\\Google\\Chrome\\User Data\\Default\\\\\n+ \\\\User Data\\Default\\\\\n+ Vista/7/8/10: \\AppData\\Local\\Google\\Chrome\\\\User Data\\Default\\\\\n Linux: /.config/google-chrome/Default/\n OS X: /Library/Application Support/Google/Chrome/Default/\n iOS: \\Applications\\com.google.chrome.ios\\Library\\Application Support\n \\Google\\Chrome\\Default\\\\\n- Chromium OS: \\home\\user\\\\\\\n+ Chromium OS: \\home\\\\user\\\\\\\n '''\n \n class MyParser(argparse.ArgumentParser):\n@@ -109,10 +109,10 @@ def error(self, message):\n def main():\n \n def write_excel(analysis_session):\n- import StringIO\n+ import io\n \n # Set up a StringIO object to save the XLSX content to before saving to disk\n- string_buffer = StringIO.StringIO()\n+ string_buffer = io.BytesIO()\n \n # Generate the XLSX content using the function in the AnalysisSession and save it to the StringIO object\n analysis_session.generate_excel(string_buffer)\n@@ -121,7 +121,7 @@ def write_excel(analysis_session):\n string_buffer.seek(0)\n \n # Write the StringIO object to a file on disk named what the user specified\n- with open(\"{}.{}\".format(os.path.join(real_path, analysis_session.output_name), analysis_session.selected_output_format), 'wb') as file_output:\n+ with open(f'{os.path.join(real_path, analysis_session.output_name)}.{analysis_session.selected_output_format}', 'wb') as file_output:\n shutil.copyfileobj(string_buffer, file_output)\n \n def write_sqlite(analysis_session):\n@@ -129,8 +129,8 @@ def write_sqlite(analysis_session):\n \n if os.path.exists(output_file):\n if os.path.getsize(output_file) > 0:\n- print('\\nDatabase file \"{}\" already exists.\\n'.format(output_file))\n- user_input = raw_input('Would you like to (O)verwrite it, (R)ename output file, or (E)xit? ')\n+ print(('\\nDatabase file \"{}\" already exists.\\n'.format(output_file)))\n+ user_input = input('Would you like to (O)verwrite it, (R)ename output file, or (E)xit? ')\n over_re = re.compile(r'(^o$|overwrite)', re.IGNORECASE)\n rename_re = re.compile(r'(^r$|rename)', re.IGNORECASE)\n exit_re = re.compile(r'(^e$|exit)', re.IGNORECASE)\n@@ -139,10 +139,10 @@ def write_sqlite(analysis_session):\n sys.exit()\n elif re.search(over_re, user_input):\n os.remove(output_file)\n- print(\"Deleted old \\\"%s\\\"\" % output_file)\n+ print((\"Deleted old \\\"%s\\\"\" % output_file))\n elif re.search(rename_re, user_input):\n output_file = \"{}_1.sqlite\".format(output_file[:-7])\n- print(\"Renaming new output to {}\".format(output_file))\n+ print((\"Renaming new output to {}\".format(output_file)))\n else:\n print(\"Did not understand response. Exiting... \")\n sys.exit()\n@@ -190,21 +190,22 @@ def write_jsonl(analysis_session):\n .format(pyhindsight.__version__) + '#' * 80)\n \n # Analysis start time\n- print(format_meta_output(\"Start time\", str(datetime.datetime.now())[:-3]))\n+ print((format_meta_output(\"Start time\", str(datetime.datetime.now())[:-3])))\n \n # Read the input directory\n analysis_session.input_path = args.input\n- print(format_meta_output(\"Input directory\", args.input))\n- log.info(\"Reading files from %s\" % args.input)\n+ print((format_meta_output('Input directory', args.input)))\n+ log.info(f'Reading files from {args.input}')\n input_listing = os.listdir(args.input)\n log.debug(\"Input directory contents: \" + str(input_listing))\n \n # Search input directory for browser profiles to analyze\n input_profiles = analysis_session.find_browser_profiles(args.input)\n- log.info(\" - Found {} browser profile(s): {}\".format(len(input_profiles), input_profiles))\n+ log.info(f' - Found {len(input_profiles)} browser profile(s): {input_profiles}')\n analysis_session.profile_paths = input_profiles\n \n- print(format_meta_output(\"Output name\", \"{}.{}\".format(analysis_session.output_name, analysis_session.selected_output_format)))\n+ print((format_meta_output(\n+ 'Output name', f'{analysis_session.output_name}.{analysis_session.selected_output_format}')))\n \n # Run the AnalysisSession\n print(\"\\n Processing:\")\n@@ -224,18 +225,18 @@ def write_jsonl(analysis_session):\n log.debug(\" - Loading '{}'\".format(plugin))\n try:\n module = importlib.import_module(\"pyhindsight.plugins.{}\".format(plugin))\n- except ImportError, e:\n+ except ImportError as e:\n log.error(\" - Error: {}\".format(e))\n- print(format_plugin_output(plugin, \"-unknown\", 'import failed (see log)'))\n+ print((format_plugin_output(plugin, \"-unknown\", 'import failed (see log)')))\n continue\n try:\n log.info(\" - Running '{}' plugin\".format(module.friendlyName))\n parsed_items = module.plugin(analysis_session)\n- print(format_plugin_output(module.friendlyName, module.version, parsed_items))\n+ print((format_plugin_output(module.friendlyName, module.version, parsed_items)))\n log.info(\" - Completed; {}\".format(parsed_items))\n completed_plugins.append(plugin)\n- except Exception, e:\n- print(format_plugin_output(module.friendlyName, module.version, 'failed'))\n+ except Exception as e:\n+ print((format_plugin_output(module.friendlyName, module.version, 'failed')))\n log.info(\" - Failed; {}\".format(e))\n \n # Then look for any custom user-provided plugins in a 'plugins' directory\n@@ -247,7 +248,8 @@ def write_jsonl(analysis_session):\n # Loop through all paths, to pick up all potential locations for custom plugins\n for potential_path in sys.path:\n # If a subdirectory exists called 'plugins' or 'pyhindsight/plugins' at the current path, continue on\n- for potential_plugin_path in [os.path.join(potential_path, 'plugins'), os.path.join(potential_path, 'pyhindsight', 'plugins')]:\n+ for potential_plugin_path in [os.path.join(potential_path, 'plugins'),\n+ os.path.join(potential_path, 'pyhindsight', 'plugins')]:\n if os.path.isdir(potential_plugin_path):\n log.info(\" Found custom plugin directory {}:\".format(potential_plugin_path))\n try:\n@@ -270,18 +272,18 @@ def write_jsonl(analysis_session):\n log.debug(\" - Loading '{}'\".format(plugin))\n try:\n module = __import__(plugin)\n- except ImportError, e:\n+ except ImportError as e:\n log.error(\" - Error: {}\".format(e))\n- print(format_plugin_output(plugin, \"-unknown\", 'import failed (see log)'))\n+ print((format_plugin_output(plugin, \"-unknown\", 'import failed (see log)')))\n continue\n try:\n log.info(\" - Running '{}' plugin\".format(module.friendlyName))\n parsed_items = module.plugin(analysis_session)\n- print(format_plugin_output(module.friendlyName, module.version, parsed_items))\n+ print((format_plugin_output(module.friendlyName, module.version, parsed_items)))\n log.info(\" - Completed; {}\".format(parsed_items))\n completed_plugins.append(plugin)\n- except Exception, e:\n- print(format_plugin_output(module.friendlyName, module.version, 'failed'))\n+ except Exception as e:\n+ print((format_plugin_output(module.friendlyName, module.version, 'failed')))\n log.info(\" - Failed; {}\".format(e))\n except Exception as e:\n log.debug(' - Error loading plugins ({})'.format(e))\n@@ -291,33 +293,34 @@ def write_jsonl(analysis_session):\n sys.path.remove(potential_plugin_path)\n \n # Check if output directory exists; attempt to create if it doesn't\n- if os.path.dirname(analysis_session.output_name) != \"\" and not os.path.exists(os.path.dirname(analysis_session.output_name)):\n+ if os.path.dirname(analysis_session.output_name) != \"\" \\\n+ and not os.path.exists(os.path.dirname(analysis_session.output_name)):\n os.makedirs(os.path.dirname(analysis_session.output_name))\n \n # Get desired output type form args.format and call the correct output creation function\n if analysis_session.selected_output_format == 'xlsx':\n log.info(\"Writing output; XLSX format selected\")\n try:\n- print(\"\\n Writing {}.xlsx\".format(analysis_session.output_name))\n+ print((\"\\n Writing {}.xlsx\".format(analysis_session.output_name)))\n write_excel(analysis_session)\n except IOError:\n type, value, traceback = sys.exc_info()\n- print(value, \"- is the file open? If so, please close it and try again.\")\n+ print((value, \"- is the file open? If so, please close it and try again.\"))\n log.error(\"Error writing XLSX file; type: {}, value: {}, traceback: {}\".format(type, value, traceback))\n \n elif args.format == 'jsonl':\n log.info(\"Writing output; JSONL format selected\")\n- print(\"\\n Writing {}.jsonl\".format(analysis_session.output_name))\n+ print((\"\\n Writing {}.jsonl\".format(analysis_session.output_name)))\n write_jsonl(analysis_session)\n \n elif args.format == 'sqlite':\n log.info(\"Writing output; SQLite format selected\")\n- print(\"\\n Writing {}.sqlite\".format(analysis_session.output_name))\n+ print((\"\\n Writing {}.sqlite\".format(analysis_session.output_name)))\n write_sqlite(analysis_session)\n \n # Display and log finish time\n- print(\"\\n Finish time: {}\".format(str(datetime.datetime.now())[:-3]))\n- log.info(\"Finish time: {}\\n\\n\".format(str(datetime.datetime.now())[:-3]))\n+ print(f'\\n Finish time: {str(datetime.datetime.now())[:-3]}')\n+ log.info(f'Finish time: {str(datetime.datetime.now())[:-3]}\\n\\n')\n \n \n if __name__ == \"__main__\":\ndiff --git a/hindsight_gui.py b/hindsight_gui.py\n--- a/hindsight_gui.py\n+++ b/hindsight_gui.py\n@@ -35,12 +35,12 @@ def get_plugins_info():\n description['version'] = module.version\n try:\n module.plugin()\n- except ImportError, e:\n+ except ImportError as e:\n description['error'] = 'import'\n description['error_msg'] = e\n continue\n \n- except Exception, e:\n+ except Exception as e:\n description['error'] = 'other'\n description['error_msg'] = e\n continue\n@@ -83,12 +83,12 @@ def get_plugins_info():\n description['version'] = module.version\n try:\n module.plugin()\n- except ImportError, e:\n+ except ImportError as e:\n description['error'] = 'import'\n description['error_msg'] = e\n continue\n \n- except Exception, e:\n+ except Exception as e:\n description['error'] = 'other'\n description['error_msg'] = e\n continue\n@@ -99,7 +99,7 @@ def get_plugins_info():\n \n except Exception as e:\n # log.debug(' - Error loading plugins ({})'.format(e))\n- print ' - Error loading plugins'\n+ print(' - Error loading plugins')\n finally:\n # Remove the current plugin location from the system path, so we don't loop over it again\n sys.path.remove(potential_plugin_path)\n@@ -179,9 +179,10 @@ def generate_sqlite():\n # temp file deletion failed\n pass\n \n+ import io\n+ str_io = io.BytesIO()\n analysis_session.generate_sqlite(temp_output)\n- import StringIO\n- str_io = StringIO.StringIO()\n+\n with open(temp_output, 'rb') as f:\n str_io.write(f.read())\n \n@@ -199,18 +200,20 @@ def generate_sqlite():\n \n @bottle.route('/xlsx')\n def generate_xlsx():\n- import StringIO\n- strIO = StringIO.StringIO()\n- analysis_session.generate_excel(strIO)\n- # strIO.write()\n- strIO.seek(0)\n- bottle.response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'\n- bottle.response.headers['Content-Disposition'] = 'attachment; filename=\"{}.xlsx\"'.format(analysis_session.output_name)\n- return strIO.read()\n+ import io\n+ string_buffer = io.BytesIO()\n+ analysis_session.generate_excel(string_buffer)\n+ string_buffer.seek(0)\n+\n+ bottle.response.headers['Content-Type'] = \\\n+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'\n+ bottle.response.headers['Content-Disposition'] = f'attachment; filename=\"{analysis_session.output_name}.xlsx\"'\n+ return string_buffer\n \n \n @bottle.route('/jsonl')\n def generate_jsonl():\n+ # TODO: there has to be a way to do this without making a temp file...\n temp_output = '.tempjsonl'\n try:\n os.remove(temp_output)\n@@ -219,10 +222,11 @@ def generate_jsonl():\n pass\n \n analysis_session.generate_jsonl(temp_output)\n- import StringIO\n- str_io = StringIO.StringIO()\n+ import io\n+ string_buffer = io.BytesIO()\n+\n with open(temp_output, 'rb') as f:\n- str_io.write(f.read())\n+ string_buffer.write(f.read())\n \n try:\n os.remove(temp_output)\n@@ -231,9 +235,9 @@ def generate_jsonl():\n pass\n \n bottle.response.headers['Content-Type'] = 'application/json; charset=UTF-8'\n- bottle.response.headers['Content-Disposition'] = 'attachment; filename={}.jsonl'.format(analysis_session.output_name)\n- str_io.seek(0)\n- return str_io.read()\n+ bottle.response.headers['Content-Disposition'] = f'attachment; filename={analysis_session.output_name}.jsonl'\n+ string_buffer.seek(0)\n+ return string_buffer\n \n \n def main():\ndiff --git a/pyhindsight/__init__.py b/pyhindsight/__init__.py\n--- a/pyhindsight/__init__.py\n+++ b/pyhindsight/__init__.py\n@@ -1,3 +1,3 @@\n __author__ = \"Ryan Benson\"\n-__version__ = \"2.4.0\"\n-__email__ = \"ryan@obsidianforensics.com\"\n+__version__ = \"20200607\"\n+__email__ = \"ryan@dfir.blog\"\ndiff --git a/pyhindsight/analysis.py b/pyhindsight/analysis.py\n--- a/pyhindsight/analysis.py\n+++ b/pyhindsight/analysis.py\n@@ -29,8 +29,8 @@ class HindsightEncoder(json.JSONEncoder):\n @staticmethod\n def base_encoder(history_item):\n item = {'source_short': 'WEBHIST', 'source_long': 'Chrome History',\n- 'parser': 'hindsight/{}'.format(__version__)}\n- for key, value in history_item.__dict__.items():\n+ 'parser': f'hindsight/{__version__}'}\n+ for key, value in list(history_item.__dict__.items()):\n # Drop any keys that have None as value\n if value is None:\n continue\n@@ -39,9 +39,12 @@ def base_encoder(history_item):\n value = value.isoformat()\n \n # JSONL requires utf-8 encoding\n- if isinstance(value, str):\n+ if isinstance(value, bytes) or isinstance(value, bytearray):\n value = value.decode('utf-8', errors='replace')\n \n+ if isinstance(key, bytes) or isinstance(key, bytearray):\n+ key = key.decode('utf-8', errors='replace')\n+\n item[key] = value\n \n item['datetime'] = item['timestamp']\n@@ -56,11 +59,10 @@ def default(self, obj):\n item['timestamp_desc'] = 'Last Visited Time'\n item['data_type'] = 'chrome:history:page_visited'\n item['url_hidden'] = 'true' if item['hidden'] else 'false'\n- if item['visit_duration'] == u'None':\n+ if item['visit_duration'] == 'None':\n del (item['visit_duration'])\n \n- item['message'] = u'{} ({}) [count: {}]'.format(\n- item['url'], item['title'], item['visit_count'])\n+ item['message'] = f\"{item['url']} ({item['title']}) [count: {item['visit_count']}]\"\n \n del(item['name'], item['row_type'], item['visit_time'],\n item['last_visit_time'], item['hidden'])\n@@ -72,10 +74,9 @@ def default(self, obj):\n item['timestamp_desc'] = 'File Downloaded'\n item['data_type'] = 'chrome:history:file_downloaded'\n \n- item['message'] = u'{} ({}). Received {}/{} bytes'.format(\n- item['url'],\n- item['full_path'] if item.get('full_path') else item.get('target_path'),\n- item['received_bytes'], item['total_bytes'])\n+ item['message'] = f\"{item['url']} \" \\\n+ f\"({item['full_path'] if item.get('full_path') else item.get('target_path')}). \" \\\n+ f\"Received {item['received_bytes']}/{item['total_bytes']} bytes\"\n \n del(item['row_type'], item['start_time'])\n return item\n@@ -101,7 +102,7 @@ def default(self, obj):\n item['httponly'] = 'true' if item['httponly'] else 'false'\n item['persistent'] = 'true' if item['persistent'] else 'false'\n \n- item['message'] = u'{} ({}) Flags: [HTTP only] = {} [Persistent] = {}'.format(\n+ item['message'] = '{} ({}) Flags: [HTTP only] = {} [Persistent] = {}'.format(\n item['url'],\n item['cookie_name'],\n item['httponly'], item['persistent'])\n@@ -119,7 +120,7 @@ def default(self, obj):\n item['usage_count'] = item['count']\n item['field_name'] = item['name']\n \n- item['message'] = u'{}: {} (times used: {})'.format(\n+ item['message'] = '{}: {} (times used: {})'.format(\n item['field_name'], item['value'], item['usage_count'])\n \n del(item['name'], item['row_type'], item['count'], item['date_created'])\n@@ -132,7 +133,7 @@ def default(self, obj):\n item['data_type'] = 'chrome:bookmark:entry'\n item['source_long'] = 'Chrome Bookmarks'\n \n- item['message'] = u'{} ({}) bookmarked in folder \"{}\"'.format(\n+ item['message'] = '{} ({}) bookmarked in folder \"{}\"'.format(\n item['name'], item['url'], item['parent_folder'])\n \n del(item['value'], item['row_type'], item['date_added'])\n@@ -145,7 +146,7 @@ def default(self, obj):\n item['data_type'] = 'chrome:bookmark:folder'\n item['source_long'] = 'Chrome Bookmarks'\n \n- item['message'] = u'\"{}\" bookmark folder created in folder \"{}\"'.format(\n+ item['message'] = '\"{}\" bookmark folder created in folder \"{}\"'.format(\n item['name'], item['parent_folder'])\n \n del(item['value'], item['row_type'], item['date_added'])\n@@ -159,7 +160,7 @@ def default(self, obj):\n item['source_long'] = 'Chrome LocalStorage'\n item['url'] = item['url'][1:]\n \n- item['message'] = u'key: {} value: {}'.format(\n+ item['message'] = 'key: {} value: {}'.format(\n item['key'], item['value'])\n \n del (item['row_type'])\n@@ -173,7 +174,7 @@ def default(self, obj):\n item['source_long'] = 'Chrome Logins'\n item['usage_count'] = item['count']\n \n- item['message'] = u'{}: {} used on {} (total times used: {})'.format(\n+ item['message'] = '{}: {} used on {} (total times used: {})'.format(\n item['name'], item['value'], item['url'], item['usage_count'])\n \n del(item['row_type'], item['count'], item['date_created'])\n@@ -186,7 +187,7 @@ def default(self, obj):\n item['data_type'] = 'chrome:preferences:entry'\n item['source_long'] = 'Chrome Preferences'\n \n- item['message'] = u'Updated preference: {}: {})'.format(\n+ item['message'] = 'Updated preference: {}: {})'.format(\n item['key'], item['value'])\n \n del(item['row_type'], item['name'])\n@@ -202,7 +203,7 @@ def default(self, obj):\n item['cache_type'] = item['row_type']\n item['cached_state'] = item['name']\n \n- item['message'] = u'Original URL: {}'.format(\n+ item['message'] = 'Original URL: {}'.format(\n item['original_url'])\n \n del(item['row_type'], item['name'], item['timezone'])\n@@ -210,11 +211,13 @@ def default(self, obj):\n \n \n class AnalysisSession(object):\n- def __init__(self, input_path=None, profile_paths=None, cache_path=None, browser_type=None, available_input_types=None,\n- version=None, display_version=None, output_name=None, log_path=None, timezone=None,\n- available_output_formats=None, selected_output_format=None, available_decrypts=None,\n- selected_decrypts=None, parsed_artifacts=None, artifacts_display=None, artifacts_counts=None,\n- plugin_descriptions=None, selected_plugins=None, plugin_results=None, hindsight_version=None, preferences=None):\n+ def __init__(\n+ self, input_path=None, profile_paths=None, cache_path=None, browser_type=None, available_input_types=None,\n+ version=None, display_version=None, output_name=None, log_path=None, timezone=None,\n+ available_output_formats=None, selected_output_format=None, available_decrypts=None,\n+ selected_decrypts=None, parsed_artifacts=None, artifacts_display=None, artifacts_counts=None,\n+ parsed_storage=None, plugin_descriptions=None, selected_plugins=None, plugin_results=None,\n+ hindsight_version=None, preferences=None):\n self.input_path = input_path\n self.profile_paths = profile_paths\n self.cache_path = cache_path\n@@ -232,6 +235,7 @@ def __init__(self, input_path=None, profile_paths=None, cache_path=None, browser\n self.parsed_artifacts = parsed_artifacts\n self.artifacts_display = artifacts_display\n self.artifacts_counts = artifacts_counts\n+ self.parsed_storage = parsed_storage\n self.plugin_descriptions = plugin_descriptions\n self.selected_plugins = selected_plugins\n self.plugin_results = plugin_results\n@@ -250,6 +254,9 @@ def __init__(self, input_path=None, profile_paths=None, cache_path=None, browser\n if self.artifacts_counts is None:\n self.artifacts_counts = {}\n \n+ if self.parsed_storage is None:\n+ self.parsed_storage = []\n+\n if self.available_output_formats is None:\n self.available_output_formats = ['sqlite', 'jsonl']\n \n@@ -274,7 +281,7 @@ def __init__(self, input_path=None, profile_paths=None, cache_path=None, browser\n \n # Set output name to default if not set by user\n if self.output_name is None:\n- self.output_name = \"Hindsight Report ({})\".format(time.strftime('%Y-%m-%dT%H-%M-%S'))\n+ self.output_name = f'Hindsight Report ({time.strftime(\"%Y-%m-%dT%H-%M-%S\")})'\n \n # Try to import modules for cookie decryption on different OSes.\n # Windows\n@@ -303,7 +310,7 @@ def __init__(self, input_path=None, profile_paths=None, cache_path=None, browser\n @staticmethod\n def sum_dict_counts(dict1, dict2):\n \"\"\"Combine two dicts by summing the values of shared keys\"\"\"\n- for key, value in dict2.items():\n+ for key, value in list(dict2.items()):\n # Case 1: dict2's value for key is a string (aka: it failed)\n if isinstance(value, str):\n # The value should only be non-int if it's a Failed message\n@@ -340,9 +347,9 @@ def is_profile(base_path, existing_files, warn=False):\n `existing_files`. Return True if all required files are present.\n \"\"\"\n is_profile = True\n- for required_file in ['History', 'Cookies']:\n+ for required_file in ['History']:\n # This approach (checking the file names) is naive but should work.\n- if required_file not in existing_files:\n+ if required_file not in existing_files or not os.path.isfile(os.path.join(base_path, required_file)):\n if warn:\n log.warning(\"The profile directory {} does not contain the \"\n \"file {}. Analysis may not be very useful.\"\n@@ -356,7 +363,7 @@ def search_subdirs(self, base_path):\n \n try:\n base_dir_listing = os.listdir(base_path)\n- except Exception, e:\n+ except Exception as e:\n log.warning('Exception reading directory {0:s}; possible permissions issue? Exception: {1:s}'\n .format(base_path, e))\n return found_profile_paths\n@@ -376,9 +383,12 @@ def find_browser_profiles(self, base_path):\n found_profile_paths = []\n base_dir_listing = os.listdir(base_path)\n \n- # The 'History' and 'Cookies' SQLite files are kind of the minimum required for most\n- # Chrome analysis. Warn if they are not present.\n- if not self.is_profile(base_path, base_dir_listing, warn=True):\n+ # The 'History' SQLite file is kind of the minimum required for most\n+ # Chrome analysis. Warn if not present.\n+ if self.is_profile(base_path, base_dir_listing, warn=True):\n+ found_profile_paths.append(base_path)\n+\n+ else:\n # Only search sub dirs if the current dir is not a Profile (Profiles are not nested).\n found_profile_paths.extend(self.search_subdirs(base_path))\n \n@@ -394,7 +404,7 @@ def find_browser_profiles(self, base_path):\n def generate_display_version(self):\n self.version = sorted(self.version)\n if self.version[0] != self.version[-1]:\n- self.display_version = \"%s-%s\" % (self.version[0], self.version[-1])\n+ self.display_version = f'{self.version[0]}-{self.version[-1]}'\n else:\n self.display_version = self.version[0]\n \n@@ -437,6 +447,7 @@ def run(self):\n cache_path=self.cache_path, timezone=self.timezone)\n browser_analysis.process()\n self.parsed_artifacts.extend(browser_analysis.parsed_artifacts)\n+ self.parsed_storage.extend(browser_analysis.parsed_storage)\n self.artifacts_counts = self.sum_dict_counts(self.artifacts_counts, browser_analysis.artifacts_counts)\n self.artifacts_display = browser_analysis.artifacts_display\n self.version.extend(browser_analysis.version)\n@@ -447,15 +458,17 @@ def run(self):\n if isinstance(browser_analysis.__dict__[item], dict):\n try:\n # If the browser_analysis attribute has 'presentation' and 'data' subkeys, promote from\n- if browser_analysis.__dict__[item].get('presentation') and browser_analysis.__dict__[item].get('data'):\n+ if browser_analysis.__dict__[item].get('presentation') and \\\n+ browser_analysis.__dict__[item].get('data'):\n self.promote_object_to_analysis_session(item, browser_analysis.__dict__[item])\n except Exception as e:\n- log.info(\"Exception occurred while analyzing {} for analysis session promotion: {}\".format(item, e))\n+ log.info(f'Exception occurred while analyzing {item} for analysis session promotion: {e}')\n \n elif self.browser_type == \"Brave\":\n browser_analysis = Brave(found_profile_path, timezone=self.timezone)\n browser_analysis.process()\n self.parsed_artifacts = browser_analysis.parsed_artifacts\n+ self.parsed_storage.extend(browser_analysis.parsed_storage)\n self.artifacts_counts = browser_analysis.artifacts_counts\n self.artifacts_display = browser_analysis.artifacts_display\n self.version = browser_analysis.version\n@@ -465,10 +478,11 @@ def run(self):\n if isinstance(browser_analysis.__dict__[item], dict):\n try:\n # If the browser_analysis attribute has 'presentation' and 'data' subkeys, promote from\n- if browser_analysis.__dict__[item].get('presentation') and browser_analysis.__dict__[item].get('data'):\n+ if browser_analysis.__dict__[item].get('presentation') and \\\n+ browser_analysis.__dict__[item].get('data'):\n self.promote_object_to_analysis_session(item, browser_analysis.__dict__[item])\n except Exception as e:\n- log.info(\"Exception occurred while analyzing {} for analysis session promotion: {}\".format(item, e))\n+ log.info(f'Exception occurred while analyzing {item} for analysis session promotion: {e}')\n \n self.generate_display_version()\n \n@@ -491,20 +505,20 @@ def run_plugins(self):\n log.info(\" - Loading '{}' [standard plugin]\".format(plugin))\n try:\n module = importlib.import_module(\"pyhindsight.plugins.{}\".format(plugin))\n- except ImportError, e:\n+ except ImportError as e:\n log.error(\" - Error: {}\".format(e))\n- print format_plugin_output(plugin, \"-unknown\", 'import failed (see log)')\n+ print(format_plugin_output(plugin, \"-unknown\", 'import failed (see log)'))\n continue\n try:\n log.info(\" - Running '{}' plugin\".format(module.friendlyName))\n parsed_items = module.plugin(self)\n- print format_plugin_output(module.friendlyName, module.version, parsed_items)\n+ print(format_plugin_output(module.friendlyName, module.version, parsed_items))\n self.plugin_results[plugin] = [module.friendlyName, module.version, parsed_items]\n log.info(\" - Completed; {}\".format(parsed_items))\n completed_plugins.append(plugin)\n break\n- except Exception, e:\n- print format_plugin_output(module.friendlyName, module.version, 'failed')\n+ except Exception as e:\n+ print(format_plugin_output(module.friendlyName, module.version, 'failed'))\n self.plugin_results[plugin] = [module.friendlyName, module.version, 'failed']\n log.info(\" - Failed; {}\".format(e))\n \n@@ -526,30 +540,30 @@ def run_plugins(self):\n if custom_plugin == plugin:\n # Check to see if we've already run this plugin (likely from a different path)\n if plugin in completed_plugins:\n- log.info(\" - Skipping '{}'; a plugin with that name has run already\".format(plugin))\n+ log.info(f\" - Skipping '{plugin}'; a plugin with that name has run already\")\n continue\n \n log.debug(\" - Loading '{}' [custom plugin]\".format(plugin))\n try:\n module = __import__(plugin)\n- except ImportError, e:\n+ except ImportError as e:\n log.error(\" - Error: {}\".format(e))\n- print format_plugin_output(plugin, \"-unknown\", 'import failed (see log)')\n+ print(format_plugin_output(plugin, \"-unknown\", 'import failed (see log)'))\n continue\n try:\n log.info(\" - Running '{}' plugin\".format(module.friendlyName))\n parsed_items = module.plugin(self)\n- print format_plugin_output(module.friendlyName, module.version, parsed_items)\n+ print(format_plugin_output(module.friendlyName, module.version, parsed_items))\n self.plugin_results[plugin] = [module.friendlyName, module.version, parsed_items]\n log.info(\" - Completed; {}\".format(parsed_items))\n completed_plugins.append(plugin)\n- except Exception, e:\n- print format_plugin_output(module.friendlyName, module.version, 'failed')\n+ except Exception as e:\n+ print(format_plugin_output(module.friendlyName, module.version, 'failed'))\n self.plugin_results[plugin] = [module.friendlyName, module.version, 'failed']\n log.info(\" - Failed; {}\".format(e))\n except Exception as e:\n log.debug(' - Error loading plugins ({})'.format(e))\n- print ' - Error loading plugins'\n+ print(' - Error loading plugins')\n finally:\n # Remove the current plugin location from the system path, so we don't loop over it again\n sys.path.remove(potential_plugin_path)\n@@ -557,7 +571,7 @@ def run_plugins(self):\n def generate_excel(self, output_object):\n import xlsxwriter\n workbook = xlsxwriter.Workbook(output_object, {'in_memory': True})\n- w = workbook.add_worksheet(u'Timeline')\n+ w = workbook.add_worksheet('Timeline')\n \n # Define cell formats\n title_header_format = workbook.add_format({'font_color': 'white', 'bg_color': 'gray', 'bold': 'true'})\n@@ -594,34 +608,34 @@ def generate_excel(self, output_object):\n blue_value_format = workbook.add_format({'font_color': 'blue', 'align': 'left'})\n \n # Title bar\n- w.merge_range('A1:H1', u'Hindsight Internet History Forensics (v%s)' % __version__, title_header_format)\n- w.merge_range('I1:M1', u'URL Specific', center_header_format)\n- w.merge_range('N1:P1', u'Download Specific', center_header_format)\n- w.merge_range('Q1:R1', u'', center_header_format)\n- w.merge_range('S1:U1', u'Cache Specific', center_header_format)\n+ w.merge_range('A1:H1', 'Hindsight Internet History Forensics (v%s)' % __version__, title_header_format)\n+ w.merge_range('I1:M1', 'URL Specific', center_header_format)\n+ w.merge_range('N1:P1', 'Download Specific', center_header_format)\n+ w.merge_range('Q1:R1', '', center_header_format)\n+ w.merge_range('S1:U1', 'Cache Specific', center_header_format)\n \n # Write column headers\n- w.write(1, 0, u'Type', header_format)\n- w.write(1, 1, u'Timestamp ({})'.format(self.timezone), header_format)\n- w.write(1, 2, u'URL', header_format)\n- w.write(1, 3, u'Title / Name / Status', header_format)\n- w.write(1, 4, u'Data / Value / Path', header_format)\n- w.write(1, 5, u'Interpretation', header_format)\n- w.write(1, 6, u'Profile', header_format)\n- w.write(1, 7, u'Source', header_format)\n- w.write(1, 8, u'Duration', header_format)\n- w.write(1, 9, u'Visit Count', header_format)\n- w.write(1, 10, u'Typed Count', header_format)\n- w.write(1, 11, u'URL Hidden', header_format)\n- w.write(1, 12, u'Transition', header_format)\n- w.write(1, 13, u'Interrupt Reason', header_format)\n- w.write(1, 14, u'Danger Type', header_format)\n- w.write(1, 15, u'Opened?', header_format)\n- w.write(1, 16, u'ETag', header_format)\n- w.write(1, 17, u'Last Modified', header_format)\n- w.write(1, 18, u'Server Name', header_format)\n- w.write(1, 19, u'Data Location [Offset]', header_format)\n- w.write(1, 20, u'All HTTP Headers', header_format)\n+ w.write(1, 0, 'Type', header_format)\n+ w.write(1, 1, 'Timestamp ({})'.format(self.timezone), header_format)\n+ w.write(1, 2, 'URL', header_format)\n+ w.write(1, 3, 'Title / Name / Status', header_format)\n+ w.write(1, 4, 'Data / Value / Path', header_format)\n+ w.write(1, 5, 'Interpretation', header_format)\n+ w.write(1, 6, 'Profile', header_format)\n+ w.write(1, 7, 'Source', header_format)\n+ w.write(1, 8, 'Duration', header_format)\n+ w.write(1, 9, 'Visit Count', header_format)\n+ w.write(1, 10, 'Typed Count', header_format)\n+ w.write(1, 11, 'URL Hidden', header_format)\n+ w.write(1, 12, 'Transition', header_format)\n+ w.write(1, 13, 'Interrupt Reason', header_format)\n+ w.write(1, 14, 'Danger Type', header_format)\n+ w.write(1, 15, 'Opened?', header_format)\n+ w.write(1, 16, 'ETag', header_format)\n+ w.write(1, 17, 'Last Modified', header_format)\n+ w.write(1, 18, 'Server Name', header_format)\n+ w.write(1, 19, 'Data Location [Offset]', header_format)\n+ w.write(1, 20, 'All HTTP Headers', header_format)\n \n # Set column widths\n w.set_column('A:A', 16) # Type\n@@ -690,9 +704,9 @@ def generate_excel(self, output_object):\n w.write(row_number, 14, item.danger_type_friendly, green_value_format) # danger type\n open_friendly = \"\"\n if item.opened == 1:\n- open_friendly = u'Yes'\n+ open_friendly = 'Yes'\n elif item.opened == 0:\n- open_friendly = u'No'\n+ open_friendly = 'No'\n w.write_string(row_number, 15, open_friendly, green_value_format) # opened\n w.write(row_number, 16, item.etag, green_value_format) # ETag\n w.write(row_number, 17, item.last_modified, green_value_format) # Last Modified\n@@ -726,8 +740,8 @@ def generate_excel(self, output_object):\n w.write(row_number, 1, friendly_date(item.timestamp), gray_date_format) # date\n try:\n w.write_string(row_number, 2, item.url, gray_url_format) # URL\n- except Exception, e:\n- print e, item.url, item.location\n+ except Exception as e:\n+ print(e, item.url, item.location)\n w.write_string(row_number, 3, str(item.name), gray_field_format) # cached status // Normal (data cached)\n w.write_string(row_number, 4, item.value, gray_value_format) # content-type (size) // image/jpeg (2035 bytes)\n w.write(row_number, 5, item.interpretation, gray_value_format) # cookie interpretation\n@@ -764,8 +778,8 @@ def generate_excel(self, output_object):\n w.write(row_number, 5, item.interpretation, blue_value_format) # interpretation\n w.write(row_number, 6, item.profile, blue_value_format) # Profile\n \n- except Exception, e:\n- log.error(\"Failed to write row to XLSX: {}\".format(e))\n+ except Exception as e:\n+ log.error(f'Failed to write row to XLSX: {e}')\n \n row_number += 1\n \n@@ -773,6 +787,59 @@ def generate_excel(self, output_object):\n w.freeze_panes(2, 0) # Freeze top row\n w.autofilter(1, 0, row_number, 19) # Add autofilter\n \n+ s = workbook.add_worksheet('Storage')\n+ # Title bar\n+ s.merge_range('A1:G1', f'Hindsight Internet History Forensics (v{__version__})', title_header_format)\n+\n+ # Write column headers\n+ s.write(1, 0, 'Type', header_format)\n+ s.write(1, 1, 'Origin', header_format)\n+ s.write(1, 2, 'Key', header_format)\n+ s.write(1, 3, 'Value', header_format)\n+ s.write(1, 4, 'Modification Time ({})'.format(self.timezone), header_format)\n+ s.write(1, 5, 'Interpretation', header_format)\n+ s.write(1, 6, 'Profile', header_format)\n+ \n+ # Set column widths\n+ s.set_column('A:A', 16) # Type\n+ s.set_column('B:B', 30) # Origin\n+ s.set_column('C:C', 35) # Key\n+ s.set_column('D:D', 60) # Value\n+ s.set_column('E:E', 16) # Mod Time\n+ s.set_column('F:F', 50) # Interpretation\n+ s.set_column('G:G', 50) # Profile\n+\n+ # Start at the row after the headers, and begin writing out the items in parsed_artifacts\n+ row_number = 2\n+ for item in self.parsed_storage:\n+ try:\n+ if item.row_type.startswith(\"file system\"):\n+ s.write_string(row_number, 0, item.row_type, black_type_format)\n+ s.write_string(row_number, 1, item.origin, black_url_format)\n+ s.write_string(row_number, 2, item.key, black_field_format)\n+ s.write_string(row_number, 3, item.value, black_value_format)\n+ s.write(row_number, 4, friendly_date(item.last_modified), black_date_format)\n+ s.write(row_number, 5, item.interpretation, black_value_format)\n+ s.write(row_number, 6, item.profile, black_value_format)\n+\n+ elif item.row_type.startswith(\"local storage\"):\n+ s.write_string(row_number, 0, item.row_type, black_type_format)\n+ s.write_string(row_number, 1, item.origin, black_url_format)\n+ s.write_string(row_number, 2, item.key, black_field_format)\n+ s.write_string(row_number, 3, item.value, black_value_format)\n+ s.write(row_number, 4, friendly_date(item.last_modified), black_date_format)\n+ s.write(row_number, 5, item.interpretation, black_value_format)\n+ s.write(row_number, 6, item.profile, black_value_format)\n+\n+ except Exception as e:\n+ log.error(f'Failed to write row to XLSX: {e}')\n+\n+ row_number += 1\n+\n+ # Formatting\n+ s.freeze_panes(2, 0) # Freeze top row\n+ s.autofilter(1, 0, row_number, 6) # Add autofilter\n+\n for item in self.__dict__:\n try:\n if self.__dict__[item]['presentation'] and self.__dict__[item]['data']:\n@@ -782,7 +849,7 @@ def generate_excel(self, output_object):\n title = d['presentation']['title']\n if 'version' in d['presentation']:\n title += \" (v{})\".format(d['presentation']['version'])\n- p.merge_range(0, 0, 0, len(d['presentation']['columns']) - 1, \"{}\".format(title), title_header_format)\n+ p.merge_range(0, 0, 0, len(d['presentation']['columns']) - 1, f\"{title}\", title_header_format)\n for counter, column in enumerate(d['presentation']['columns']):\n # print column\n p.write(1, counter, column['display_name'], header_format)\n@@ -814,9 +881,8 @@ def generate_excel(self, output_object):\n title = d['presentation']['title']\n if 'version' in d['presentation']:\n title += \" (v{})\".format(d['presentation']['version'])\n- p.merge_range(0, 0, 0, len(d['presentation']['columns']) - 1, \"{}\".format(title), title_header_format)\n+ p.merge_range(0, 0, 0, len(d['presentation']['columns']) - 1, f\"{title}\", title_header_format)\n for counter, column in enumerate(d['presentation']['columns']):\n- # print column\n p.write(1, counter, column['display_name'], header_format)\n if 'display_width' in column:\n p.set_column(counter, counter, column['display_width'])\n@@ -842,89 +908,125 @@ def generate_excel(self, output_object):\n def generate_sqlite(self, output_file_path='.temp_db'):\n \n output_db = sqlite3.connect(output_file_path)\n- output_db.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')\n+ output_db.text_factory = lambda x: str(x, 'utf-8', 'ignore')\n \n with output_db:\n c = output_db.cursor()\n- c.execute(\"CREATE TABLE timeline(type TEXT, timestamp TEXT, url TEXT, title TEXT, value TEXT, \"\n- \"interpretation TEXT, profile TEXT, source TEXT, visit_duration TEXT, visit_count INT, typed_count INT, \"\n- \"url_hidden INT, transition TEXT, interrupt_reason TEXT, danger_type TEXT, opened INT, etag TEXT, \"\n- \"last_modified TEXT, server_name TEXT, data_location TEXT, http_headers TEXT)\")\n-\n- c.execute(\"CREATE TABLE installed_extensions(name TEXT, description TEXT, version TEXT, app_id TEXT, profile TEXT)\")\n-\n- for item in self.parsed_artifacts:\n- if item.row_type.startswith(\"url\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, interpretation, profile, source, visit_duration, visit_count, \"\n- \"typed_count, url_hidden, transition) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.interpretation, item.profile,\n- item.visit_source, item.visit_duration, item.visit_count, item.typed_count, item.hidden, item.transition_friendly))\n-\n- elif item.row_type.startswith(\"autofill\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.name, item.value, item.interpretation, item.profile))\n-\n- elif item.row_type.startswith(\"download\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile, \"\n- \"interrupt_reason, danger_type, opened, etag, last_modified) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.status_friendly, item.value,\n- item.interpretation, item.profile, item.interrupt_reason_friendly, item.danger_type_friendly,\n- item.opened, item.etag, item.last_modified))\n-\n- elif item.row_type.startswith(\"bookmark folder\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.name, item.value,\n- item.interpretation, item.profile))\n-\n- elif item.row_type.startswith(\"bookmark\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n- item.interpretation, item.profile))\n-\n- elif item.row_type.startswith(\"cookie\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n- item.interpretation, item.profile))\n-\n- elif item.row_type.startswith(\"local storage\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n- item.interpretation, item.profile))\n-\n- elif item.row_type.startswith(\"cache\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile, \"\n- \"etag, last_modified, server_name, data_location)\"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, str(item.name), item.value,\n- item.interpretation, item.profile, item.etag, item.last_modified, item.server_name, item.location))\n+ c.execute(\n+ 'CREATE TABLE timeline(type TEXT, timestamp TEXT, url TEXT, title TEXT, value TEXT, '\n+ 'interpretation TEXT, profile TEXT, source TEXT, visit_duration TEXT, visit_count INT, '\n+ 'typed_count INT, url_hidden INT, transition TEXT, interrupt_reason TEXT, danger_type TEXT, '\n+ 'opened INT, etag TEXT, last_modified TEXT, server_name TEXT, data_location TEXT, http_headers TEXT)')\n \n- elif item.row_type.startswith(\"login\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n- item.interpretation, item.profile))\n+ c.execute(\n+ 'CREATE TABLE storage(type TEXT, origin TEXT, key TEXT, value TEXT, modification_time TEXT, '\n+ 'interpretation TEXT, profile TEXT)')\n \n- elif item.row_type.startswith(\"preference\"):\n- c.execute(\"INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) \"\n- \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n- (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n- item.interpretation, item.profile))\n+ c.execute(\n+ 'CREATE TABLE installed_extensions(name TEXT, description TEXT, version TEXT, app_id TEXT, '\n+ 'profile TEXT)')\n \n- if self.__dict__.get(\"installed_extensions\"):\n+ for item in self.parsed_artifacts:\n+ if item.row_type.startswith('url'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, interpretation, profile, source, '\n+ 'visit_duration, visit_count, typed_count, url_hidden, transition) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', \n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.interpretation, \n+ item.profile, item.visit_source, item.visit_duration, item.visit_count, item.typed_count, \n+ item.hidden, item.transition_friendly))\n+\n+ elif item.row_type.startswith('autofill'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.name, item.value, item.interpretation,\n+ item.profile))\n+\n+ elif item.row_type.startswith('download'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile, '\n+ 'interrupt_reason, danger_type, opened, etag, last_modified) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.status_friendly, item.value,\n+ item.interpretation, item.profile, item.interrupt_reason_friendly, item.danger_type_friendly,\n+ item.opened, item.etag, item.last_modified))\n+\n+ elif item.row_type.startswith('bookmark folder'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ elif item.row_type.startswith('bookmark'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ elif item.row_type.startswith('cookie'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ elif item.row_type.startswith('local storage'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ elif item.row_type.startswith('cache'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile, '\n+ 'etag, last_modified, server_name, data_location)'\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, str(item.name), item.value,\n+ item.interpretation, item.profile, item.etag, item.last_modified, item.server_name,\n+ item.location))\n+\n+ elif item.row_type.startswith('login'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ elif item.row_type.startswith('preference'):\n+ c.execute(\n+ 'INSERT INTO timeline (type, timestamp, url, title, value, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, friendly_date(item.timestamp), item.url, item.name, item.value,\n+ item.interpretation, item.profile))\n+\n+ for item in self.parsed_storage:\n+ if item.row_type.startswith('local'):\n+ c.execute(\n+ 'INSERT INTO storage (type, origin, key, value, modification_time, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, item.origin, item.key, item.value, item.last_modified, item.interpretation,\n+ item.profile))\n+\n+ if item.row_type.startswith('file system'):\n+ c.execute(\n+ 'INSERT INTO storage (type, origin, key, value, modification_time, interpretation, profile) '\n+ 'VALUES (?, ?, ?, ?, ?, ?, ?)',\n+ (item.row_type, item.origin, item.key, item.value, item.last_modified, item.interpretation,\n+ item.profile))\n+\n+ if self.__dict__.get('installed_extensions'):\n for extension in self.installed_extensions['data']:\n- c.execute(\"INSERT INTO installed_extensions (name, description, version, app_id, profile) \"\n- \"VALUES (?, ?, ?, ?, ?)\",\n- (extension.name, extension.description, extension.version, extension.app_id, extension.profile))\n+ c.execute(\n+ 'INSERT INTO installed_extensions (name, description, version, app_id, profile) '\n+ 'VALUES (?, ?, ?, ?, ?)',\n+ (extension.name, extension.description, extension.version, extension.app_id, extension.profile))\n \n def generate_jsonl(self, output_file):\n- with open(output_file, mode='wb') as jsonl:\n+ with open(output_file, mode='w') as jsonl:\n for parsed_artifact in self.parsed_artifacts:\n parsed_artifact_json = json.dumps(parsed_artifact, cls=HindsightEncoder)\n jsonl.write(parsed_artifact_json)\ndiff --git a/pyhindsight/browsers/brave.py b/pyhindsight/browsers/brave.py\n--- a/pyhindsight/browsers/brave.py\n+++ b/pyhindsight/browsers/brave.py\n@@ -26,7 +26,7 @@ def get_history(self, path, history_file, version, row_type):\n history_json = json.loads(history_raw)\n \n for version_dict in history_json['about']['brave']['versionInformation']:\n- if version_dict['name'] == u'Brave':\n+ if version_dict['name'] == 'Brave':\n self.display_version = version_dict['version']\n \n for s, site in enumerate(history_json['sites']):\n@@ -73,16 +73,16 @@ def process(self):\n custom_type_re = re.compile(r'__([A-z0-9\\._]*)$')\n for input_file in input_listing:\n if re.search(r'session-store-', input_file):\n- row_type = u'url'\n+ row_type = 'url'\n custom_type_m = re.search(custom_type_re, input_file)\n if custom_type_m:\n- row_type = u'url ({})'.format(custom_type_m.group(1))\n+ row_type = 'url ({})'.format(custom_type_m.group(1))\n # self.get_history(args.input, input_file, self.version, row_type)\n self.get_history(self.profile_path, input_file, self.version, row_type)\n display_type = 'URL' if not custom_type_m else 'URL ({})'.format(custom_type_m.group(1))\n self.artifacts_display[input_file] = \"{} records\".format(display_type)\n- print self.format_processing_output(\"{} records\".format(display_type),\n- self.artifacts_counts[input_file])\n+ print((self.format_processing_output(\"{} records\".format(display_type),\n+ self.artifacts_counts[input_file])))\n \n if input_file == 'Partitions':\n partitions = os.listdir(os.path.join(self.profile_path, input_file))\n@@ -91,52 +91,52 @@ def process(self):\n partition_listing = os.listdir(os.path.join(self.profile_path, input_file, partition))\n if 'Cookies' in partition_listing:\n self.get_cookies(partition_path, 'Cookies', [47]) # Parse cookies like a modern Chrome version (v47)\n- print self.format_processing_output(\"Cookie records ({})\".format(partition), self.artifacts_counts['Cookies'])\n+ print((self.format_processing_output(\"Cookie records ({})\".format(partition), self.artifacts_counts['Cookies'])))\n \n if 'Local Storage' in partition_listing:\n self.get_local_storage(partition_path, 'Local Storage')\n- print self.format_processing_output(\"Local Storage records ({})\".format(partition), self.artifacts_counts['Local Storage'])\n+ print((self.format_processing_output(\"Local Storage records ({})\".format(partition), self.artifacts_counts['Local Storage'])))\n \n # Version information is moved to after parsing history, as we read the version from the same file rather than detecting via SQLite table attributes\n- print self.format_processing_output(\"Detected {} version\".format(self.browser_name), self.display_version)\n+ print((self.format_processing_output(\"Detected {} version\".format(self.browser_name), self.display_version)))\n log.info(\"Detected {} version {}\".format(self.browser_name, self.display_version))\n \n if 'Cache' in input_listing:\n- self.get_cache(self.profile_path, 'Cache', row_type=u'cache')\n+ self.get_cache(self.profile_path, 'Cache', row_type='cache')\n self.artifacts_display['Cache'] = \"Cache records\"\n- print self.format_processing_output(self.artifacts_display['Cache'],\n- self.artifacts_counts['Cache'])\n+ print((self.format_processing_output(self.artifacts_display['Cache'],\n+ self.artifacts_counts['Cache'])))\n if 'GPUCache' in input_listing:\n- self.get_cache(self.profile_path, 'GPUCache', row_type=u'cache (gpu)')\n+ self.get_cache(self.profile_path, 'GPUCache', row_type='cache (gpu)')\n self.artifacts_display['GPUCache'] = \"GPU Cache records\"\n- print self.format_processing_output(self.artifacts_display['GPUCache'],\n- self.artifacts_counts['GPUCache'])\n+ print((self.format_processing_output(self.artifacts_display['GPUCache'],\n+ self.artifacts_counts['GPUCache'])))\n \n if 'Cookies' in input_listing:\n self.get_cookies(self.profile_path, 'Cookies', [47]) # Parse cookies like a modern Chrome version (v47)\n self.artifacts_display['Cookies'] = \"Cookie records\"\n- print self.format_processing_output(\"Cookie records\", self.artifacts_counts['Cookies'])\n+ print((self.format_processing_output(\"Cookie records\", self.artifacts_counts['Cookies'])))\n \n if 'Local Storage' in input_listing:\n self.get_local_storage(self.profile_path, 'Local Storage')\n self.artifacts_display['Local Storage'] = \"Local Storage records\"\n- print self.format_processing_output(\"Local Storage records\", self.artifacts_counts['Local Storage'])\n+ print((self.format_processing_output(\"Local Storage records\", self.artifacts_counts['Local Storage'])))\n \n if 'Web Data' in input_listing:\n self.get_autofill(self.profile_path, 'Web Data', [47]) # Parse autofill like a modern Chrome version (v47)\n self.artifacts_display['Autofill'] = \"Autofill records\"\n- print self.format_processing_output(self.artifacts_display['Autofill'],\n- self.artifacts_counts['Autofill'])\n+ print((self.format_processing_output(self.artifacts_display['Autofill'],\n+ self.artifacts_counts['Autofill'])))\n \n if 'Preferences' in input_listing:\n self.get_preferences(self.profile_path, 'Preferences')\n self.artifacts_display['Preferences'] = \"Preference Items\"\n- print self.format_processing_output(\"Preference Items\", self.artifacts_counts['Preferences'])\n+ print((self.format_processing_output(\"Preference Items\", self.artifacts_counts['Preferences'])))\n \n if 'UserPrefs' in input_listing:\n self.get_preferences(self.profile_path, 'UserPrefs')\n self.artifacts_display['UserPrefs'] = \"UserPrefs Items\"\n- print self.format_processing_output(\"UserPrefs Items\", self.artifacts_counts['UserPrefs'])\n+ print((self.format_processing_output(\"UserPrefs Items\", self.artifacts_counts['UserPrefs'])))\n \n # Destroy the cached key so that json serialization doesn't\n # have a cardiac arrest on the non-unicode binary data.\ndiff --git a/pyhindsight/browsers/chrome.py b/pyhindsight/browsers/chrome.py\n--- a/pyhindsight/browsers/chrome.py\n+++ b/pyhindsight/browsers/chrome.py\n@@ -6,11 +6,10 @@\n import re\n import struct\n import json\n-import codecs\n import logging\n import shutil\n from pyhindsight.browsers.webbrowser import WebBrowser\n-from pyhindsight.utils import friendly_date, to_datetime\n+from pyhindsight import utils\n \n # Try to import optionally modules - do nothing on failure, as status is tracked elsewhere\n try:\n@@ -34,11 +33,11 @@\n \n class Chrome(WebBrowser):\n def __init__(self, profile_path, browser_name=None, cache_path=None, version=None, timezone=None,\n- parsed_artifacts=None, storage=None, installed_extensions=None, artifacts_counts=None, artifacts_display=None,\n+ parsed_artifacts=None, parsed_storage=None, storage=None, installed_extensions=None, artifacts_counts=None, artifacts_display=None,\n available_decrypts=None, preferences=None):\n- # TODO: try to fix this to use super()\n WebBrowser.__init__(self, profile_path, browser_name=browser_name, cache_path=cache_path, version=version,\n- timezone=timezone, parsed_artifacts=parsed_artifacts, artifacts_counts=artifacts_counts,\n+ timezone=timezone, parsed_artifacts=parsed_artifacts, parsed_storage=parsed_storage,\n+ artifacts_counts=artifacts_counts,\n artifacts_display=artifacts_display, preferences=preferences)\n self.profile_path = profile_path\n self.browser_name = \"Chrome\"\n@@ -59,6 +58,9 @@ def __init__(self, profile_path, browser_name=None, cache_path=None, version=Non\n if self.parsed_artifacts is None:\n self.parsed_artifacts = []\n \n+ if self.parsed_storage is None:\n+ self.parsed_storage = []\n+\n if self.installed_extensions is None:\n self.installed_extensions = []\n \n@@ -94,7 +96,8 @@ def determine_version(self):\n Based on research I did to create \"Chrome Evolution\" tool - dfir.blog/chrome-evolution\n \"\"\"\n \n- possible_versions = range(1, 77)\n+ possible_versions = list(range(1, 84))\n+ # TODO: remove 82?\n previous_possible_versions = possible_versions[:]\n \n def update_and_rollback_if_empty(version_list, prev_version_list):\n@@ -129,87 +132,100 @@ def trim_lesser_versions(version):\n \"\"\"Remove version numbers < 'version' from 'possible_versions'\"\"\"\n possible_versions[:] = [x for x in possible_versions if x >= version]\n \n- if 'History' in self.structure.keys():\n- log.debug(\"Analyzing 'History' structure\")\n- log.debug(\" - Starting possible versions: {}\".format(possible_versions))\n- if 'visits' in self.structure['History'].keys():\n+ if 'History' in list(self.structure.keys()):\n+ log.debug('Analyzing \\'History\\' structure')\n+ log.debug(f' - Starting possible versions: {possible_versions}')\n+ if 'visits' in list(self.structure['History'].keys()):\n trim_lesser_versions_if('visit_duration', self.structure['History']['visits'], 20)\n trim_lesser_versions_if('incremented_omnibox_typed_score', self.structure['History']['visits'], 68)\n- if 'visit_source' in self.structure['History'].keys():\n+ if 'visit_source' in list(self.structure['History'].keys()):\n trim_lesser_versions_if('source', self.structure['History']['visit_source'], 7)\n- if 'downloads' in self.structure['History'].keys():\n+ if 'downloads' in list(self.structure['History'].keys()):\n trim_lesser_versions_if('target_path', self.structure['History']['downloads'], 26)\n trim_lesser_versions_if('opened', self.structure['History']['downloads'], 16)\n trim_lesser_versions_if('etag', self.structure['History']['downloads'], 30)\n trim_lesser_versions_if('original_mime_type', self.structure['History']['downloads'], 37)\n trim_lesser_versions_if('last_access_time', self.structure['History']['downloads'], 59)\n- if 'downloads_slices' in self.structure['History'].keys():\n+ if 'downloads_slices' in list(self.structure['History'].keys()):\n trim_lesser_versions(58)\n- log.debug(\" - Finishing possible versions: {}\".format(possible_versions))\n+ log.debug(f' - Finishing possible versions: {possible_versions}')\n \n # the pseudo-History file generated by the ChromeNative Volatility plugin should use the v30 query\n- elif (db.startswith('History__') for db in self.structure.keys()):\n+ elif (db.startswith('History__') for db in list(self.structure.keys())):\n trim_lesser_versions(30)\n \n- possible_versions, previous_possible_versions = update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n+ possible_versions, previous_possible_versions = \\\n+ update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n \n- if 'Cookies' in self.structure.keys():\n+ if 'Cookies' in list(self.structure.keys()):\n log.debug(\"Analyzing 'Cookies' structure\")\n- log.debug(\" - Starting possible versions: {}\".format(possible_versions))\n- if 'cookies' in self.structure['Cookies'].keys():\n+ log.debug(f' - Starting possible versions: {possible_versions}')\n+ if 'cookies' in list(self.structure['Cookies'].keys()):\n+ trim_lesser_versions_if('source_scheme', self.structure['Cookies']['cookies'], 80)\n trim_lesser_versions_if('samesite', self.structure['Cookies']['cookies'], 76)\n trim_lesser_versions_if('is_persistent', self.structure['Cookies']['cookies'], 66)\n- trim_lesser_versions_if('priority', self.structure['Cookies']['cookies'], 28)\n trim_lesser_versions_if('encrypted_value', self.structure['Cookies']['cookies'], 33)\n- log.debug(\" - Finishing possible versions: {}\".format(possible_versions))\n+ trim_lesser_versions_if('priority', self.structure['Cookies']['cookies'], 28)\n+ log.debug(f' - Finishing possible versions: {possible_versions}')\n \n- possible_versions, previous_possible_versions = update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n+ possible_versions, previous_possible_versions = \\\n+ update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n \n- if 'Web Data' in self.structure.keys():\n+ if 'Web Data' in list(self.structure.keys()):\n log.debug(\"Analyzing 'Web Data' structure\")\n- log.debug(\" - Starting possible versions: {}\".format(possible_versions))\n- if 'autofill' in self.structure['Web Data'].keys():\n+ log.debug(f' - Starting possible versions: {possible_versions}')\n+ if 'autofill' in list(self.structure['Web Data'].keys()):\n trim_lesser_versions_if('name', self.structure['Web Data']['autofill'], 2)\n trim_lesser_versions_if('date_created', self.structure['Web Data']['autofill'], 35)\n- if 'autofill_profiles' in self.structure['Web Data'].keys():\n+ if 'autofill_profiles' in list(self.structure['Web Data'].keys()):\n trim_lesser_versions_if('language_code', self.structure['Web Data']['autofill_profiles'], 36)\n trim_lesser_versions_if('validity_bitfield', self.structure['Web Data']['autofill_profiles'], 63)\n- trim_lesser_versions_if('is_client_validity_states_updated', self.structure['Web Data']['autofill_profiles'], 71)\n+ trim_lesser_versions_if(\n+ 'is_client_validity_states_updated', self.structure['Web Data']['autofill_profiles'], 71)\n \n- if 'autofill_sync_metadata' in self.structure['Web Data'].keys():\n+ if 'autofill_sync_metadata' in list(self.structure['Web Data'].keys()):\n trim_lesser_versions(57)\n trim_lesser_versions_if('model_type', self.structure['Web Data']['autofill_sync_metadata'], 69)\n- if 'web_apps' not in self.structure['Web Data'].keys():\n+ if 'web_apps' not in list(self.structure['Web Data'].keys()):\n trim_lesser_versions(38)\n- if 'credit_cards' in self.structure['Web Data'].keys():\n+ if 'credit_cards' in list(self.structure['Web Data'].keys()):\n trim_lesser_versions_if('billing_address_id', self.structure['Web Data']['credit_cards'], 53)\n- log.debug(\" - Finishing possible versions: {}\".format(possible_versions))\n+ log.debug(f' - Finishing possible versions: {possible_versions}')\n \n- possible_versions, previous_possible_versions = update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n+ possible_versions, previous_possible_versions = \\\n+ update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n \n- if 'Login Data' in self.structure.keys():\n+ if 'Login Data' in list(self.structure.keys()):\n log.debug(\"Analyzing 'Login Data' structure\")\n- log.debug(\" - Starting possible versions: {}\".format(possible_versions))\n- if 'logins' in self.structure['Login Data'].keys():\n+ log.debug(f' - Starting possible versions: {possible_versions}')\n+ if 'logins' in list(self.structure['Login Data'].keys()):\n trim_lesser_versions_if('display_name', self.structure['Login Data']['logins'], 39)\n trim_lesser_versions_if('generation_upload_status', self.structure['Login Data']['logins'], 42)\n trim_greater_versions_if('ssl_valid', self.structure['Login Data']['logins'], 53)\n trim_lesser_versions_if('possible_username_pairs', self.structure['Login Data']['logins'], 59)\n trim_lesser_versions_if('id', self.structure['Login Data']['logins'], 73)\n- log.debug(\" - Finishing possible versions: {}\".format(possible_versions))\n+ if 'field_info' in list(self.structure['Login Data'].keys()):\n+ trim_lesser_versions(80)\n+ if 'compromised_credentials' in list(self.structure['Login Data'].keys()):\n+ trim_lesser_versions(83)\n+ log.debug(f' - Finishing possible versions: {possible_versions}')\n \n- possible_versions, previous_possible_versions = update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n+ possible_versions, previous_possible_versions = \\\n+ update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n \n- if 'Network Action Predictor' in self.structure.keys():\n+ if 'Network Action Predictor' in list(self.structure.keys()):\n log.debug(\"Analyzing 'Network Action Predictor' structure\")\n- log.debug(\" - Starting possible versions: {}\".format(possible_versions))\n- if 'resource_prefetch_predictor_url' in self.structure['Network Action Predictor'].keys():\n+ log.debug(f' - Starting possible versions: {possible_versions}')\n+ if 'resource_prefetch_predictor_url' in list(self.structure['Network Action Predictor'].keys()):\n trim_lesser_versions(22)\n- trim_lesser_versions_if('key', self.structure['Network Action Predictor']['resource_prefetch_predictor_url'], 55)\n- trim_lesser_versions_if('proto', self.structure['Network Action Predictor']['resource_prefetch_predictor_url'], 54)\n- log.debug(\" - Finishing possible versions: {}\".format(possible_versions))\n+ trim_lesser_versions_if(\n+ 'key', self.structure['Network Action Predictor']['resource_prefetch_predictor_url'], 55)\n+ trim_lesser_versions_if(\n+ 'proto', self.structure['Network Action Predictor']['resource_prefetch_predictor_url'], 54)\n+ log.debug(f' - Finishing possible versions: {possible_versions}')\n \n- possible_versions, previous_possible_versions = update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n+ possible_versions, previous_possible_versions = \\\n+ update_and_rollback_if_empty(possible_versions, previous_possible_versions)\n \n self.version = possible_versions\n \n@@ -250,7 +266,7 @@ def get_history(self, path, history_file, version, row_type):\n \n # Get the lowest possible version from the version list, and decrement it until it finds a matching query\n compatible_version = version[0]\n- while compatible_version not in query.keys() and compatible_version > 0:\n+ while compatible_version not in list(query.keys()) and compatible_version > 0:\n compatible_version -= 1\n \n if compatible_version is not 0:\n@@ -279,11 +295,11 @@ def get_history(self, path, history_file, version, row_type):\n duration = datetime.timedelta(microseconds=row.get('visit_duration'))\n \n new_row = Chrome.URLItem(self.profile_path, row.get('id'), row.get('url'), row.get('title'),\n- to_datetime(row.get('visit_time'), self.timezone),\n- to_datetime(row.get('last_visit_time'), self.timezone), row.get('visit_count'),\n+ utils.to_datetime(row.get('visit_time'), self.timezone),\n+ utils.to_datetime(row.get('last_visit_time'), self.timezone), row.get('visit_count'),\n row.get('typed_count'), row.get('from_visit'), row.get('transition'),\n row.get('hidden'), row.get('favicon_id'), row.get('is_indexed'),\n- unicode(duration), row.get('source'))\n+ str(duration), row.get('source'))\n \n # Set the row type as determined earlier\n new_row.row_type = row_type\n@@ -302,7 +318,7 @@ def get_history(self, path, history_file, version, row_type):\n log.info(\" - Parsed {} items\".format(len(results)))\n self.parsed_artifacts.extend(results)\n \n- except Exception, e:\n+ except Exception as e:\n self.artifacts_counts[history_file] = 'Failed'\n log.error(\" - Exeception parsing {}; {}\".format(os.path.join(path, history_file), e))\n \n@@ -333,7 +349,7 @@ def get_downloads(self, path, database, version, row_type):\n \n # Get the lowest possible version from the version list, and decrement it until it finds a matching query\n compatible_version = version[0]\n- while compatible_version not in query.keys() and compatible_version > 0:\n+ while compatible_version not in list(query.keys()) and compatible_version > 0:\n compatible_version -= 1\n \n if compatible_version is not 0:\n@@ -362,8 +378,8 @@ def get_downloads(self, path, database, version, row_type):\n # Using row.get(key) returns 'None' if the key doesn't exist instead of an error\n new_row = Chrome.DownloadItem(self.profile_path, row.get('id'), row.get('url'), row.get('received_bytes'),\n row.get('total_bytes'), row.get('state'), row.get('full_path'),\n- to_datetime(row.get('start_time'), self.timezone),\n- to_datetime(row.get('end_time'), self.timezone), row.get('target_path'),\n+ utils.to_datetime(row.get('start_time'), self.timezone),\n+ utils.to_datetime(row.get('end_time'), self.timezone), row.get('target_path'),\n row.get('current_path'), row.get('opened'), row.get('danger_type'),\n row.get('interrupt_reason'), row.get('etag'), row.get('last_modified'),\n row.get('chain_index'))\n@@ -385,7 +401,7 @@ def get_downloads(self, path, database, version, row_type):\n elif new_row.target_path is not None:\n new_row.value = new_row.target_path\n else:\n- new_row.value = u'Error retrieving download location'\n+ new_row.value = 'Error retrieving download location'\n log.error(\" - Error retrieving download location for download '{}'\".format(new_row.url))\n \n new_row.row_type = row_type\n@@ -453,7 +469,7 @@ def clean(x):\n if decrypted_value is \"\" and self.available_decrypts['linux'] is 1:\n try:\n if not self.cached_key:\n- my_pass = 'peanuts'.encode('utf8')\n+ my_pass = 'peanuts'\n iterations = 1\n self.cached_key = PBKDF2(my_pass, salt, length, iterations)\n decrypted_value = chrome_decrypt(encrypted_value, key=self.cached_key)\n@@ -492,7 +508,7 @@ def get_cookies(self, path, database, version):\n \n # Get the lowest possible version from the version list, and decrement it until it finds a matching query\n compatible_version = version[0]\n- while compatible_version not in query.keys() and compatible_version > 0:\n+ while compatible_version not in list(query.keys()) and compatible_version > 0:\n compatible_version -= 1\n \n if compatible_version is not 0:\n@@ -513,7 +529,7 @@ def get_cookies(self, path, database, version):\n for row in cursor:\n if row.get('encrypted_value') is not None:\n if len(row.get('encrypted_value')) >= 2:\n- cookie_value = self.decrypt_cookie(row.get('encrypted_value')).decode('utf-8')\n+ cookie_value = self.decrypt_cookie(row.get('encrypted_value'))\n else:\n cookie_value = row.get('value')\n else:\n@@ -521,32 +537,32 @@ def get_cookies(self, path, database, version):\n # print type(cookie_value), cookie_value\n \n new_row = Chrome.CookieItem(self.profile_path, row.get('host_key'), row.get('path'), row.get('name'),\n- cookie_value, to_datetime(row.get('creation_utc'), self.timezone),\n- to_datetime(row.get('last_access_utc'), self.timezone),\n+ cookie_value, utils.to_datetime(row.get('creation_utc'), self.timezone),\n+ utils.to_datetime(row.get('last_access_utc'), self.timezone),\n row.get('secure'), row.get('httponly'), row.get('persistent'),\n- row.get('has_expires'), to_datetime(row.get('expires_utc'), self.timezone),\n+ row.get('has_expires'), utils.to_datetime(row.get('expires_utc'), self.timezone),\n row.get('priority'))\n \n accessed_row = Chrome.CookieItem(self.profile_path, row.get('host_key'), row.get('path'),\n row.get('name'), cookie_value,\n- to_datetime(row.get('creation_utc'), self.timezone),\n- to_datetime(row.get('last_access_utc'), self.timezone),\n+ utils.to_datetime(row.get('creation_utc'), self.timezone),\n+ utils.to_datetime(row.get('last_access_utc'), self.timezone),\n row.get('secure'), row.get('httponly'), row.get('persistent'),\n- row.get('has_expires'), to_datetime(row.get('expires_utc'), self.timezone),\n+ row.get('has_expires'), utils.to_datetime(row.get('expires_utc'), self.timezone),\n row.get('priority'))\n \n new_row.url = (new_row.host_key + new_row.path)\n accessed_row.url = (accessed_row.host_key + accessed_row.path)\n \n # Create the row for when the cookie was created\n- new_row.row_type = u'cookie (created)'\n+ new_row.row_type = 'cookie (created)'\n new_row.timestamp = new_row.creation_utc\n results.append(new_row)\n \n # If the cookie was created and accessed at the same time (only used once), or if the last accessed\n # time is 0 (happens on iOS), don't create an accessed row\n- if new_row.creation_utc != new_row.last_access_utc and accessed_row.last_access_utc != to_datetime(0, self.timezone):\n- accessed_row.row_type = u'cookie (accessed)'\n+ if new_row.creation_utc != new_row.last_access_utc and accessed_row.last_access_utc != utils.to_datetime(0, self.timezone):\n+ accessed_row.row_type = 'cookie (accessed)'\n accessed_row.timestamp = accessed_row.last_access_utc\n results.append(accessed_row)\n \n@@ -555,7 +571,7 @@ def get_cookies(self, path, database, version):\n log.info(\" - Parsed {} items\".format(len(results)))\n self.parsed_artifacts.extend(results)\n \n- except Exception, e:\n+ except Exception as e:\n self.artifacts_counts[database] = 'Failed - {}'.format(e)\n log.error(\" - Couldn't open {}\".format(os.path.join(path, database)))\n \n@@ -573,7 +589,7 @@ def get_login_data(self, path, database, version):\n \n # Get the lowest possible version from the version list, and decrement it until it finds a matching query\n compatible_version = version[0]\n- while compatible_version not in query.keys() and compatible_version > 0:\n+ while compatible_version not in list(query.keys()) and compatible_version > 0:\n compatible_version -= 1\n \n if compatible_version is not 0:\n@@ -593,18 +609,18 @@ def get_login_data(self, path, database, version):\n \n for row in cursor:\n if row.get('blacklisted_by_user') == 1:\n- blacklist_row = Chrome.LoginItem(self.profile_path, to_datetime(row.get('date_created'), self.timezone),\n- url=row.get('action_url'), name=row.get('username_element').decode(),\n- value=u'',\n+ blacklist_row = Chrome.LoginItem(self.profile_path, utils.to_datetime(row.get('date_created'), self.timezone),\n+ url=row.get('origin_url'), name=row.get('username_element'),\n+ value='',\n count=row.get('times_used'))\n- blacklist_row.row_type = u'login (blacklist)'\n+ blacklist_row.row_type = 'login (blacklist)'\n results.append(blacklist_row)\n \n if row.get('username_value') is not None and row.get('blacklisted_by_user') == 0:\n- username_row = Chrome.LoginItem(self.profile_path, to_datetime(row.get('date_created'), self.timezone),\n+ username_row = Chrome.LoginItem(self.profile_path, utils.to_datetime(row.get('date_created'), self.timezone),\n url=row.get('action_url'), name=row.get('username_element'),\n value=row.get('username_value'), count=row.get('times_used'))\n- username_row.row_type = u'login (username)'\n+ username_row.row_type = 'login (username)'\n results.append(username_row)\n \n if row.get('password_value') is not None and row.get('blacklisted_by_user') == 0:\n@@ -615,10 +631,10 @@ def get_login_data(self, path, database, version):\n except:\n password = self.decrypt_cookie(row.get('password_value'))\n \n- password_row = Chrome.LoginItem(self.profile_path, to_datetime(row.get('date_created'), self.timezone),\n+ password_row = Chrome.LoginItem(self.profile_path, utils.to_datetime(row.get('date_created'), self.timezone),\n url=row.get('action_url'), name=row.get('password_element'),\n value=password, count=row.get('times_used'))\n- password_row.row_type = u'login (password)'\n+ password_row.row_type = 'login (password)'\n results.append(password_row)\n \n db_file.close()\n@@ -644,7 +660,7 @@ def get_autofill(self, path, database, version):\n \n # Get the lowest possible version from the version list, and decrement it until it finds a matching query\n compatible_version = version[0]\n- while compatible_version not in query.keys() and compatible_version > 0:\n+ while compatible_version not in list(query.keys()) and compatible_version > 0:\n compatible_version -= 1\n \n if compatible_version is not 0:\n@@ -663,11 +679,11 @@ def get_autofill(self, path, database, version):\n cursor.execute(query[compatible_version])\n \n for row in cursor:\n- results.append(Chrome.AutofillItem(self.profile_path, to_datetime(row.get('date_created'), self.timezone),\n+ results.append(Chrome.AutofillItem(self.profile_path, utils.to_datetime(row.get('date_created'), self.timezone),\n row.get('name'), row.get('value'), row.get('count')))\n \n if row.get('date_last_used') and row.get('count') > 1:\n- results.append(Chrome.AutofillItem(self.profile_path, to_datetime(row.get('date_last_used'),\n+ results.append(Chrome.AutofillItem(self.profile_path, utils.to_datetime(row.get('date_last_used'),\n self.timezone), row.get('name'), row.get('value'), row.get('count')))\n \n db_file.close()\n@@ -689,29 +705,29 @@ def get_bookmarks(self, path, file, version):\n bookmarks_path = os.path.join(path, file)\n \n try:\n- bookmarks_file = codecs.open(bookmarks_path, 'rb', encoding='utf-8')\n- decoded_json = json.loads(bookmarks_file.read())\n+ with open(bookmarks_path, encoding='utf-8', errors='replace') as f:\n+ decoded_json = json.loads(f.read())\n+\n log.info(\" - Reading from file '{}'\".format(bookmarks_path))\n \n # TODO: sync_id\n def process_bookmark_children(parent, children):\n for child in children:\n if child[\"type\"] == \"url\":\n- results.append(Chrome.BookmarkItem(self.profile_path, to_datetime(child[\"date_added\"], self.timezone),\n+ results.append(Chrome.BookmarkItem(self.profile_path, utils.to_datetime(child[\"date_added\"], self.timezone),\n child[\"name\"], child[\"url\"], parent))\n elif child[\"type\"] == \"folder\":\n new_parent = parent + \" > \" + child[\"name\"]\n- results.append(Chrome.BookmarkFolderItem(self.profile_path, to_datetime(child[\"date_added\"], self.timezone),\n+ results.append(Chrome.BookmarkFolderItem(self.profile_path, utils.to_datetime(child[\"date_added\"], self.timezone),\n child[\"date_modified\"], child[\"name\"], parent))\n process_bookmark_children(new_parent, child[\"children\"])\n \n- for top_level_folder in decoded_json[\"roots\"].keys():\n+ for top_level_folder in list(decoded_json[\"roots\"].keys()):\n if top_level_folder != \"sync_transaction_version\" and top_level_folder != \"synced\" and top_level_folder != \"meta_info\":\n if decoded_json[\"roots\"][top_level_folder][\"children\"] is not None:\n process_bookmark_children(decoded_json[\"roots\"][top_level_folder][\"name\"],\n decoded_json[\"roots\"][top_level_folder][\"children\"])\n \n- bookmarks_file.close()\n self.artifacts_counts['Bookmarks'] = len(results)\n log.info(\" - Parsed {} items\".format(len(results)))\n self.parsed_artifacts.extend(results)\n@@ -723,60 +739,40 @@ def process_bookmark_children(parent, children):\n \n def get_local_storage(self, path, dir_name):\n results = []\n- illegal_xml_re = re.compile(ur'[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufdd0-\\ufddf\\ufffe-\\uffff]',\n+ illegal_xml_re = re.compile(r'[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufdd0-\\ufddf\\ufffe-\\uffff]',\n re.UNICODE)\n \n # Grab file list of 'Local Storage' directory\n ls_path = os.path.join(path, dir_name)\n- log.info(\"Local Storage:\")\n- log.info(\" - Reading from {}\".format(ls_path))\n+ log.info('Local Storage:')\n+ log.info(f' - Reading from {ls_path}')\n \n local_storage_listing = os.listdir(ls_path)\n- log.debug(\" - {} files in Local Storage directory\".format(len(local_storage_listing)))\n+ log.debug(f' - {len(local_storage_listing)} files in Local Storage directory')\n filtered_listing = []\n \n+ # Chrome v61+ used leveldb for LocalStorage, but kept old SQLite .localstorage files if upgraded.\n if 'leveldb' in local_storage_listing:\n- ls_lvl_db_path = os.path.join(ls_path, 'leveldb')\n- all_ls_lvl_db_pairs = self.get_prefixed_leveldb_pairs(ls_lvl_db_path)\n- for entry in all_ls_lvl_db_pairs:\n- ldb_entry = self.parse_ls_ldb_dict(entry)\n- if ldb_entry:\n- results.append(Chrome.LocalStorageItem(self.profile_path, ldb_entry['origin'],\n- to_datetime(0, self.timezone),\n- ldb_entry['key'], ldb_entry['value']))\n-\n+ ls_ldb_path = os.path.join(ls_path, 'leveldb')\n+ ls_ldb_records = utils.get_ldb_pairs(ls_ldb_path)\n+ for record in ls_ldb_records:\n+ ls_item = self.parse_ls_ldb_record(record)\n+ if ls_item and ls_item.get('record_type') == 'entry':\n+ results.append(Chrome.LocalStorageItem(\n+ self.profile_path, ls_item['origin'], ls_item['key'], ls_item['value']))\n+\n+ # Chrome v60 and earlier used a SQLite file (with a .localstorage file ext) for each origin\n for ls_file in local_storage_listing:\n- if (ls_file[:3] == 'ftp' or ls_file[:4] == 'http' or ls_file[:4] == 'file' or\n- ls_file[:16] == 'chrome-extension') and ls_file[-8:] != '-journal':\n+ if ls_file.startswith(('ftp', 'http', 'file', 'chrome-extension')) and ls_file.endswith('.localstorage'):\n filtered_listing.append(ls_file)\n ls_file_path = os.path.join(ls_path, ls_file)\n ls_created = os.stat(ls_file_path).st_ctime\n \n- def to_unicode(raw_data):\n- if type(raw_data) in (int, long, float):\n- return unicode(raw_data, 'utf-16', errors='replace')\n- elif type(raw_data) is unicode:\n- return raw_data\n- elif type(raw_data) is buffer:\n- try:\n- # When Javascript uses localStorage, it saves everything in UTF-16\n- uni = unicode(raw_data, 'utf-16', errors='replace')\n- # However, some websites use custom compression to squeeze more data in, and just pretend\n- # it's UTF-16, which can result in \"characters\" that are illegal in XML. We need to remove\n- # these so Excel will be able to display the output.\n- # TODO: complete work on decoding the compressed data\n- return illegal_xml_re.sub(u'\\ufffd', uni)\n-\n- except UnicodeDecodeError:\n- return u''\n- else:\n- return u''\n-\n # Connect to Local Storage file sqlite db\n try:\n db_file = sqlite3.connect(ls_file_path)\n except Exception as e:\n- log.warning(\" - Error opening {}: {}\".format(ls_file_path, e))\n+ log.warning(f' - Error opening {ls_file_path}: {e}')\n break\n \n # Use a dictionary cursor\n@@ -786,120 +782,137 @@ def to_unicode(raw_data):\n try:\n cursor.execute('SELECT key,value FROM ItemTable')\n for row in cursor:\n- # Using row.get(key) returns 'None' if the key doesn't exist instead of an error\n- results.append(Chrome.LocalStorageItem(self.profile_path, ls_file.decode(), to_datetime(ls_created, self.timezone),\n- row.get('key'), to_unicode(row.get('value'))))\n+ try:\n+ printable_value = row.get('value', b'').decode('utf-16')\n+ except:\n+ printable_value = repr(row.get('value'))\n+\n+ results.append(Chrome.LocalStorageItem(\n+ profile=self.profile_path, origin=ls_file[:-13], key=row.get('key', ''),\n+ value=printable_value,\n+ last_modified=utils.to_datetime(ls_created, self.timezone)))\n except Exception as e:\n- log.warning(\" - Error reading key/values from {}: {}\".format(ls_file_path, e))\n+ log.warning(f' - Error reading key/values from {ls_file_path}: {e}')\n pass\n \n self.artifacts_counts['Local Storage'] = len(results)\n- log.info(\" - Parsed {} items from {} files\".format(len(results), len(filtered_listing)))\n- self.parsed_artifacts.extend(results)\n+ log.info(f' - Parsed {len(results)} items from {len(filtered_listing)} files')\n+ self.parsed_storage.extend(results)\n \n def get_extensions(self, path, dir_name):\n results = []\n- log.info(\"Extensions:\")\n+ log.info('Extensions:')\n \n # Profile folder\n try:\n profile = os.path.split(path)[1]\n except:\n- profile = \"error\"\n+ profile = 'error'\n \n # Grab listing of 'Extensions' directory\n ext_path = os.path.join(path, dir_name)\n- log.info(\" - Reading from {}\".format(ext_path))\n+ log.info(f' - Reading from {ext_path}')\n ext_listing = os.listdir(ext_path)\n- log.debug(\" - {count} files in Extensions directory: {list}\".format(list=str(ext_listing),\n- count=len(ext_listing)))\n+ log.debug(f' - {len(ext_listing)} files in Extensions directory: {str(ext_listing)}')\n \n # Only process directories with the expected naming convention\n app_id_re = re.compile(r'^([a-z]{32})$')\n ext_listing = [x for x in ext_listing if app_id_re.match(x)]\n- log.debug(\" - {count} files in Extensions directory will be processed: {list}\".format(\n- list=str(ext_listing), count=len(ext_listing)))\n+ log.debug(f' - {len(ext_listing)} files in Extensions directory will be processed: {str(ext_listing)}')\n \n # Process each directory with an app_id name\n for app_id in ext_listing:\n # Get listing of the contents of app_id directory; should contain subdirs for each version of the extension.\n ext_vers_listing = os.path.join(ext_path, app_id)\n ext_vers = os.listdir(ext_vers_listing)\n+ manifest_file = None\n+ selected_version = None\n \n # Connect to manifest.json in latest version directory\n- manifest_path = os.path.join(ext_vers_listing, ext_vers[-1], 'manifest.json')\n- try:\n- manifest_file = codecs.open(manifest_path, 'rb', encoding='utf-8', errors='replace')\n- except IOError:\n- log.error(\" - Error opening {} for extension {}\".format(manifest_path, app_id))\n- break\n+ for version in sorted(ext_vers, reverse=True, key=lambda x: int(x.split('.', maxsplit=1)[0])):\n+ manifest_path = os.path.join(ext_vers_listing, version, 'manifest.json')\n+ try:\n+ with open(manifest_path, encoding='utf-8', errors='replace') as f:\n+ decoded_manifest = json.loads(f.read())\n+ selected_version = version\n+ break\n+ except (IOError, json.JSONDecodeError) as e:\n+ log.error(f' - Error opening {manifest_path} for extension {app_id}; {e}')\n+ continue\n+\n+ if not decoded_manifest:\n+ log.error(f' - Error opening manifest info for extension {app_id}')\n+ continue\n \n name = None\n description = None\n \n- if manifest_file:\n- try:\n- decoded_manifest = json.loads(manifest_file.read())\n- if decoded_manifest[\"name\"][:2] == '__':\n- if decoded_manifest[\"default_locale\"]:\n- locale_messages_path = os.path.join(ext_vers_listing, ext_vers[-1], '_locales',\n- decoded_manifest[\"default_locale\"], 'messages.json')\n- locale_messages_file = codecs.open(locale_messages_path, 'rb', encoding='utf-8',\n- errors='replace')\n- decoded_locale_messages = json.loads(locale_messages_file.read())\n+ try:\n+ if decoded_manifest['name'].startswith('__'):\n+ if decoded_manifest['default_locale']:\n+ locale_messages_path = os.path.join(\n+ ext_vers_listing, selected_version, '_locales', decoded_manifest['default_locale'],\n+ 'messages.json')\n+ with open(locale_messages_path, encoding='utf-8', errors='replace') as f:\n+ decoded_locale_messages = json.loads(f.read())\n+\n+ try:\n+ name = decoded_locale_messages[decoded_manifest['name'][6:-2]]['message']\n+ except KeyError:\n+ try:\n+ name = decoded_locale_messages[decoded_manifest['name'][6:-2]].lower['message']\n+ except KeyError:\n+ try:\n+ # Google Wallet / Chrome Payments is weird/hidden - name is saved different\n+ # than other extensions\n+ name = decoded_locale_messages['app_name']['message']\n+ except:\n+ log.warning(f' - Error reading \\'name\\' for {app_id}')\n+ name = ''\n+ else:\n+ try:\n+ name = decoded_manifest['name']\n+ except KeyError:\n+ name = None\n+ log.error(f' - Error reading \\'name\\' for {app_id}')\n+\n+ if 'description' in list(decoded_manifest.keys()):\n+ if decoded_manifest['description'].startswith('__'):\n+ if decoded_manifest['default_locale']:\n+ locale_messages_path = os.path.join(\n+ ext_vers_listing, selected_version, '_locales', decoded_manifest['default_locale'],\n+ 'messages.json')\n+ with open(locale_messages_path, encoding='utf-8', errors='replace') as f:\n+ decoded_locale_messages = json.loads(f.read())\n+\n try:\n- name = decoded_locale_messages[decoded_manifest[\"name\"][6:-2]][\"message\"]\n+ description = decoded_locale_messages[decoded_manifest['description'][6:-2]]['message']\n except KeyError:\n try:\n- name = decoded_locale_messages[decoded_manifest[\"name\"][6:-2]].lower[\"message\"]\n+ description = decoded_locale_messages[\n+ decoded_manifest['description'][6:-2]].lower['message']\n except KeyError:\n try:\n- # Google Wallet / Chrome Payments is weird/hidden - name is saved different than other extensions\n- name = decoded_locale_messages[\"app_name\"][\"message\"]\n+ # Google Wallet / Chrome Payments is weird/hidden - name is saved different\n+ # than other extensions\n+ description = decoded_locale_messages['app_description']['message']\n except:\n- log.warning(\" - Error reading 'name' for {}\".format(app_id))\n- name = \"\"\n+ description = ''\n+ log.error(f' - Error reading \\'message\\' for {app_id}')\n else:\n try:\n- name = decoded_manifest[\"name\"]\n+ description = decoded_manifest['description']\n except KeyError:\n- name = None\n- log.error(\" - Error reading 'name' for {}\".format(app_id))\n-\n- if \"description\" in decoded_manifest.keys():\n- if decoded_manifest[\"description\"][:2] == '__':\n- if decoded_manifest[\"default_locale\"]:\n- locale_messages_path = os.path.join(ext_vers_listing, ext_vers[-1], '_locales',\n- decoded_manifest[\"default_locale\"], 'messages.json')\n- locale_messages_file = codecs.open(locale_messages_path, 'rb', encoding='utf-8',\n- errors='replace')\n- decoded_locale_messages = json.loads(locale_messages_file.read())\n- try:\n- description = decoded_locale_messages[decoded_manifest[\"description\"][6:-2]][\"message\"]\n- except KeyError:\n- try:\n- description = decoded_locale_messages[decoded_manifest[\"description\"][6:-2]].lower[\"message\"]\n- except KeyError:\n- try:\n- # Google Wallet / Chrome Payments is weird/hidden - name is saved different than other extensions\n- description = decoded_locale_messages[\"app_description\"][\"message\"]\n- except:\n- description = \"\"\n- log.error(\" - Error reading 'message' for {}\".format(app_id))\n- else:\n- try:\n- description = decoded_manifest[\"description\"]\n- except KeyError:\n- description = None\n- log.warning(\" - Error reading 'description' for {}\".format(app_id))\n+ description = None\n+ log.warning(f' - Error reading \\'description\\' for {app_id}')\n \n- results.append(Chrome.BrowserExtension(profile, app_id, name, description, decoded_manifest[\"version\"]))\n- except:\n- log.error(\" - Error decoding manifest file for {}\".format(app_id))\n- pass\n+ results.append(Chrome.BrowserExtension(profile, app_id, name, description, decoded_manifest['version']))\n+ except:\n+ log.error(f' - Error decoding manifest file for {app_id}')\n+ pass\n \n self.artifacts_counts['Extensions'] = len(results)\n- log.info(\" - Parsed {} items\".format(len(results)))\n+ log.info(' - Parsed {} items'.format(len(results)))\n presentation = {'title': 'Installed Extensions',\n 'columns': [\n {'display_name': 'Extension Name',\n@@ -933,16 +946,19 @@ def check_and_append_pref(parent, pref, value=None, description=None):\n 'group': None,\n 'name': pref,\n 'value': value,\n- 'description': description})\n+ 'description': description\n+ })\n+ \n else:\n results.append({\n 'group': None,\n 'name': pref,\n 'value': '',\n- 'description': description})\n+ 'description': description\n+ })\n \n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e}')\n \n def check_and_append_pref_and_children(parent, pref, value=None, description=None):\n # If the preference exists, continue\n@@ -955,13 +971,16 @@ def check_and_append_pref_and_children(parent, pref, value=None, description=Non\n 'group': None,\n 'name': pref,\n 'value': value,\n- 'description': description})\n+ 'description': description\n+ })\n+ \n else:\n results.append({\n 'group': None,\n 'name': pref,\n 'value': '',\n- 'description': description})\n+ 'description': description\n+ })\n \n def append_group(group, description=None):\n # Append the preference group to our results array\n@@ -969,154 +988,150 @@ def append_group(group, description=None):\n 'group': group,\n 'name': None,\n 'value': None,\n- 'description': description})\n+ 'description': description\n+ })\n \n def append_pref(pref, value=None, description=None):\n results.append({\n 'group': None,\n 'name': pref,\n 'value': value,\n- 'description': description})\n+ 'description': description\n+ })\n \n def expand_language_code(code):\n # From https://cs.chromium.org/chromium/src/components/translate/core/browser/translate_language_list.cc\n codes = {\n- \"af\": \"Afrikaans\",\n- \"am\": \"Amharic\",\n- \"ar\": \"Arabic\",\n- \"az\": \"Azerbaijani\",\n- \"be\": \"Belarusian\",\n- \"bg\": \"Bulgarian\",\n- \"bn\": \"Bengali\",\n- \"bs\": \"Bosnian\",\n- \"ca\": \"Catalan\",\n- \"ceb\": \"Cebuano\",\n- \"co\": \"Corsican\",\n- \"cs\": \"Czech\",\n- \"cy\": \"Welsh\",\n- \"da\": \"Danish\",\n- \"de\": \"German\",\n- \"el\": \"Greek\",\n- \"en\": \"English\",\n- \"eo\": \"Esperanto\",\n- \"es\": \"Spanish\",\n- \"et\": \"Estonian\",\n- \"eu\": \"Basque\",\n- \"fa\": \"Persian\",\n- \"fi\": \"Finnish\",\n- \"fy\": \"Frisian\",\n- \"fr\": \"French\",\n- \"ga\": \"Irish\",\n- \"gd\": \"Scots Gaelic\",\n- \"gl\": \"Galician\",\n- \"gu\": \"Gujarati\",\n- \"ha\": \"Hausa\",\n- \"haw\": \"Hawaiian\",\n- \"hi\": \"Hindi\",\n- \"hr\": \"Croatian\",\n- \"ht\": \"Haitian Creole\",\n- \"hu\": \"Hungarian\",\n- \"hy\": \"Armenian\",\n- \"id\": \"Indonesian\",\n- \"ig\": \"Igbo\",\n- \"is\": \"Icelandic\",\n- \"it\": \"Italian\",\n- \"iw\": \"Hebrew\",\n- \"ja\": \"Japanese\",\n- \"ka\": \"Georgian\",\n- \"kk\": \"Kazakh\",\n- \"km\": \"Khmer\",\n- \"kn\": \"Kannada\",\n- \"ko\": \"Korean\",\n- \"ku\": \"Kurdish\",\n- \"ky\": \"Kyrgyz\",\n- \"la\": \"Latin\",\n- \"lb\": \"Luxembourgish\",\n- \"lo\": \"Lao\",\n- \"lt\": \"Lithuanian\",\n- \"lv\": \"Latvian\",\n- \"mg\": \"Malagasy\",\n- \"mi\": \"Maori\",\n- \"mk\": \"Macedonian\",\n- \"ml\": \"Malayalam\",\n- \"mn\": \"Mongolian\",\n- \"mr\": \"Marathi\",\n- \"ms\": \"Malay\",\n- \"mt\": \"Maltese\",\n- \"my\": \"Burmese\",\n- \"ne\": \"Nepali\",\n- \"nl\": \"Dutch\",\n- \"no\": \"Norwegian\",\n- \"ny\": \"Nyanja\",\n- \"pa\": \"Punjabi\",\n- \"pl\": \"Polish\",\n- \"ps\": \"Pashto\",\n- \"pt\": \"Portuguese\",\n- \"ro\": \"Romanian\",\n- \"ru\": \"Russian\",\n- \"sd\": \"Sindhi\",\n- \"si\": \"Sinhala\",\n- \"sk\": \"Slovak\",\n- \"sl\": \"Slovenian\",\n- \"sm\": \"Samoan\",\n- \"sn\": \"Shona\",\n- \"so\": \"Somali\",\n- \"sq\": \"Albanian\",\n- \"sr\": \"Serbian\",\n- \"st\": \"Southern Sotho\",\n- \"su\": \"Sundanese\",\n- \"sv\": \"Swedish\",\n- \"sw\": \"Swahili\",\n- \"ta\": \"Tamil\",\n- \"te\": \"Telugu\",\n- \"tg\": \"Tajik\",\n- \"th\": \"Thai\",\n- \"tl\": \"Tagalog\",\n- \"tr\": \"Turkish\",\n- \"uk\": \"Ukrainian\",\n- \"ur\": \"Urdu\",\n- \"uz\": \"Uzbek\",\n- \"vi\": \"Vietnamese\",\n- \"yi\": \"Yiddish\",\n- \"xh\": \"Xhosa\",\n- \"yo\": \"Yoruba\",\n- \"zh-CN\": \"Chinese (Simplified)\",\n- \"zh-TW\": \"Chinese (Traditional)\",\n- \"zu\": \"Zulu\"\n+ 'af': 'Afrikaans',\n+ 'am': 'Amharic',\n+ 'ar': 'Arabic',\n+ 'az': 'Azerbaijani',\n+ 'be': 'Belarusian',\n+ 'bg': 'Bulgarian',\n+ 'bn': 'Bengali',\n+ 'bs': 'Bosnian',\n+ 'ca': 'Catalan',\n+ 'ceb': 'Cebuano',\n+ 'co': 'Corsican',\n+ 'cs': 'Czech',\n+ 'cy': 'Welsh',\n+ 'da': 'Danish',\n+ 'de': 'German',\n+ 'el': 'Greek',\n+ 'en': 'English',\n+ 'eo': 'Esperanto',\n+ 'es': 'Spanish',\n+ 'et': 'Estonian',\n+ 'eu': 'Basque',\n+ 'fa': 'Persian',\n+ 'fi': 'Finnish',\n+ 'fy': 'Frisian',\n+ 'fr': 'French',\n+ 'ga': 'Irish',\n+ 'gd': 'Scots Gaelic',\n+ 'gl': 'Galician',\n+ 'gu': 'Gujarati',\n+ 'ha': 'Hausa',\n+ 'haw': 'Hawaiian',\n+ 'hi': 'Hindi',\n+ 'hr': 'Croatian',\n+ 'ht': 'Haitian Creole',\n+ 'hu': 'Hungarian',\n+ 'hy': 'Armenian',\n+ 'id': 'Indonesian',\n+ 'ig': 'Igbo',\n+ 'is': 'Icelandic',\n+ 'it': 'Italian',\n+ 'iw': 'Hebrew',\n+ 'ja': 'Japanese',\n+ 'ka': 'Georgian',\n+ 'kk': 'Kazakh',\n+ 'km': 'Khmer',\n+ 'kn': 'Kannada',\n+ 'ko': 'Korean',\n+ 'ku': 'Kurdish',\n+ 'ky': 'Kyrgyz',\n+ 'la': 'Latin',\n+ 'lb': 'Luxembourgish',\n+ 'lo': 'Lao',\n+ 'lt': 'Lithuanian',\n+ 'lv': 'Latvian',\n+ 'mg': 'Malagasy',\n+ 'mi': 'Maori',\n+ 'mk': 'Macedonian',\n+ 'ml': 'Malayalam',\n+ 'mn': 'Mongolian',\n+ 'mr': 'Marathi',\n+ 'ms': 'Malay',\n+ 'mt': 'Maltese',\n+ 'my': 'Burmese',\n+ 'ne': 'Nepali',\n+ 'nl': 'Dutch',\n+ 'no': 'Norwegian',\n+ 'ny': 'Nyanja',\n+ 'pa': 'Punjabi',\n+ 'pl': 'Polish',\n+ 'ps': 'Pashto',\n+ 'pt': 'Portuguese',\n+ 'ro': 'Romanian',\n+ 'ru': 'Russian',\n+ 'sd': 'Sindhi',\n+ 'si': 'Sinhala',\n+ 'sk': 'Slovak',\n+ 'sl': 'Slovenian',\n+ 'sm': 'Samoan',\n+ 'sn': 'Shona',\n+ 'so': 'Somali',\n+ 'sq': 'Albanian',\n+ 'sr': 'Serbian',\n+ 'st': 'Southern Sotho',\n+ 'su': 'Sundanese',\n+ 'sv': 'Swedish',\n+ 'sw': 'Swahili',\n+ 'ta': 'Tamil',\n+ 'te': 'Telugu',\n+ 'tg': 'Tajik',\n+ 'th': 'Thai',\n+ 'tl': 'Tagalog',\n+ 'tr': 'Turkish',\n+ 'uk': 'Ukrainian',\n+ 'ur': 'Urdu',\n+ 'uz': 'Uzbek',\n+ 'vi': 'Vietnamese',\n+ 'yi': 'Yiddish',\n+ 'xh': 'Xhosa',\n+ 'yo': 'Yoruba',\n+ 'zh-CN': 'Chinese (Simplified)',\n+ 'zh-TW': 'Chinese (Traditional)',\n+ 'zu': 'Zulu'\n }\n return codes.get(code, code)\n \n results = []\n timestamped_preference_items = []\n- log.info(\"Preferences:\")\n- prefs = None\n+ log.info('Preferences:')\n \n # Open 'Preferences' file\n pref_path = os.path.join(path, preferences_file)\n try:\n- log.info(\" - Reading from {}\".format(pref_path))\n- pref_file = codecs.open(pref_path, 'rb', encoding='utf-8', errors='replace')\n- prefs = json.loads(pref_file.read())\n-\n- except Exception, e:\n- log.exception(\" - Error decoding Preferences file {}\".format(pref_path))\n- self.artifacts_counts[preferences_file] = 'Failed'\n- return\n+ log.info(f' - Reading from {pref_path}')\n+ with open(pref_path, encoding='utf-8', errors='replace') as f:\n+ prefs = json.loads(f.read())\n \n- if not prefs:\n- log.error(\" - Error loading Preferences file {}\".format(pref_path))\n+ except Exception as e:\n+ log.exception(f' - Error decoding Preferences file {pref_path}: {e}')\n self.artifacts_counts[preferences_file] = 'Failed'\n return\n \n # Account Information\n if prefs.get('account_info'):\n- append_group(\"Account Information\")\n+ append_group('Account Information')\n for account in prefs['account_info']:\n- for account_item in account.keys():\n+ for account_item in list(account.keys()):\n append_pref(account_item, account[account_item])\n \n # Local file paths\n- append_group(\"Local file paths\")\n+ append_group('Local file paths')\n if prefs.get('download'):\n check_and_append_pref(prefs['download'], 'default_directory')\n if prefs.get('printing'):\n@@ -1129,22 +1144,24 @@ def expand_language_code(code):\n \n # Autofill\n if prefs.get('autofill'):\n- append_group(\"Autofill\")\n+ append_group('Autofill')\n check_and_append_pref(prefs['autofill'], 'enabled')\n \n # Clearing Chrome Data\n if prefs.get('browser'):\n- append_group(\"Clearing Chrome Data\")\n+ append_group('Clearing Chrome Data')\n if prefs['browser'].get('last_clear_browsing_data_time'):\n- check_and_append_pref(prefs['browser'], 'last_clear_browsing_data_time',\n- friendly_date(prefs['browser']['last_clear_browsing_data_time']),\n- \"Last time the history was cleared\")\n+ check_and_append_pref(\n+ prefs['browser'], 'last_clear_browsing_data_time',\n+ utils.friendly_date(prefs['browser']['last_clear_browsing_data_time']),\n+ 'Last time the history was cleared')\n check_and_append_pref(prefs['browser'], 'clear_lso_data_enabled')\n if prefs['browser'].get('clear_data'):\n try:\n- check_and_append_pref(prefs['browser']['clear_data'], 'time_period',\n- description=\"0: past hour; 1: past day; 2: past week; 3: last 4 weeks; \"\n- \"4: the beginning of time\")\n+ check_and_append_pref(\n+ prefs['browser']['clear_data'], 'time_period',\n+ description='0: past hour; 1: past day; 2: past week; 3: last 4 weeks; '\n+ '4: the beginning of time')\n check_and_append_pref(prefs['browser']['clear_data'], 'content_licenses')\n check_and_append_pref(prefs['browser']['clear_data'], 'hosted_apps_data')\n check_and_append_pref(prefs['browser']['clear_data'], 'cookies')\n@@ -1152,41 +1169,42 @@ def expand_language_code(code):\n check_and_append_pref(prefs['browser']['clear_data'], 'browsing_history')\n check_and_append_pref(prefs['browser']['clear_data'], 'passwords')\n check_and_append_pref(prefs['browser']['clear_data'], 'form_data')\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n+\n+ append_group('Per Host Zoom Levels', 'These settings persist even when the history is cleared, and may be '\n+ 'useful in some cases.')\n \n- append_group(\"Per Host Zoom Levels\", \"These settings persist even when the history is cleared, and may be \"\n- \"useful in some cases.\")\n # There are per_host_zoom_levels keys in at least two locations: profile.per_host_zoom_levels and\n # partition.per_host_zoom_levels.[integer].\n if prefs.get('profile'):\n if prefs['profile'].get('per_host_zoom_levels'):\n try:\n- for zoom in prefs['profile']['per_host_zoom_levels'].keys():\n+ for zoom in list(prefs['profile']['per_host_zoom_levels'].keys()):\n check_and_append_pref(prefs['profile']['per_host_zoom_levels'], zoom)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs.get('partition'):\n if prefs['partition'].get('per_host_zoom_levels'):\n try:\n- for number in prefs['partition']['per_host_zoom_levels'].keys():\n- for zoom in prefs['partition']['per_host_zoom_levels'][number].keys():\n+ for number in list(prefs['partition']['per_host_zoom_levels'].keys()):\n+ for zoom in list(prefs['partition']['per_host_zoom_levels'][number].keys()):\n check_and_append_pref(prefs['partition']['per_host_zoom_levels'][number], zoom)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs.get('profile'):\n if prefs['profile'].get('content_settings'):\n if prefs['profile']['content_settings'].get('pattern_pairs'):\n try:\n- append_group(\"Profile Content Settings\", \"These settings persist even when the history is \"\n- \"cleared, and may be useful in some cases.\")\n- for pair in prefs['profile']['content_settings']['pattern_pairs'].keys():\n+ append_group('Profile Content Settings', 'These settings persist even when the history is '\n+ 'cleared, and may be useful in some cases.')\n+ for pair in list(prefs['profile']['content_settings']['pattern_pairs'].keys()):\n # Adding the space before the domain prevents Excel from freaking out... idk.\n append_pref(' '+str(pair), str(prefs['profile']['content_settings']['pattern_pairs'][pair]))\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs['profile']['content_settings'].get('exceptions'):\n if prefs['profile']['content_settings']['exceptions'].get('media_engagement'):\n@@ -1200,14 +1218,17 @@ def expand_language_code(code):\n # \"visits\": 1\n # }\n try:\n- for origin, pref_data in prefs['profile']['content_settings']['exceptions']['media_engagement'].iteritems():\n- if pref_data.get(\"last_modified\"):\n- pref_item = Chrome.PreferenceItem(self.profile_path, url=origin, timestamp=to_datetime(pref_data[\"last_modified\"], self.timezone),\n- key=\"media_engagement [in {}.profile.content_settings.exceptions]\"\n- .format(preferences_file), value=str(pref_data), interpretation=\"\")\n+ for origin, pref_data in \\\n+ prefs['profile']['content_settings']['exceptions']['media_engagement'].items():\n+ if pref_data.get('last_modified'):\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url=origin, \n+ timestamp=utils.to_datetime(pref_data['last_modified'], self.timezone),\n+ key=f'media_engagement [in {preferences_file}.profile.content_settings.exceptions]', \n+ value=str(pref_data), interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs['profile']['content_settings']['exceptions'].get('notifications'):\n # Example (from in Preferences file):\n@@ -1216,14 +1237,17 @@ def expand_language_code(code):\n # \"setting\": 1\n # }\n try:\n- for origin, pref_data in prefs['profile']['content_settings']['exceptions']['notifications'].iteritems():\n- if pref_data.get(\"last_modified\"):\n- pref_item = Chrome.PreferenceItem(self.profile_path, url=origin, timestamp=to_datetime(pref_data[\"last_modified\"], self.timezone),\n- key=\"notifications [in {}.profile.content_settings.exceptions]\"\n- .format(preferences_file), value=str(pref_data), interpretation=\"\")\n+ for origin, pref_data in \\\n+ prefs['profile']['content_settings']['exceptions']['notifications'].items():\n+ if pref_data.get('last_modified'):\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url=origin, \n+ timestamp=utils.to_datetime(pref_data['last_modified'], self.timezone),\n+ key=f'notifications [in {preferences_file}.profile.content_settings.exceptions]', \n+ value=str(pref_data), interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs['profile']['content_settings']['exceptions'].get('permission_autoblocking_data'):\n # Example (from in Preferences file):\n@@ -1234,14 +1258,17 @@ def expand_language_code(code):\n # \"ignore_count\": 1\n # }}},\n try:\n- for origin, pref_data in prefs['profile']['content_settings']['exceptions']['permission_autoblocking_data'].iteritems():\n- if pref_data.get(\"last_modified\") and pref_data.get(\"last_modified\") != \"0\":\n- pref_item = Chrome.PreferenceItem(self.profile_path, url=origin, timestamp=to_datetime(pref_data[\"last_modified\"], self.timezone),\n- key=\"permission_autoblocking_data [in {}.profile.content_settings.exceptions]\"\n- .format(preferences_file), value=str(pref_data), interpretation=\"\")\n+ for origin, pref_data in \\\n+ prefs['profile']['content_settings']['exceptions']['permission_autoblocking_data'].items():\n+ if pref_data.get('last_modified') and pref_data.get('last_modified') != '0':\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url=origin, \n+ timestamp=utils.to_datetime(pref_data['last_modified'], self.timezone),\n+ key=f'permission_autoblocking_data [in {preferences_file}.profile.content_settings.exceptions]', \n+ value=str(pref_data), interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs['profile']['content_settings']['exceptions'].get('site_engagement'):\n # Example (from in Preferences file):\n@@ -1254,14 +1281,17 @@ def expand_language_code(code):\n # \"rawScore\": 4.5\n # }\n try:\n- for origin, pref_data in prefs['profile']['content_settings']['exceptions']['site_engagement'].iteritems():\n- if pref_data.get(\"last_modified\"):\n- pref_item = Chrome.PreferenceItem(self.profile_path, url=origin, timestamp=to_datetime(pref_data[\"last_modified\"], self.timezone),\n- key=\"site_engagement [in {}.profile.content_settings.exceptions]\"\n- .format(preferences_file), value=str(pref_data), interpretation=\"\")\n+ for origin, pref_data in \\\n+ prefs['profile']['content_settings']['exceptions']['site_engagement'].items():\n+ if pref_data.get('last_modified'):\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url=origin, \n+ timestamp=utils.to_datetime(pref_data['last_modified'], self.timezone),\n+ key=f'site_engagement [in {preferences_file}.profile.content_settings.exceptions]', \n+ value=str(pref_data), interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs['profile']['content_settings']['exceptions'].get('sound'):\n # Example (from in Preferences file):\n@@ -1270,18 +1300,20 @@ def expand_language_code(code):\n # \"setting\": 2\n # }\n try:\n- for origin, pref_data in prefs['profile']['content_settings']['exceptions']['sound'].iteritems():\n- if pref_data.get(\"last_modified\"):\n- interpretation = \"\"\n- if pref_data.get(\"setting\") is 2:\n- interpretation = \"Muted site\"\n- pref_item = Chrome.PreferenceItem(self.profile_path, url=origin, timestamp=to_datetime(pref_data[\"last_modified\"], self.timezone),\n- key=\"sound [in {}.profile.content_settings.exceptions]\"\n- .format(preferences_file), value=str(pref_data),\n- interpretation=interpretation)\n+ for origin, pref_data in \\\n+ prefs['profile']['content_settings']['exceptions']['sound'].items():\n+ if pref_data.get('last_modified'):\n+ interpretation = ''\n+ if pref_data.get('setting') is 2:\n+ interpretation = 'Muted site'\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url=origin, \n+ timestamp=utils.to_datetime(pref_data['last_modified'], self.timezone),\n+ key=f'sound [in {preferences_file}.profile.content_settings.exceptions]', \n+ value=str(pref_data), interpretation=interpretation)\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs.get('extensions'):\n if prefs['extensions'].get('autoupdate'):\n@@ -1294,12 +1326,14 @@ def expand_language_code(code):\n # },\n try:\n if prefs['extensions']['autoupdate'].get('last_check'):\n- pref_item = Chrome.PreferenceItem(self.profile_path, url='', timestamp=to_datetime(prefs['extensions']['autoupdate']['last_check'], self.timezone),\n- key=\"autoupdate.last_check [in {}.extensions]\".format(preferences_file),\n- value=prefs['extensions']['autoupdate']['last_check'], interpretation=\"\")\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url='', \n+ timestamp=utils.to_datetime(prefs['extensions']['autoupdate']['last_check'], self.timezone),\n+ key=f'autoupdate.last_check [in {preferences_file}.extensions]',\n+ value=prefs['extensions']['autoupdate']['last_check'], interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs.get('signin'):\n if prefs['signin'].get('signedin_time'):\n@@ -1308,16 +1342,18 @@ def expand_language_code(code):\n # \"signedin_time\": \"13196354823425155\"\n # },\n try:\n- pref_item = Chrome.PreferenceItem(self.profile_path, url='', timestamp=to_datetime(prefs['signin']['signedin_time'], self.timezone),\n- key=\"signedin_time [in {}.signin]\".format(preferences_file),\n- value=prefs['signin']['signedin_time'], interpretation=\"\")\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url='', \n+ timestamp=utils.to_datetime(prefs['signin']['signedin_time'], self.timezone),\n+ key=f'signedin_time [in {preferences_file}.signin]',\n+ value=prefs['signin']['signedin_time'], interpretation='')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n if prefs.get('translate_last_denied_time_for_language'):\n try:\n- for lang_code, timestamp in prefs['translate_last_denied_time_for_language'].iteritems():\n+ for lang_code, timestamp in prefs['translate_last_denied_time_for_language'].items():\n # Example (from in Preferences file):\n # \"translate_last_denied_time_for_language\": {\n # u'ar': 1438733440742.06,\n@@ -1327,25 +1363,26 @@ def expand_language_code(code):\n if isinstance(timestamp, list):\n timestamp = timestamp[0]\n assert isinstance(timestamp, float)\n- pref_item = Chrome.PreferenceItem(self.profile_path, url='', timestamp=to_datetime(timestamp, self.timezone),\n- key=\"translate_last_denied_time_for_language [in {}]\".format(preferences_file),\n- value=\"{}: {}\".format(lang_code, timestamp),\n- interpretation=\"Declined to translate page from {}\".format(expand_language_code(lang_code)))\n+ pref_item = Chrome.PreferenceItem(\n+ self.profile_path, url='', timestamp=utils.to_datetime(timestamp, self.timezone),\n+ key=f'translate_last_denied_time_for_language [in {preferences_file}]',\n+ value=f'{lang_code}: {timestamp}',\n+ interpretation=f'Declined to translate page from {expand_language_code(lang_code)}')\n timestamped_preference_items.append(pref_item)\n- except Exception, e:\n- log.exception(\" - Exception parsing Preference item: {})\".format(e))\n+ except Exception as e:\n+ log.exception(f' - Exception parsing Preference item: {e})')\n \n self.parsed_artifacts.extend(timestamped_preference_items)\n \n self.artifacts_counts[preferences_file] = len(results)\n- log.info(\" - Parsed {} items\".format(len(results)))\n+ log.info(f' - Parsed {len(results)} items')\n \n try:\n profile_folder = os.path.split(path)[1]\n except:\n- profile_folder = \"error\"\n+ profile_folder = 'error'\n \n- presentation = {'title': 'Preferences ({})'.format(profile_folder),\n+ presentation = {'title': f'Preferences ({profile_folder})',\n 'columns': [\n {'display_name': 'Group',\n 'data_name': 'group',\n@@ -1376,26 +1413,31 @@ def get_cache(self, path, dir_name, row_type=None):\n results = []\n \n path = os.path.join(path, dir_name)\n- log.info(\"Cache items from {}:\".format(path))\n+ log.info(f'Cache items from {path}:')\n \n try:\n- log.debug(\" - Found cache index file\")\n+ log.debug(' - Found cache index file')\n cacheBlock = CacheBlock(os.path.join(path, 'index'))\n \n # Checking type\n if cacheBlock.type != CacheBlock.INDEX:\n- log.error(\" - 'index' block file is invalid (has wrong magic type)\")\n+ log.error(' - \\'index\\' block file is invalid (has wrong magic type)')\n self.artifacts_counts[dir_name] = 'Failed'\n return\n- log.debug(\" - Parsed index block file (version {})\".format(cacheBlock.version))\n+ log.debug(f' - Parsed index block file (version {cacheBlock.version})')\n except:\n- log.error(\" - Failed to parse index block file\")\n+ log.error(' - Failed to parse index block file')\n+ return\n+\n+ if cacheBlock.version != 2:\n+ log.error(' - Parsing CacheBlocks other than v2 is not supported')\n return\n \n try:\n index = open(os.path.join(path, 'index'), 'rb')\n except:\n- log.error(\" - Error reading cache index file {}\".format(os.path.join(path, 'index')))\n+ log.error(f' - Error reading cache index file {os.path.join(path, \"index\")}')\n+ index.close()\n self.artifacts_counts[dir_name] = 'Failed'\n return\n \n@@ -1409,21 +1451,24 @@ def get_cache(self, path, dir_name, row_type=None):\n entry = CacheEntry(self.profile_path, CacheAddress(raw, path=path), row_type, self.timezone)\n # Add the new row to the results array\n results.append(entry)\n- except Exception, e:\n- log.error(\" - Error parsing cache entry {}: {}\".format(raw, str(e)))\n+ except Exception as e:\n+ log.error(f' - Error parsing cache entry {raw}: {str(e)}')\n \n try:\n # Checking if there is a next item in the bucket because\n # such entries are not stored in the Index File so they will\n # be ignored during iterative lookup in the hash table\n while entry.next != 0:\n- entry = CacheEntry(self.profile_path, CacheAddress(entry.next, path=path), row_type, self.timezone)\n+ entry = CacheEntry(self.profile_path, CacheAddress(entry.next, path=path),\n+ row_type, self.timezone)\n results.append(entry)\n- except Exception, e:\n- log.error(\" - Error parsing cache entry {}: {}\".format(raw, str(e)))\n+ except Exception as e:\n+ log.error(f' - Error parsing cache entry {raw}: {str(e)}')\n+\n+ index.close()\n \n self.artifacts_counts[dir_name] = len(results)\n- log.info(\" - Parsed {} items\".format(len(results)))\n+ log.info(f' - Parsed {len(results)} items')\n self.parsed_artifacts.extend(results)\n \n def get_application_cache(self, path, dir_name, row_type=None):\n@@ -1440,19 +1485,19 @@ def get_application_cache(self, path, dir_name, row_type=None):\n \n base_path = os.path.join(path, dir_name)\n cache_path = os.path.join(base_path, 'Cache')\n- log.info(\"Application Cache items from {}:\".format(path))\n+ log.info(f'Application Cache items from {path}:')\n \n # Connect to 'Index' sqlite db\n db_path = os.path.join(base_path, 'Index')\n try:\n index_db = sqlite3.connect(db_path)\n- log.info(\" - Reading from file '{}'\".format(db_path))\n+ log.info(f' - Reading from file \\'{db_path}\\'')\n \n # Use a dictionary cursor\n index_db.row_factory = WebBrowser.dict_factory\n cursor = index_db.cursor()\n except:\n- log.error(\" - Error opening Application Cache Index SQLite DB {}\".format(db_path))\n+ log.error(f' - Error opening Application Cache Index SQLite DB {db_path}')\n self.artifacts_counts[dir_name] = 'Failed'\n return\n \n@@ -1460,11 +1505,11 @@ def get_application_cache(self, path, dir_name, row_type=None):\n cache_block = CacheBlock(os.path.join(cache_path, 'index'))\n # Checking type\n if cache_block.type != CacheBlock.INDEX:\n- raise Exception(\"Invalid Index File\")\n+ raise Exception('Invalid Index File')\n \n index = open(os.path.join(cache_path, 'index'), 'rb')\n except:\n- log.error(\" - Error reading cache index file {}\".format(os.path.join(path, 'index')))\n+ log.error(f' - Error reading cache index file {os.path.join(path, \"index\")}')\n self.artifacts_counts[dir_name] = 'Failed'\n return\n \n@@ -1488,260 +1533,249 @@ def get_application_cache(self, path, dir_name, row_type=None):\n # such entries are not stored in the Index File so they will\n # be ignored during iterative lookup in the hash table\n while entry.next != 0:\n- entry = CacheEntry(self.profile_path, CacheAddress(entry.next, path=cache_path), row_type, self.timezone)\n+ entry = CacheEntry(self.profile_path, CacheAddress(entry.next, path=cache_path), \n+ row_type, self.timezone)\n cursor.execute('''SELECT url FROM Entries WHERE response_id=?''', [entry.key])\n index_url = cursor.fetchone()\n if index_url:\n entry.url = index_url['url']\n results.append(entry)\n- except Exception, e:\n- log.error(\" - Error parsing cache entry {}: {}\".format(raw, str(e)))\n+ except Exception as e:\n+ log.error(f' - Error parsing cache entry {raw}: {str(e)}')\n \n+ index.close()\n index_db.close()\n \n self.artifacts_counts[dir_name] = len(results)\n- log.info(\" - Parsed {} items\".format(len(results)))\n+ log.info(f' - Parsed {len(results)} items')\n self.parsed_artifacts.extend(results)\n \n- def get_fs_path_leveldb(self, lvl_db_path):\n- import leveldb\n- db = leveldb.LevelDB(lvl_db_path, create_if_missing=False)\n- nodes = {}\n- pairs = list(db.RangeIter())\n- for pair in pairs:\n- # Each origin value should be a tuple of length 2; if not, log it and skip it.\n- if not isinstance(pair, tuple) or len(pair) is not 2:\n- log.warning(\" - Found LevelDB key/value pair that is not formed as expected ({}); skipping.\".format(str(pair)))\n- continue\n- fs_path_re = re.compile(b\"\\x00(?P\\d\\d)(\\\\\\\\|/)(?P\\d{8})\\x00\")\n- m = fs_path_re.search(pair[1])\n- if m:\n- nodes[pair[0]] = {\"dir\": m.group(\"dir\"), \"id\": m.group(\"id\")}\n- return nodes\n-\n- def get_prefixed_leveldb_pairs(self, lvl_db_path, prefix=\"\"):\n- \"\"\"Given a path to a LevelDB and a prefix string, return all pairs starting\"\"\"\n- try:\n- import leveldb\n- except ImportError:\n- log.warning(\"Failed to import leveldb; unable to process {}\".format(lvl_db_path))\n- return []\n-\n- try:\n- db = leveldb.LevelDB(lvl_db_path, create_if_missing=False)\n- except Exception as e:\n- log.warning(\" - Couldn't open {0:s} as LevelDB; {1:s}\".format(lvl_db_path, e))\n- return []\n-\n- cleaned_pairs = []\n- pairs = list(db.RangeIter())\n- for pair in pairs:\n- # Each origin value should be a tuple of length 2; if not, log it and skip it.\n- if not isinstance(pair, tuple) or len(pair) is not 2:\n- log.warning(\" - Found LevelDB key/value pair that is not formed as expected ({}); skipping.\".format(str(pair)))\n- continue\n- if pair[0].startswith(prefix):\n- # Split the tuple in the origin domain and origin ID, and remove the prefix from the domain\n- (key, value) = pair\n- key = key[len(prefix):]\n- cleaned_pairs.append({\"key\": key, \"value\": value})\n-\n- return cleaned_pairs\n-\n @staticmethod\n- def parse_ls_ldb_dict(ls_dict):\n- origin, ls_key, ls_value = (None, None, None)\n- origin_and_key = ls_dict['key']\n-\n- if ls_dict['key'].startswith('META:'):\n- origin = ls_dict['key'].split(':', 1)[1]\n- ls_key = 'META'\n- return False\n-\n- elif ls_dict['key'] == 'VERSION':\n- return False\n+ def parse_ls_ldb_record(record):\n+ \"\"\"\n+ From https://cs.chromium.org/chromium/src/components/services/storage/dom_storage/local_storage_impl.cc:\n+\n+ // LevelDB database schema\n+ // =======================\n+ //\n+ // Version 1 (in sorted order):\n+ // key: \"VERSION\"\n+ // value: \"1\"\n+ //\n+ // key: \"META:\" + \n+ // value: \n+ //\n+ // key: \"_\" + 'origin'> + '\\x00' +