File size: 293,407 Bytes
5980447 | 1 2 | {"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: <userdir>\\Local Settings\\Application Data\\Google\\Chrome\n- \\User Data\\Default\\\\\n- Vista/7/8/10: <userdir>\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\\\\n+ \\\\User Data\\Default\\\\\n+ Vista/7/8/10: <userdir>\\AppData\\Local\\Google\\Chrome\\\\User Data\\Default\\\\\n Linux: <userdir>/.config/google-chrome/Default/\n OS X: <userdir>/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\\<GUID>\\\\\n+ Chromium OS: \\home\\\\user\\<GUID>\\\\\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 \"<encrypted>\" 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'<User chose to \"Never save password\" for this site>',\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='<User chose to \"Never save password\" for this site>',\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'<buffer decode error>'\n- else:\n- return u'<unknown type decode error>'\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 = '<error>'\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 = \"<error>\"\n+ description = '<error>'\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 = \"<error>\"\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': '<not present>',\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': '<not present>',\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<dir>\\d\\d)(\\\\\\\\|/)(?P<id>\\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:\" + <url::Origin 'origin'>\n+ // value: <LocalStorageOriginMetaData serialized as a string>\n+ //\n+ // key: \"_\" + <url::Origin> 'origin'> + '\\x00' + <script controlled key>\n+ // value: <script controlled value>\n+ \"\"\"\n+ parsed = {}\n+\n+ if record['key'].startswith('META:'.encode('utf-8')):\n+ parsed['record_type'] = 'META'\n+ parsed['origin'] = record['key'][5:].decode()\n+ parsed['key'] = record['key'][5:].decode()\n+\n+ # From https://cs.chromium.org/chromium/src/components/services/storage/dom_storage/\n+ # local_storage_database.proto:\n+ # message LocalStorageOriginMetaData\n+ # required int64 last_modified = 1;\n+ # required uint64 size_bytes = 2;\n+ # TODO: consider redoing this using protobufs\n+ if record['value'].startswith(b'\\x08'):\n+ ptr = 1\n+ last_modified, bytes_read = utils.read_varint(record['value'][ptr:])\n+ size_bytes, _ = utils.read_varint(record['value'][ptr + bytes_read:])\n+ parsed['value'] = f'Last modified: {last_modified}; size: {size_bytes}'\n+ return parsed\n+\n+ elif record['key'] == 'VERSION':\n+ return\n \n- else:\n+ elif record['key'].startswith(b'_'):\n+ parsed['record_type'] = 'entry'\n try:\n- origin, ls_key = ls_dict['key'].split('\\x00', 1)\n+ parsed['origin'], parsed['key'] = record['key'][1:].split(b'\\x00', 1)\n+ parsed['origin'] = parsed['origin'].decode()\n \n- if ls_key.startswith('\\x01'):\n- ls_key = ls_key.lstrip('\\x01')\n+ if parsed['key'].startswith(b'\\x01'):\n+ parsed['key'] = parsed['key'].lstrip(b'\\x01').decode()\n \n- elif ls_key.startswith('\\x00'):\n- ls_key = ls_key.lstrip('\\x00').decode('utf-16')\n+ elif parsed['key'].startswith('\\x00'):\n+ parsed['key'] = parsed['key'].lstrip('\\x00').decode('utf-16')\n \n except Exception as e:\n log.error(\"Origin/key parsing error: {}\".format(e))\n+ return\n \n- try:\n- ls_value = ls_dict['value']\n+ try:\n+ if record['value'].startswith(b'\\x01'):\n+ parsed['value'] = record['value'].lstrip(b'\\x01').decode('utf-8', errors='replace')\n \n- if ls_value.startswith('\\x01'):\n- ls_value = ls_value.lstrip('\\x01')\n+ elif record['value'].startswith(b'\\x00'):\n+ parsed['value'] = record['value'].lstrip(b'\\x00').decode('utf-16', errors='replace')\n \n- elif ls_value.startswith('\\x00'):\n- ls_value = ls_value.lstrip('\\x00').decode('utf-16', errors='replace')\n+ elif record['value'].startswith(b'\\x08'):\n+ parsed['value'] = record['value'].lstrip(b'\\x08').decode()\n \n- elif ls_value.startswith('\\x08'):\n- ls_value = ls_value.lstrip('\\x08')\n- except Exception as e:\n- log.error(\"Value parsing error: {}\".format(e))\n+ except Exception as e:\n+ log.error(f'Value parsing error: {e}')\n+ return\n \n- log.info({'origin': origin, 'key': ls_key, 'value': ls_value})\n- return {'origin': origin, 'key': ls_key, 'value': ls_value}\n+ return parsed\n \n def build_logical_fs_path(self, node, parent_path=None):\n if not parent_path:\n parent_path = []\n \n- parent_path.append(node[\"name\"])\n- node[\"path\"] = parent_path\n- for child_node in node[\"children\"].itervalues():\n- self.build_logical_fs_path(child_node, parent_path=list(node[\"path\"]))\n+ parent_path.append(node['name'])\n+ node['path'] = parent_path\n+ for child_node in node['children'].values():\n+ self.build_logical_fs_path(child_node, parent_path=list(node['path']))\n \n- def flatten_nodes_to_list(self, profile_folder, output_list, node):\n+ def flatten_nodes_to_list(self, output_list, node):\n output_row = {\n- \"type\": node[\"type\"],\n- \"display_type\": node[\"display_type\"],\n- \"origin\": node[\"path\"][0],\n- \"logical_path\": \"\\\\\".join(node[\"path\"][1:]),\n- \"local_path\": \"{}\\\\File System\\\\{}\\\\{}\".format(profile_folder, node[\"origin_id\"], node[\"type\"])\n+ 'type': node['type'],\n+ 'display_type': node['display_type'],\n+ 'origin': node['path'][0],\n+ 'logical_path': '\\\\'.join(node['path'][1:]),\n+ 'local_path': os.path.join('File System', node['origin_id'], node['type'])\n }\n- if node.get(\"fs_path\"):\n- output_row[\"local_path\"] += \"\\\\{}\\\\{}\".format(node[\"fs_path\"][\"dir\"], node[\"fs_path\"][\"id\"])\n+ if node.get('fs_path'):\n+ fs_path = os.path.split(node['fs_path'])\n+ output_row['local_path'] = os.path.join(output_row['local_path'], fs_path[0], fs_path[1])\n+\n+ if node.get('modification_time'):\n+ output_row['modification_time'] = utils.to_datetime(node['modification_time'])\n \n output_list.append(output_row)\n- for child_node in node[\"children\"].itervalues():\n- self.flatten_nodes_to_list(profile_folder, output_list, child_node)\n+ for child_node in node['children'].values():\n+ self.flatten_nodes_to_list(output_list, child_node)\n \n def get_file_system(self, path, dir_name):\n try:\n- # TODO: add conditionally to imports/requirements?\n- import leveldb\n+ import plyvel\n except ImportError:\n- self.artifacts_counts['File System'] = 0\n- log.info(\"File System: Failed to parse; couldn't import leveldb.\")\n+ self.artifacts_counts['File System'] = 'Failed'\n+ log.info('File System: Failed to parse; couldn\\'t import plyvel.')\n return\n \n result_list = []\n result_count = 0\n- try:\n- profile_folder = os.path.split(path)[1]\n- except:\n- profile_folder = \"error\"\n- log.info(\"File System ({}):\".format(profile_folder))\n \n # Grab listing of 'File System' directory\n+ log.info('File System:')\n fs_root_path = os.path.join(path, dir_name)\n- log.info(\" - Reading from {}\".format(fs_root_path))\n+ log.info(f' - Reading from {fs_root_path}')\n fs_root_listing = os.listdir(fs_root_path)\n- log.debug(\" - {count} files in File System directory: {list}\".format(list=str(fs_root_listing),\n- count=len(fs_root_listing)))\n- # 'Origins' is a LevelDB that holds the mapping for each of the [000, 001, 002, ... ] dirs to web origin (https_www.google.com_0)\n+ log.debug(f' - {len(fs_root_listing)} files in File System directory: {str(fs_root_listing)}')\n+\n+ # 'Origins' is a LevelDB that holds the mapping for each of the [000, 001, 002, ... ] dirs to\n+ # web origin (https_www.google.com_0)\n if 'Origins' in fs_root_listing:\n- lvl_db_path = os.path.join(fs_root_path, 'Origins')\n- origins = self.get_prefixed_leveldb_pairs(lvl_db_path, \"ORIGIN:\")\n+ ldb_path = os.path.join(fs_root_path, 'Origins')\n+ origins = utils.get_ldb_pairs(ldb_path, 'ORIGIN:')\n for origin in origins:\n- origin_domain = origin[\"key\"]\n- origin_id = origin[\"value\"]\n+ origin_domain = origin['key'].decode()\n+ origin_id = origin['value'].decode()\n origin_root_path = os.path.join(fs_root_path, origin_id)\n- t_tree = {}\n- p_tree = {}\n-\n- if os.path.isdir(origin_root_path):\n- origin_t_path = os.path.join(origin_root_path, 't')\n- if os.path.isdir(origin_t_path):\n- log.debug(\" - Found 'temporary' data directory for origin {}\".format(origin_domain))\n- origin_t_paths_path = os.path.join(origin_t_path, 'Paths')\n- if os.path.isdir(origin_t_paths_path):\n- try:\n- t_items = self.get_prefixed_leveldb_pairs(origin_t_paths_path, \"CHILD_OF:\")\n- t_fs_paths = self.get_fs_path_leveldb(origin_t_paths_path)\n- t_nodes = {\"0\": {\"name\": origin_domain, \"type\": \"t\", \"display_type\": \"file system (temporary)\",\n- \"origin_id\": origin_id, \"fs_path\": t_fs_paths.get('0'), \"children\": {}}}\n- for item in t_items:\n- (parent, name) = item[\"key\"].split(\":\")\n- t_nodes[item[\"value\"]] = {\"name\": name, \"type\": \"t\", \"display_type\": \"file system (temporary)\",\n- \"origin_id\": origin_id, \"parent\": parent, \"fs_path\": t_fs_paths.get(item[\"value\"]),\n- \"children\": {}}\n- result_count += 1\n-\n- for id in t_nodes:\n- if t_nodes[id].get(\"parent\"):\n- t_nodes[t_nodes[id].get(\"parent\")][\"children\"][id] = t_nodes[id]\n- else:\n- t_tree[id] = t_nodes[id]\n-\n- self.build_logical_fs_path(t_tree[\"0\"])\n- self.flatten_nodes_to_list(profile_folder, result_list, t_tree[\"0\"])\n- except Exception as e:\n- log.error(\" - Error accessing LevelDB {}: {}\".format(origin_t_paths_path, str(e)))\n-\n- origin_p_path = os.path.join(origin_root_path, 'p')\n- if os.path.isdir(origin_p_path):\n- log.debug(\" - Found 'persistent' data directory for origin {}\".format(origin_domain))\n- origin_p_paths_path = os.path.join(origin_p_path, 'Paths')\n- if os.path.isdir(origin_p_paths_path):\n- try:\n- p_items = self.get_prefixed_leveldb_pairs(origin_p_paths_path, \"CHILD_OF:\")\n- p_fs_paths = self.get_fs_path_leveldb(origin_p_paths_path)\n- p_nodes = {\"0\": {\"name\": origin_domain, \"type\": \"p\", \"display_type\": \"file system (persistent)\",\n- \"origin_id\": origin_id, \"fs_path\": p_fs_paths.get('0'), \"children\": {}}}\n- for item in p_items:\n- (parent, name) = item[\"key\"].split(\":\")\n- p_nodes[item[\"value\"]] = {\"name\": name, \"type\": \"p\", \"display_type\": \"file system (persistent)\",\n- \"origin_id\": origin_id, \"parent\": parent, \"fs_path\": p_fs_paths.get(item[\"value\"]),\n- \"children\": {}}\n- result_count += 1\n-\n- for id in p_nodes:\n- if p_nodes[id].get(\"parent\"):\n- p_nodes[p_nodes[id].get(\"parent\")][\"children\"][id] = p_nodes[id]\n- else:\n- p_tree[id] = p_nodes[id]\n-\n- self.build_logical_fs_path(p_tree[\"0\"])\n- self.flatten_nodes_to_list(profile_folder, result_list, p_tree[\"0\"])\n- except Exception as e:\n- log.error(\" - Error accessing LevelDB {}: {}\".format(origin_p_paths_path, str(e)))\n-\n- log.info(\" - Parsed {} items\".format(len(result_list)))\n- self.artifacts_counts['File System'] = len(result_list)\n+ if not os.path.isdir(origin_root_path):\n+ continue\n+\n+ # Each Origin can have a temporary (t) and persistent (p) storage section.\n+ for fs_type in ['t', 'p']:\n+ node_tree = {}\n+ fs_type_path = os.path.join(origin_root_path, fs_type)\n+ if not os.path.isdir(fs_type_path):\n+ continue\n \n- presentation = {'title': 'Storage',\n- 'columns': [\n- {'display_name': 'Storage Type',\n- 'data_name': 'display_type',\n- 'display_width': 26},\n- {'display_name': 'Origin',\n- 'data_name': 'origin',\n- 'display_width': 50},\n- {'display_name': 'Logical Path / Key',\n- 'data_name': 'logical_path',\n- 'display_width': 50},\n- {'display_name': 'Local Path',\n- 'data_name': 'local_path',\n- 'display_width': 36}\n- ]}\n+ log.debug(f' - Found \\'{fs_type}\\' data directory for origin {origin_domain}')\n+\n+ # Within each storage section is a 'Paths' leveldb, which holds the logical structure\n+ # relationship between the files stored in this section.\n+ fs_paths_path = os.path.join(fs_type_path, 'Paths')\n+ if not os.path.isdir(fs_paths_path):\n+ continue\n+\n+ # The 'Paths' ldbs can have entries of four different types:\n+ # // - (\"CHILD_OF:|parent_id|:<name>\", \"|file_id|\"),\n+ # // - (\"LAST_FILE_ID\", \"|last_file_id|\"),\n+ # // - (\"LAST_INTEGER\", \"|last_integer|\"),\n+ # // - (\"|file_id|\", \"pickled FileInfo\")\n+ # // where FileInfo has |parent_id|, |data_path|, |name| and |modification_time|\n+ # from cs.chromium.org/chromium/src/storage/browser/file_system/sandbox_directory_database.cc\n+\n+ backing_files = {}\n+ path_nodes = {\n+ '0': {'name': origin_domain, 'type': fs_type, 'display_type': f'file system ({fs_type})',\n+ 'origin_id': origin_id, 'fs_path': backing_files.get('0'), 'children': {}}}\n+\n+ path_items = utils.get_ldb_pairs(fs_paths_path)\n+\n+ for item in path_items:\n+ # This will find keys that start with a number, rather than letter (ASCII code),\n+ # which only matches \"file id\" items (from above list of four types).\n+ if item['key'][0] < 58:\n+ overall_length, ptr = utils.read_int32(item['value'], 0)\n+ parent_id, ptr = utils.read_int64(item['value'], ptr)\n+ backing_file_path, ptr = utils.read_string(item['value'], ptr)\n+ name, ptr = utils.read_string(item['value'], ptr)\n+ mod_time, ptr = utils.read_int64(item['value'], ptr)\n+\n+ path_parts = re.split(r'[/\\\\]', backing_file_path)\n+ if path_parts != ['']:\n+ normalized_backing_file_path = os.path.join(path_parts[0], path_parts[1])\n+ else:\n+ normalized_backing_file_path = backing_file_path\n+\n+ backing_files[item['key'].decode()] = {\n+ 'backing_file_path': normalized_backing_file_path,\n+ 'modification_time': mod_time}\n+\n+ elif item['key'].startswith(b'CHILD_OF:'):\n+ parent, name = item['key'][9:].split(b':')\n+ path_nodes[item['value'].decode()] = {\n+ 'name': name.decode(),\n+ 'type': fs_type,\n+ 'display_type': f'file system ({fs_type})',\n+ 'origin_id': origin_id,\n+ 'parent': parent.decode(),\n+ 'fs_path': backing_files[item['value'].decode()]['backing_file_path'],\n+ 'modification_time': backing_files[item['value'].decode()]['modification_time'],\n+ 'children': {}}\n+ result_count += 1\n+\n+ for entry_id in path_nodes:\n+ if path_nodes[entry_id].get('parent'):\n+ path_nodes[path_nodes[entry_id].get('parent')]['children'][entry_id] = path_nodes[entry_id]\n+ else:\n+ node_tree[entry_id] = path_nodes[entry_id]\n \n- self.storage.setdefault('data', [])\n- self.storage.setdefault('presentation', presentation)\n- self.storage['data'].extend(result_list)\n- # self.storage = {'data': result_list, 'presentation': presentation}\n+ self.build_logical_fs_path(node_tree['0'])\n+ flattened_list = []\n+ self.flatten_nodes_to_list(flattened_list, node_tree['0'])\n+\n+ for item in flattened_list:\n+ result_list.append(Chrome.FileSystemItem(\n+ self.profile_path, item.get('origin'), item.get('logical_path'), item.get('local_path'),\n+ item.get('modification_time')))\n+\n+ log.info(f' - Parsed {len(result_list)} items')\n+ self.artifacts_counts['File System'] = len(result_list)\n+ self.parsed_storage.extend(result_list)\n \n def process(self):\n supported_databases = ['History', 'Archived History', 'Web Data', 'Cookies', 'Login Data', 'Extension Cookies']\n- supported_subdirs = ['Local Storage', 'Extensions', 'File System']\n+ supported_subdirs = ['Local Storage', 'Extensions', 'File System', 'Platform Notifications']\n supported_jsons = ['Bookmarks'] # , 'Preferences']\n supported_items = supported_databases + supported_subdirs + supported_jsons\n- log.debug(\"Supported items: \" + str(supported_items))\n+ log.debug(f'Supported items: {supported_items}')\n \n input_listing = os.listdir(self.profile_path)\n for input_file in input_listing:\n # If input_file is in our supported db list, or if the input_file name starts with a\n # value in supported_databases followed by '__' (used to add in dbs from additional sources)\n- if input_file in supported_databases or input_file.startswith(tuple([db + '__' for db in supported_databases])):\n+ if input_file in supported_databases or \\\n+ input_file.startswith(tuple([db + '__' for db in supported_databases])):\n # Process structure from Chrome database files\n self.build_structure(self.profile_path, input_file)\n \n@@ -1749,110 +1783,124 @@ def process(self):\n self.determine_version()\n \n if len(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 elif len(self.version) == 1:\n self.display_version = self.version[0]\n else:\n- print(\"Unable to determine browser version from\")\n+ print('Unable to determine browser version')\n \n print(self.format_profile_path(self.profile_path))\n \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+ print(self.format_processing_output(f'Detected {self.browser_name} version', self.display_version))\n+ log.info(f'Detected {self.browser_name} version {self.display_version}')\n \n- log.info(\"Found the following supported files or directories:\")\n+ log.info('Found the following supported files or directories:')\n for input_file in input_listing:\n if input_file in supported_items:\n- log.info(\" - %s\" % input_file)\n+ log.info(f' - {input_file}')\n \n # Process History files\n custom_type_re = re.compile(r'__([A-z0-9\\._]*)$')\n for input_file in input_listing:\n if re.search(r'^History__|^History$', 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 = f'url ({custom_type_m.group(1)})'\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(self.artifacts_display[input_file],\n- self.artifacts_counts.get(input_file, '0'))\n+ display_type = 'URL' if not custom_type_m else f'URL ({custom_type_m.group(1)})'\n+ self.artifacts_display[input_file] = f'{display_type} records'\n+ print(self.format_processing_output(\n+ self.artifacts_display[input_file], \n+ self.artifacts_counts.get(input_file, '0')))\n \n- row_type = u'download'\n+ row_type = 'download'\n if custom_type_m:\n- row_type = u'download ({})'.format(custom_type_m.group(1))\n+ row_type = f'download ({custom_type_m.group(1)})'\n self.get_downloads(self.profile_path, input_file, self.version, row_type)\n- display_type = 'Download' if not custom_type_m else 'Download ({})'.format(custom_type_m.group(1))\n- self.artifacts_display[input_file + '_downloads'] = \"{} records\".format(display_type)\n- print self.format_processing_output(self.artifacts_display[input_file + '_downloads'],\n- self.artifacts_counts.get(input_file + '_downloads', '0'))\n+ display_type = 'Download' if not custom_type_m else f'Download ({custom_type_m.group(1)})'\n+ self.artifacts_display[input_file + '_downloads'] = f'{display_type} records'\n+ print(self.format_processing_output(\n+ self.artifacts_display[input_file + '_downloads'], \n+ self.artifacts_counts.get(input_file + '_downloads', '0')))\n \n if 'Archived History' in input_listing:\n- self.get_history(self.profile_path, 'Archived History', self.version, u'url (archived)')\n+ self.get_history(self.profile_path, 'Archived History', self.version, 'url (archived)')\n self.artifacts_display['Archived History'] = \"Archived URL records\"\n- print self.format_processing_output(self.artifacts_display['Archived History'],\n- self.artifacts_counts.get('Archived History', '0'))\n+ print(self.format_processing_output(\n+ self.artifacts_display['Archived History'],\n+ self.artifacts_counts.get('Archived History', '0')))\n \n if self.cache_path is not None and self.cache_path != '':\n c_path, c_dir = os.path.split(self.cache_path)\n- self.get_cache(c_path, c_dir, row_type=u'cache')\n- self.artifacts_display['Cache'] = \"Cache records\"\n- print self.format_processing_output(self.artifacts_display['Cache'],\n- self.artifacts_counts.get('Cache', '0'))\n+ self.get_cache(c_path, c_dir, row_type='cache')\n+ self.artifacts_display['Cache'] = 'Cache records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Cache'],\n+ self.artifacts_counts.get('Cache', '0')))\n \n elif 'Cache' in input_listing:\n- self.get_cache(self.profile_path, 'Cache', row_type=u'cache')\n- self.artifacts_display['Cache'] = \"Cache records\"\n- print self.format_processing_output(self.artifacts_display['Cache'],\n- self.artifacts_counts.get('Cache', '0'))\n+ self.get_cache(self.profile_path, 'Cache', row_type='cache')\n+ self.artifacts_display['Cache'] = 'Cache records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Cache'],\n+ self.artifacts_counts.get('Cache', '0')))\n+ \n if 'GPUCache' in input_listing:\n- self.get_cache(self.profile_path, 'GPUCache', row_type=u'cache (gpu)')\n- self.artifacts_display['GPUCache'] = \"GPU Cache records\"\n- print self.format_processing_output(self.artifacts_display['GPUCache'],\n- self.artifacts_counts.get('GPUCache', '0'))\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(\n+ self.artifacts_display['GPUCache'],\n+ self.artifacts_counts.get('GPUCache', '0')))\n \n if 'Media Cache' in input_listing:\n- self.get_cache(self.profile_path, 'Media Cache', row_type=u'cache (media)')\n- self.artifacts_display['Media Cache'] = \"Media Cache records\"\n- print self.format_processing_output(self.artifacts_display['Media Cache'],\n- self.artifacts_counts.get('Media Cache', '0'))\n+ self.get_cache(self.profile_path, 'Media Cache', row_type='cache (media)')\n+ self.artifacts_display['Media Cache'] = 'Media Cache records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Media Cache'],\n+ self.artifacts_counts.get('Media Cache', '0')))\n \n if 'Application Cache' in input_listing:\n- self.get_application_cache(self.profile_path, 'Application Cache', row_type=u'cache (application)')\n- self.artifacts_display['Application Cache'] = \"Application Cache records\"\n- print self.format_processing_output(self.artifacts_display['Application Cache'],\n- self.artifacts_counts.get('Application Cache', '0'))\n+ self.get_application_cache(self.profile_path, 'Application Cache', row_type='cache (application)')\n+ self.artifacts_display['Application Cache'] = 'Application Cache records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Application Cache'],\n+ self.artifacts_counts.get('Application Cache', '0')))\n \n if 'Cookies' in input_listing:\n self.get_cookies(self.profile_path, 'Cookies', self.version)\n- self.artifacts_display['Cookies'] = \"Cookie records\"\n- print self.format_processing_output(self.artifacts_display['Cookies'],\n- self.artifacts_counts.get('Cookies', '0'))\n+ self.artifacts_display['Cookies'] = 'Cookie records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Cookies'],\n+ self.artifacts_counts.get('Cookies', '0')))\n \n if 'Web Data' in input_listing:\n self.get_autofill(self.profile_path, 'Web Data', self.version)\n- self.artifacts_display['Autofill'] = \"Autofill records\"\n- print self.format_processing_output(self.artifacts_display['Autofill'],\n- self.artifacts_counts.get('Autofill', '0'))\n+ self.artifacts_display['Autofill'] = 'Autofill records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Autofill'],\n+ self.artifacts_counts.get('Autofill', '0')))\n \n if 'Bookmarks' in input_listing:\n self.get_bookmarks(self.profile_path, 'Bookmarks', self.version)\n- self.artifacts_display['Bookmarks'] = \"Bookmark records\"\n- print self.format_processing_output(self.artifacts_display['Bookmarks'],\n- self.artifacts_counts.get('Bookmarks', '0'))\n+ self.artifacts_display['Bookmarks'] = 'Bookmark records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Bookmarks'],\n+ self.artifacts_counts.get('Bookmarks', '0')))\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(self.artifacts_display['Local Storage'],\n- self.artifacts_counts.get('Local Storage', '0'))\n+ self.artifacts_display['Local Storage'] = 'Local Storage records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Local Storage'],\n+ self.artifacts_counts.get('Local Storage', '0')))\n \n if 'Extensions' in input_listing:\n self.get_extensions(self.profile_path, 'Extensions')\n- self.artifacts_display['Extensions'] = \"Extensions\"\n- print self.format_processing_output(self.artifacts_display['Extensions'],\n- self.artifacts_counts.get('Extensions', '0'))\n+ self.artifacts_display['Extensions'] = 'Extensions'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Extensions'],\n+ self.artifacts_counts.get('Extensions', '0')))\n \n if 'Extension Cookies' in input_listing:\n # Workaround to cap the version at 65 for Extension Cookies, as until that\n@@ -1862,27 +1910,31 @@ def process(self):\n # ext_cookies_version.insert(0, 65)\n \n self.get_cookies(self.profile_path, 'Extension Cookies', ext_cookies_version)\n- self.artifacts_display['Extension Cookies'] = \"Extension Cookie records\"\n- print self.format_processing_output(self.artifacts_display['Extension Cookies'],\n- self.artifacts_counts.get('Extension Cookies', '0'))\n+ self.artifacts_display['Extension Cookies'] = 'Extension Cookie records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Extension Cookies'],\n+ self.artifacts_counts.get('Extension Cookies', '0')))\n \n if 'Login Data' in input_listing:\n self.get_login_data(self.profile_path, 'Login Data', self.version)\n- self.artifacts_display['Login Data'] = \"Login Data records\"\n- print self.format_processing_output(self.artifacts_display['Login Data'],\n- self.artifacts_counts.get('Login Data', '0'))\n+ self.artifacts_display['Login Data'] = 'Login Data records'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Login Data'],\n+ self.artifacts_counts.get('Login Data', '0')))\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(self.artifacts_display['Preferences'],\n- self.artifacts_counts.get('Preferences', '0'))\n+ self.artifacts_display['Preferences'] = 'Preference Items'\n+ print(self.format_processing_output(\n+ self.artifacts_display['Preferences'],\n+ self.artifacts_counts.get('Preferences', '0')))\n \n if 'File System' in input_listing:\n self.get_file_system(self.profile_path, 'File System')\n- self.artifacts_display['File System'] = \"File System Items\"\n- print self.format_processing_output(self.artifacts_display['File System'],\n- self.artifacts_counts.get('File System', '0'))\n+ self.artifacts_display['File System'] = 'File System Items'\n+ print(self.format_processing_output(\n+ self.artifacts_display['File System'],\n+ self.artifacts_counts.get('File System', '0')))\n \n # Destroy the cached key so that json serialization doesn't\n # have a cardiac arrest on the non-unicode binary data.\n@@ -1894,112 +1946,113 @@ class URLItem(WebBrowser.URLItem):\n def __init__(self, profile, url_id, url, title, visit_time, last_visit_time, visit_count, typed_count, from_visit,\n transition, hidden, favicon_id, indexed=None, visit_duration=None, visit_source=None,\n transition_friendly=None):\n- WebBrowser.URLItem.__init__(self, profile=profile, url_id=url_id, url=url, title=title, visit_time=visit_time, last_visit_time=last_visit_time,\n- visit_count=visit_count, typed_count=typed_count, from_visit=from_visit, transition=transition,\n- hidden=hidden, favicon_id=favicon_id, indexed=indexed, visit_duration=visit_duration,\n- visit_source=visit_source, transition_friendly=transition_friendly)\n+ WebBrowser.URLItem.__init__(self, profile=profile, url_id=url_id, url=url, title=title, visit_time=visit_time,\n+ last_visit_time=last_visit_time, visit_count=visit_count, typed_count=typed_count,\n+ from_visit=from_visit, transition=transition, hidden=hidden, favicon_id=favicon_id,\n+ indexed=indexed, visit_duration=visit_duration, visit_source=visit_source,\n+ transition_friendly=transition_friendly)\n \n def decode_transition(self):\n # Source: http://src.chromium.org/svn/trunk/src/content/public/common/page_transition_types_list.h\n transition_friendly = {\n- 0: u'link', # User got to this page by clicking a link on another page.\n- 1: u'typed', # User got this page by typing the URL in the URL bar. This should not be\n- # used for cases where the user selected a choice that didn't look at all\n- # like a URL; see GENERATED below.\n- # We also use this for other 'explicit' navigation actions.\n- 2: u'auto bookmark', # User got to this page through a suggestion in the UI, for example)\n- # through the destinations page.\n- 3: u'auto subframe', # This is a subframe navigation. This is any content that is automatically\n- # loaded in a non-toplevel frame. For example, if a page consists of\n- # several frames containing ads, those ad URLs will have this transition\n- # type. The user may not even realize the content in these pages is a\n- # separate frame, so may not care about the URL (see MANUAL below).\n- 4: u'manual subframe', # For subframe navigations that are explicitly requested by the user and\n- # generate new navigation entries in the back/forward list. These are\n- # probably more important than frames that were automatically loaded in\n- # the background because the user probably cares about the fact that this\n- # link was loaded.\n- 5: u'generated', # User got to this page by typing in the URL bar and selecting an entry\n- # that did not look like a URL. For example, a match might have the URL\n- # of a Google search result page, but appear like 'Search Google for ...'.\n- # These are not quite the same as TYPED navigations because the user\n- # didn't type or see the destination URL.\n- # See also KEYWORD.\n- 6: u'start page', # This is a toplevel navigation. This is any content that is automatically\n- # loaded in a toplevel frame. For example, opening a tab to show the ASH\n- # screen saver, opening the devtools window, opening the NTP after the safe\n- # browsing warning, opening web-based dialog boxes are examples of\n- # AUTO_TOPLEVEL navigations.\n- 7: u'form submit', # The user filled out values in a form and submitted it. NOTE that in\n- # some situations submitting a form does not result in this transition\n- # type. This can happen if the form uses script to submit the contents.\n- 8: u'reload', # The user 'reloaded' the page, either by hitting the reload button or by\n- # hitting enter in the address bar. NOTE: This is distinct from the\n- # concept of whether a particular load uses 'reload semantics' (i.e.\n- # bypasses cached data). For this reason, lots of code needs to pass\n- # around the concept of whether a load should be treated as a 'reload'\n- # separately from their tracking of this transition type, which is mainly\n- # used for proper scoring for consumers who care about how frequently a\n- # user typed/visited a particular URL.\n- # SessionRestore and undo tab close use this transition type too.\n- 9: u'keyword', # The url was generated from a replaceable keyword other than the default\n- # search provider. If the user types a keyword (which also applies to\n- # tab-to-search) in the omnibox this qualifier is applied to the transition\n- # type of the generated url. TemplateURLModel then may generate an\n- # additional visit with a transition type of KEYWORD_GENERATED against the\n- # url 'http://' + keyword. For example, if you do a tab-to-search against\n- # wikipedia the generated url has a transition qualifer of KEYWORD, and\n- # TemplateURLModel generates a visit for 'wikipedia.org' with a transition\n- # type of KEYWORD_GENERATED.\n- 10: u'keyword generated'} # Corresponds to a visit generated for a keyword. See description of\n- # KEYWORD for more details.\n+ 0: 'link', # User got to this page by clicking a link on another page.\n+ 1: 'typed', # User got this page by typing the URL in the URL bar. This should not be\n+ # used for cases where the user selected a choice that didn't look at all\n+ # like a URL; see GENERATED below.\n+ # We also use this for other 'explicit' navigation actions.\n+ 2: 'auto bookmark', # User got to this page through a suggestion in the UI, for example)\n+ # through the destinations page.\n+ 3: 'auto subframe', # This is a subframe navigation. This is any content that is automatically\n+ # loaded in a non-toplevel frame. For example, if a page consists of\n+ # several frames containing ads, those ad URLs will have this transition\n+ # type. The user may not even realize the content in these pages is a\n+ # separate frame, so may not care about the URL (see MANUAL below).\n+ 4: 'manual subframe', # For subframe navigations that are explicitly requested by the user and\n+ # generate new navigation entries in the back/forward list. These are\n+ # probably more important than frames that were automatically loaded in\n+ # the background because the user probably cares about the fact that this\n+ # link was loaded.\n+ 5: 'generated', # User got to this page by typing in the URL bar and selecting an entry\n+ # that did not look like a URL. For example, a match might have the URL\n+ # of a Google search result page, but appear like 'Search Google for ...'.\n+ # These are not quite the same as TYPED navigations because the user\n+ # didn't type or see the destination URL.\n+ # See also KEYWORD.\n+ 6: 'start page', # This is a toplevel navigation. This is any content that is automatically\n+ # loaded in a toplevel frame. For example, opening a tab to show the ASH\n+ # screen saver, opening the devtools window, opening the NTP after the safe\n+ # browsing warning, opening web-based dialog boxes are examples of\n+ # AUTO_TOPLEVEL navigations.\n+ 7: 'form submit', # The user filled out values in a form and submitted it. NOTE that in\n+ # some situations submitting a form does not result in this transition\n+ # type. This can happen if the form uses script to submit the contents.\n+ 8: 'reload', # The user 'reloaded' the page, either by hitting the reload button or by\n+ # hitting enter in the address bar. NOTE: This is distinct from the\n+ # concept of whether a particular load uses 'reload semantics' (i.e.\n+ # bypasses cached data). For this reason, lots of code needs to pass\n+ # around the concept of whether a load should be treated as a 'reload'\n+ # separately from their tracking of this transition type, which is mainly\n+ # used for proper scoring for consumers who care about how frequently a\n+ # user typed/visited a particular URL.\n+ # SessionRestore and undo tab close use this transition type too.\n+ 9: 'keyword', # The url was generated from a replaceable keyword other than the default\n+ # search provider. If the user types a keyword (which also applies to\n+ # tab-to-search) in the omnibox this qualifier is applied to the transition\n+ # type of the generated url. TemplateURLModel then may generate an\n+ # additional visit with a transition type of KEYWORD_GENERATED against the\n+ # url 'http://' + keyword. For example, if you do a tab-to-search against\n+ # wikipedia the generated url has a transition qualifer of KEYWORD, and\n+ # TemplateURLModel generates a visit for 'wikipedia.org' with a transition\n+ # type of KEYWORD_GENERATED.\n+ 10: 'keyword generated'} # Corresponds to a visit generated for a keyword. See description of\n+ # KEYWORD for more details.\n \n qualifiers_friendly = {\n- 0x00800000: u'Blocked', # A managed user attempted to visit a URL but was blocked.\n- 0x01000000: u'Forward or Back', # User used the Forward or Back button to navigate among browsing\n- # history.\n- 0x02000000: u'From Address Bar', # User used the address bar to trigger this navigation.\n- 0x04000000: u'Home Page', # User is navigating to the home page.\n- 0x08000000: u'From API', # The transition originated from an external application; the exact\n- # definition of this is embedder dependent.\n- 0x10000000: u'Navigation Chain Start', # The beginning of a navigation chain.\n- 0x20000000: u'Navigation Chain End', # The last transition in a redirect chain.\n- 0x40000000: u'Client Redirect', # Redirects caused by JavaScript or a meta refresh tag on the page.\n- 0x80000000: u'Server Redirect'} # Redirects sent from the server by HTTP headers. It might be nice to\n- # break this out into 2 types in the future, permanent or temporary,\n- # if we can get that information from WebKit.\n+ 0x00800000: 'Blocked', # A managed user attempted to visit a URL but was blocked.\n+ 0x01000000: 'Forward or Back', # User used the Forward or Back button to navigate among browsing\n+ # history.\n+ 0x02000000: 'From Address Bar', # User used the address bar to trigger this navigation.\n+ 0x04000000: 'Home Page', # User is navigating to the home page.\n+ 0x08000000: 'From API', # The transition originated from an external application; the exact\n+ # definition of this is embedder dependent.\n+ 0x10000000: 'Navigation Chain Start', # The beginning of a navigation chain.\n+ 0x20000000: 'Navigation Chain End', # The last transition in a redirect chain.\n+ 0x40000000: 'Client Redirect', # Redirects caused by JavaScript or a meta refresh tag on the page.\n+ 0x80000000: 'Server Redirect'} # Redirects sent from the server by HTTP headers. It might be nice to\n+ # break this out into 2 types in the future, permanent or temporary,\n+ # if we can get that information from WebKit.\n raw = self.transition\n # If the transition has already been translated to a string, just use that\n- if isinstance(raw, (str, unicode)):\n+ if isinstance(raw, str):\n self.transition_friendly = raw\n return\n \n core_mask = 0xff\n code = raw & core_mask\n \n- if code in transition_friendly.keys():\n+ if code in list(transition_friendly.keys()):\n self.transition_friendly = transition_friendly[code] + '; '\n \n for qualifier in qualifiers_friendly:\n if raw & qualifier == qualifier:\n if not self.transition_friendly:\n- self.transition_friendly = u\"\"\n+ self.transition_friendly = \"\"\n self.transition_friendly += qualifiers_friendly[qualifier] + '; '\n \n def decode_source(self):\n # https://code.google.com/p/chromium/codesearch#chromium/src/components/history/core/browser/history_types.h\n source_friendly = {\n- 0: u'Synced', # Synchronized from somewhere else.\n- 1: u'Local', # User browsed. In my experience, this value isn't written; it will be null.\n- None: u'Local', # See https://cs.chromium.org/chromium/src/components/history/core/browser/visit_database.cc\n- 2: u'Added by Extension', # Added by an extension.\n- 3: u'Firefox (Imported)',\n- 4: u'IE (Imported)',\n- 5: u'Safari (Imported)'}\n+ 0: 'Synced', # Synchronized from somewhere else.\n+ 1: 'Local', # User browsed. In my experience, this value isn't written; it will be null.\n+ None: 'Local', # See https://cs.chromium.org/chromium/src/components/history/core/browser/visit_database.cc\n+ 2: 'Added by Extension', # Added by an extension.\n+ 3: 'Firefox (Imported)',\n+ 4: 'IE (Imported)',\n+ 5: 'Safari (Imported)'}\n \n raw = self.visit_source\n \n- if raw in source_friendly.keys():\n+ if raw in list(source_friendly.keys()):\n self.visit_source = source_friendly[raw]\n \n class DownloadItem(WebBrowser.DownloadItem):\n@@ -2017,118 +2070,118 @@ def __init__(self, profile, download_id, url, received_bytes, total_bytes, state\n \n def decode_interrupt_reason(self):\n interrupts = {\n- 0: u'No Interrupt', # Success\n+ 0: 'No Interrupt', # Success\n \n # from download_interrupt_reason_values.h on Chromium site\n # File errors\n- 1: u'File Error', # Generic file operation failure.\n- 2: u'Access Denied', # The file cannot be accessed due to security restrictions.\n- 3: u'Disk Full', # There is not enough room on the drive.\n- 5: u'Path Too Long', # The directory or file name is too long.\n- 6: u'File Too Large', # The file is too large for the file system to handle.\n- 7: u'Virus', # The file contains a virus.\n- 10: u'Temporary Problem', # The file was in use. Too many files are opened at once. We have run\n- # out of memory.\n- 11: u'Blocked', # The file was blocked due to local policy.\n- 12: u'Security Check Failed', # An attempt to check the safety of the download failed due to\n- # unexpected reasons. See http://crbug.com/153212.\n- 13: u'Resume Error', # An attempt was made to seek past the end of a file in opening a file\n- # (as part of resuming a previously interrupted download).\n+ 1: 'File Error', # Generic file operation failure.\n+ 2: 'Access Denied', # The file cannot be accessed due to security restrictions.\n+ 3: 'Disk Full', # There is not enough room on the drive.\n+ 5: 'Path Too Long', # The directory or file name is too long.\n+ 6: 'File Too Large', # The file is too large for the file system to handle.\n+ 7: 'Virus', # The file contains a virus.\n+ 10: 'Temporary Problem', # The file was in use. Too many files are opened at once. We have run\n+ # out of memory.\n+ 11: 'Blocked', # The file was blocked due to local policy.\n+ 12: 'Security Check Failed', # An attempt to check the safety of the download failed due to\n+ # unexpected reasons. See http://crbug.com/153212.\n+ 13: 'Resume Error', # An attempt was made to seek past the end of a file in opening a file\n+ # (as part of resuming a previously interrupted download).\n \n # Network errors\n- 20: u'Network Error', # Generic network failure.\n- 21: u'Operation Timed Out', # The network operation timed out.\n- 22: u'Connection Lost', # The network connection has been lost.\n- 23: u'Server Down', # The server has gone down.\n+ 20: 'Network Error', # Generic network failure.\n+ 21: 'Operation Timed Out', # The network operation timed out.\n+ 22: 'Connection Lost', # The network connection has been lost.\n+ 23: 'Server Down', # The server has gone down.\n \n # Server responses\n- 30: u'Server Error', # The server indicates that the operation has failed (generic).\n- 31: u'Range Request Error', # The server does not support range requests.\n- 32: u'Server Precondition Error', # The download request does not meet the specified precondition.\n- # Internal use only: the file has changed on the server.\n- 33: u'Unable to get file', # The server does not have the requested data.\n- 34: u'Server Unauthorized', # Server didn't authorize access to resource.\n- 35: u'Server Certificate Problem', # Server certificate problem.\n- 36: u'Server Access Forbidden', # Server access forbidden.\n- 37: u'Server Unreachable', # Unexpected server response. This might indicate that the responding\n- # server may not be the intended server.\n- 38: u'Content Length Mismatch', # The server sent fewer bytes than the content-length header. It may indicate\n- # that the connection was closed prematurely, or the Content-Length header was\n- # invalid. The download is only interrupted if strong validators are present.\n- # Otherwise, it is treated as finished.\n- 39: u'Cross Origin Redirect', # An unexpected cross-origin redirect happened.\n+ 30: 'Server Error', # The server indicates that the operation has failed (generic).\n+ 31: 'Range Request Error', # The server does not support range requests.\n+ 32: 'Server Precondition Error', # The download request does not meet the specified precondition.\n+ # Internal use only: the file has changed on the server.\n+ 33: 'Unable to get file', # The server does not have the requested data.\n+ 34: 'Server Unauthorized', # Server didn't authorize access to resource.\n+ 35: 'Server Certificate Problem', # Server certificate problem.\n+ 36: 'Server Access Forbidden', # Server access forbidden.\n+ 37: 'Server Unreachable', # Unexpected server response. This might indicate that the responding\n+ # server may not be the intended server.\n+ 38: 'Content Length Mismatch', # The server sent fewer bytes than the content-length header. It may indicate\n+ # that the connection was closed prematurely, or the Content-Length header was\n+ # invalid. The download is only interrupted if strong validators are present.\n+ # Otherwise, it is treated as finished.\n+ 39: 'Cross Origin Redirect', # An unexpected cross-origin redirect happened.\n \n \n # User input\n- 40: u'Cancelled', # The user cancelled the download.\n- 41: u'Browser Shutdown', # The user shut down the browser.\n+ 40: 'Cancelled', # The user cancelled the download.\n+ 41: 'Browser Shutdown', # The user shut down the browser.\n \n # Crash\n- 50: u'Browser Crashed'} # The browser crashed.\n+ 50: 'Browser Crashed'} # The browser crashed.\n \n- if self.interrupt_reason in interrupts.keys():\n+ if self.interrupt_reason in list(interrupts.keys()):\n self.interrupt_reason_friendly = interrupts[self.interrupt_reason]\n elif self.interrupt_reason is None:\n self.interrupt_reason_friendly = None\n else:\n- self.interrupt_reason_friendly = u'[Error - Unknown Interrupt Code]'\n+ self.interrupt_reason_friendly = '[Error - Unknown Interrupt Code]'\n log.error(\" - Error decoding interrupt code for download '{}'\".format(self.url))\n \n def decode_danger_type(self):\n # from download_danger_type.h on Chromium site\n dangers = {\n- 0: u'Not Dangerous', # The download is safe.\n- 1: u'Dangerous', # A dangerous file to the system (e.g.: a pdf or extension from places\n- # other than gallery).\n- 2: u'Dangerous URL', # SafeBrowsing download service shows this URL leads to malicious file\n- # download.\n- 3: u'Dangerous Content', # SafeBrowsing download service shows this file content as being\n- # malicious.\n- 4: u'Content May Be Malicious', # The content of this download may be malicious (e.g., extension is exe\n- # but SafeBrowsing has not finished checking the content).\n- 5: u'Uncommon Content', # SafeBrowsing download service checked the contents of the download,\n- # but didn't have enough data to determine whether it was malicious.\n- 6: u'Dangerous But User Validated', # The download was evaluated to be one of the other types of danger,\n- # but the user told us to go ahead anyway.\n- 7: u'Dangerous Host', # SafeBrowsing download service checked the contents of the download\n- # and didn't have data on this specific file, but the file was served\n- # from a host known to serve mostly malicious content.\n- 8: u'Potentially Unwanted', # Applications and extensions that modify browser and/or computer\n- # settings\n- 9: u'Whitelisted by Policy'} # Download URL whitelisted by enterprise policy.\n-\n- if self.danger_type in dangers.keys():\n+ 0: 'Not Dangerous', # The download is safe.\n+ 1: 'Dangerous', # A dangerous file to the system (e.g.: a pdf or extension from places\n+ # other than gallery).\n+ 2: 'Dangerous URL', # SafeBrowsing download service shows this URL leads to malicious file\n+ # download.\n+ 3: 'Dangerous Content', # SafeBrowsing download service shows this file content as being\n+ # malicious.\n+ 4: 'Content May Be Malicious', # The content of this download may be malicious (e.g., extension is exe\n+ # but SafeBrowsing has not finished checking the content).\n+ 5: 'Uncommon Content', # SafeBrowsing download service checked the contents of the download,\n+ # but didn't have enough data to determine whether it was malicious.\n+ 6: 'Dangerous But User Validated', # The download was evaluated to be one of the other types of danger,\n+ # but the user told us to go ahead anyway.\n+ 7: 'Dangerous Host', # SafeBrowsing download service checked the contents of the download\n+ # and didn't have data on this specific file, but the file was served\n+ # from a host known to serve mostly malicious content.\n+ 8: 'Potentially Unwanted', # Applications and extensions that modify browser and/or computer\n+ # settings\n+ 9: 'Whitelisted by Policy'} # Download URL whitelisted by enterprise policy.\n+\n+ if self.danger_type in list(dangers.keys()):\n self.danger_type_friendly = dangers[self.danger_type]\n elif self.danger_type is None:\n self.danger_type_friendly = None\n else:\n- self.danger_type_friendly = u'[Error - Unknown Danger Code]'\n+ self.danger_type_friendly = '[Error - Unknown Danger Code]'\n log.error(\" - Error decoding danger code for download '{}'\".format(self.url))\n \n def decode_download_state(self):\n # from download_item.h on Chromium site\n states = {\n- 0: u\"In Progress\", # Download is actively progressing.\n- 1: u\"Complete\", # Download is completely finished.\n- 2: u\"Cancelled\", # Download has been cancelled.\n- 3: u\"Interrupted\", # '3' was the old \"Interrupted\" code until a bugfix in Chrome v22. 22+ it's '4'\n- 4: u\"Interrupted\"} # This state indicates that the download has been interrupted.\n+ 0: \"In Progress\", # Download is actively progressing.\n+ 1: \"Complete\", # Download is completely finished.\n+ 2: \"Cancelled\", # Download has been cancelled.\n+ 3: \"Interrupted\", # '3' was the old \"Interrupted\" code until a bugfix in Chrome v22. 22+ it's '4'\n+ 4: \"Interrupted\"} # This state indicates that the download has been interrupted.\n \n- if self.state in states.keys():\n+ if self.state in list(states.keys()):\n self.state_friendly = states[self.state]\n else:\n- self.state_friendly = u\"[Error - Unknown State]\"\n+ self.state_friendly = \"[Error - Unknown State]\"\n log.error(\" - Error decoding download state for download '{}'\".format(self.url))\n \n def create_friendly_status(self):\n try:\n- status = u\"%s - %i%% [%i/%i]\" % \\\n+ status = \"%s - %i%% [%i/%i]\" % \\\n (self.state_friendly, (float(self.received_bytes) / float(self.total_bytes)) * 100,\n self.received_bytes, self.total_bytes)\n except ZeroDivisionError:\n- status = u\"%s - %i bytes\" % (self.state_friendly, self.received_bytes)\n+ status = \"%s - %i bytes\" % (self.state_friendly, self.received_bytes)\n except:\n- status = u\"[parsing error]\"\n+ status = \"[parsing error]\"\n log.error(\" - Error creating friendly status message for download '{}'\".format(self.url))\n self.status_friendly = status\n \n@@ -2248,36 +2301,36 @@ def __init__(self, address, size, isHTTPHeader=False):\n \n if isHTTPHeader and self.address.blockType != CacheAddress.SEPARATE_FILE:\n # Getting raw data\n- string = \"\"\n+ block_bytes = b''\n block = open(os.path.join(self.address.path, self.address.fileSelector), 'rb')\n \n # Offset in file\n self.offset = 8192 + self.address.blockNumber*self.address.entrySize\n block.seek(self.offset)\n for _ in range(self.size):\n- string += struct.unpack('c', block.read(1))[0]\n+ block_bytes += struct.unpack('c', block.read(1))[0]\n block.close()\n \n # Finding the beginning of the request\n- start = re.search(\"HTTP\", string)\n+ start = re.search(b'HTTP', block_bytes)\n if start is None:\n return\n else:\n- string = string[start.start():]\n+ block_bytes = block_bytes[start.start():]\n \n # Finding the end (some null characters : verified by experience)\n- end = re.search(\"\\x00\\x00\", string)\n+ end = re.search(b'\\x00\\x00', block_bytes)\n if end is None:\n return\n else:\n- string = string[:end.end()-2]\n+ block_bytes = block_bytes[:end.end()-2]\n \n # Creating the dictionary of headers\n self.headers = {}\n- for line in string.split('\\0'):\n- stripped = line.split(':')\n+ for line in block_bytes.split(b'\\0'):\n+ stripped = line.split(b':')\n self.headers[stripped[0].lower()] = \\\n- ':'.join(stripped[1:]).strip()\n+ b':'.join(stripped[1:]).strip()\n self.type = CacheData.HTTP_HEADER\n \n def save(self, filename=None):\n@@ -2310,7 +2363,7 @@ def __str__(self):\n Display the type of cacheData\n \"\"\"\n if self.type == CacheData.HTTP_HEADER:\n- if self.headers.has_key('content-type'):\n+ if 'content-type' in self.headers:\n return \"HTTP Header %s\" % self.headers['content-type']\n else:\n return \"HTTP Header\"\n@@ -2370,7 +2423,7 @@ def __init__(self, filename):\n \n class CacheItem(Chrome.HistoryItem):\n def __init__(self, profile, url, date_created, key, value, http_headers):\n- super(CacheItem, self).__init__(u'cache', timestamp=date_created, profile=profile, name=key, value=value)\n+ super(CacheItem, self).__init__('cache', timestamp=date_created, profile=profile, name=key, value=value)\n self.profile = profile\n self.url = url\n self.date_created = date_created\n@@ -2411,7 +2464,7 @@ def __init__(self, profile, address, row_type, timezone):\n self.usageCounter = struct.unpack('I', block.read(4))[0]\n self.reuseCounter = struct.unpack('I', block.read(4))[0]\n self.state = struct.unpack('I', block.read(4))[0]\n- self.creationTime = to_datetime(struct.unpack('Q', block.read(8))[0], self.timezone)\n+ self.creationTime = utils.to_datetime(struct.unpack('Q', block.read(8))[0], self.timezone)\n self.keyLength = struct.unpack('I', block.read(4))[0]\n self.keyAddress = struct.unpack('I', block.read(4))[0]\n \n@@ -2486,11 +2539,11 @@ def __init__(self, profile, address, row_type, timezone):\n self.etag = self.http_headers_dict.get('etag')\n self.last_modified = self.http_headers_dict.get('last-modified')\n \n- for key, value in self.http_headers_dict.iteritems():\n+ for key, value in self.http_headers_dict.items():\n if key and value:\n- self.http_headers_str += u\"{}: {}\\n\".format(key, value)\n+ self.http_headers_str += \"{}: {}\\n\".format(key, value)\n elif key:\n- self.http_headers_str += u\"{}\\n\".format(key)\n+ self.http_headers_str += \"{}\\n\".format(key)\n self.http_headers_str = self.http_headers_str.rstrip()\n \n def keyToStr(self):\n@@ -2506,7 +2559,7 @@ def keyToStr(self):\n def __str__(self):\n \n string = \"Hash: 0x%08x\" % self.hash + '\\n'\n- if self.next != 0:\n+ if self.__next__ != 0:\n string += \"Next: 0x%08x\" % self.next + '\\n'\n string += \"Usage Counter: %d\" % self.usageCounter + '\\n'\\\n \"Reuse Counter: %d\" % self.reuseCounter + '\\n'\\\ndiff --git a/pyhindsight/browsers/webbrowser.py b/pyhindsight/browsers/webbrowser.py\n--- a/pyhindsight/browsers/webbrowser.py\n+++ b/pyhindsight/browsers/webbrowser.py\n@@ -7,9 +7,10 @@\n \n \n class WebBrowser(object):\n- def __init__(self, profile_path, browser_name, cache_path=None, version=None, display_version=None,\n- timezone=None, structure=None, parsed_artifacts=None, artifacts_counts=None,\n- artifacts_display=None, preferences=None):\n+ def __init__(\n+ self, profile_path, browser_name, cache_path=None, version=None, display_version=None,\n+ timezone=None, structure=None, parsed_artifacts=None, parsed_storage=None, artifacts_counts=None,\n+ artifacts_display=None, preferences=None):\n self.profile_path = profile_path\n self.browser_name = browser_name\n self.cache_path = cache_path\n@@ -18,6 +19,7 @@ def __init__(self, profile_path, browser_name, cache_path=None, version=None, di\n self.timezone = timezone\n self.structure = structure\n self.parsed_artifacts = parsed_artifacts\n+ self.parsed_storage = parsed_storage\n self.artifacts_counts = artifacts_counts\n self.artifacts_display = artifacts_display\n self.preferences = preferences\n@@ -28,6 +30,9 @@ def __init__(self, profile_path, browser_name, cache_path=None, version=None, di\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.artifacts_counts is None:\n self.artifacts_counts = {}\n \n@@ -55,7 +60,7 @@ def format_profile_path(profile_path):\n \n def build_structure(self, path, database):\n \n- if database not in self.structure.keys():\n+ if database not in list(self.structure.keys()):\n self.structure[database] = {}\n \n # Connect to SQLite db\n@@ -64,7 +69,7 @@ def build_structure(self, path, database):\n db = sqlite3.connect(database_path)\n cursor = db.cursor()\n except sqlite3.OperationalError:\n- print \"Not a database\"\n+ print(\"Not a database\")\n return\n \n # Find the names of each table in the db\n@@ -72,9 +77,9 @@ def build_structure(self, path, database):\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n tables = cursor.fetchall()\n except sqlite3.OperationalError:\n- print \"\\nSQLite3 error; is the Chrome profile in use? Hindsight cannot access history files \" \\\n- \"if Chrome has them locked. This error most often occurs when trying to analyze a local \" \\\n- \"Chrome installation while it is running. Please close Chrome and try again.\"\n+ print(\"\\nSQLite3 error; is the Chrome profile in use? Hindsight cannot access history files \"\n+ \"if Chrome has them locked. This error most often occurs when trying to analyze a local \"\n+ \"Chrome installation while it is running. Please close Chrome and try again.\")\n sys.exit(1)\n except:\n log.error(\" - Couldn't connect to {}\".format(database_path))\n@@ -114,9 +119,10 @@ def __iter__(self):\n return iter(self.__dict__)\n \n class URLItem(HistoryItem):\n- def __init__(self, profile, url_id, url, title, visit_time, last_visit_time, visit_count, typed_count, from_visit,\n- transition, hidden, favicon_id, indexed=None, visit_duration=None, visit_source=None,\n- transition_friendly=None):\n+ def __init__(\n+ self, profile, url_id, url, title, visit_time, last_visit_time, visit_count, typed_count, from_visit,\n+ transition, hidden, favicon_id, indexed=None, visit_duration=None, visit_source=None,\n+ transition_friendly=None):\n super(WebBrowser.URLItem, self).__init__('url', timestamp=visit_time, profile=profile, url=url, name=title)\n self.profile = profile\n self.url_id = url_id\n@@ -136,11 +142,12 @@ def __init__(self, profile, url_id, url, title, visit_time, last_visit_time, vis\n self.transition_friendly = transition_friendly\n \n class DownloadItem(HistoryItem):\n- def __init__(self, profile, download_id, url, received_bytes, total_bytes, state, full_path=None, start_time=None,\n- end_time=None, target_path=None, current_path=None, opened=None, danger_type=None,\n- interrupt_reason=None, etag=None, last_modified=None, chain_index=None, interrupt_reason_friendly=None,\n- danger_type_friendly=None, state_friendly=None, status_friendly=None):\n- super(WebBrowser.DownloadItem, self).__init__(u'download', timestamp=start_time, profile=profile, url=url)\n+ def __init__(\n+ self, profile, download_id, url, received_bytes, total_bytes, state, full_path=None, start_time=None,\n+ end_time=None, target_path=None, current_path=None, opened=None, danger_type=None,\n+ interrupt_reason=None, etag=None, last_modified=None, chain_index=None, interrupt_reason_friendly=None,\n+ danger_type_friendly=None, state_friendly=None, status_friendly=None):\n+ super(WebBrowser.DownloadItem, self).__init__('download', timestamp=start_time, profile=profile, url=url)\n self.profile = profile\n self.download_id = download_id\n self.url = url\n@@ -166,7 +173,8 @@ def __init__(self, profile, download_id, url, received_bytes, total_bytes, state\n class CookieItem(HistoryItem):\n def __init__(self, profile, host_key, path, name, value, creation_utc, last_access_utc, secure, http_only,\n persistent=None, has_expires=None, expires_utc=None, priority=None):\n- super(WebBrowser.CookieItem, self).__init__('cookie', timestamp=creation_utc, profile=profile, url=host_key, name=name, value=value)\n+ super(WebBrowser.CookieItem, self).__init__(\n+ 'cookie', timestamp=creation_utc, profile=profile, url=host_key, name=name, value=value)\n self.profile = profile\n self.host_key = host_key\n self.path = path\n@@ -183,7 +191,8 @@ def __init__(self, profile, host_key, path, name, value, creation_utc, last_acce\n \n class AutofillItem(HistoryItem):\n def __init__(self, profile, date_created, name, value, count):\n- super(WebBrowser.AutofillItem, self).__init__(u'autofill', timestamp=date_created, profile=profile, name=name, value=value)\n+ super(WebBrowser.AutofillItem, self).__init__(\n+ 'autofill', timestamp=date_created, profile=profile, name=name, value=value)\n self.profile = profile\n self.date_created = date_created\n self.name = name\n@@ -192,7 +201,8 @@ def __init__(self, profile, date_created, name, value, count):\n \n class BookmarkItem(HistoryItem):\n def __init__(self, profile, date_added, name, url, parent_folder, sync_transaction_version=None):\n- super(WebBrowser.BookmarkItem, self).__init__(u'bookmark', timestamp=date_added, profile=profile, name=name, value=parent_folder)\n+ super(WebBrowser.BookmarkItem, self).__init__(\n+ 'bookmark', timestamp=date_added, profile=profile, name=name, value=parent_folder)\n self.profile = profile\n self.date_added = date_added\n self.name = name\n@@ -202,7 +212,8 @@ def __init__(self, profile, date_added, name, url, parent_folder, sync_transacti\n \n class BookmarkFolderItem(HistoryItem):\n def __init__(self, profile, date_added, date_modified, name, parent_folder, sync_transaction_version=None):\n- super(WebBrowser.BookmarkFolderItem, self).__init__(u'bookmark folder', timestamp=date_added, profile=profile, name=name, value=parent_folder)\n+ super(WebBrowser.BookmarkFolderItem, self).__init__(\n+ 'bookmark folder', timestamp=date_added, profile=profile, name=name, value=parent_folder)\n self.profile = profile\n self.date_added = date_added\n self.date_modified = date_modified\n@@ -210,15 +221,6 @@ def __init__(self, profile, date_added, date_modified, name, parent_folder, sync\n self.parent_folder = parent_folder\n self.sync_transaction_version = sync_transaction_version\n \n- class LocalStorageItem(HistoryItem):\n- def __init__(self, profile, url, date_created, key, value):\n- super(WebBrowser.LocalStorageItem, self).__init__(u'local storage', timestamp=date_created, profile=profile, name=key, value=value)\n- self.profile = profile\n- self.url = url\n- self.date_created = date_created\n- self.key = key\n- self.value = value\n-\n class BrowserExtension(object):\n def __init__(self, profile, app_id, name, description, version):\n self.profile = profile\n@@ -229,7 +231,8 @@ def __init__(self, profile, app_id, name, description, version):\n \n class LoginItem(HistoryItem):\n def __init__(self, profile, date_created, url, name, value, count):\n- super(WebBrowser.LoginItem, self).__init__(u'login', timestamp=date_created, profile=profile, url=url, name=name, value=value)\n+ super(WebBrowser.LoginItem, self).__init__(\n+ 'login', timestamp=date_created, profile=profile, url=url, name=name, value=value)\n self.profile = profile\n self.date_created = date_created\n self.url = url\n@@ -239,10 +242,60 @@ def __init__(self, profile, date_created, url, name, value, count):\n \n class PreferenceItem(HistoryItem):\n def __init__(self, profile, url, timestamp, key, value, interpretation):\n- super(WebBrowser.PreferenceItem, self).__init__(u'preference', timestamp=timestamp, profile=profile, name=key, value=value)\n+ super(WebBrowser.PreferenceItem, self).__init__(\n+ 'preference', timestamp=timestamp, profile=profile, name=key, value=value)\n self.profile = profile\n self.url = url\n self.timestamp = timestamp\n self.key = key\n self.value = value\n self.interpretation = interpretation\n+\n+ class StorageItem(object):\n+ def __init__(self, item_type, profile, origin, key, value=None, last_modified=None, interpretation=None):\n+ self.row_type = item_type\n+ self.profile = profile\n+ self.origin = origin\n+ self.key = key\n+ self.value = value\n+ self.last_modified = last_modified\n+ self.interpretation = interpretation\n+\n+ def __lt__(self, other):\n+ return self.origin < other.origin\n+\n+ def __iter__(self):\n+ return iter(self.__dict__)\n+\n+ class LocalStorageItem(StorageItem):\n+ def __init__(self, profile, origin, key, value, last_modified=None):\n+ \"\"\"\n+\n+ :param profile: The path to the browser profile this item is part of.\n+ :param origin: The web origin this LocalStorage item belongs to.\n+ :param key: The key of the LocalStorage item.\n+ :param value: The value of the LocalStorage item. It will be rendered in UTF-16 if possible; if not, it\n+ will be shown as a string repr of bytes.\n+ :param last_modified: Approximation of time content under this origin was last modified.\n+ If the LocalStorage items were stored in SQLite, this timestamp is when that SQLite file was last modified.\n+ This means copying the file or otherwise altering the LocalStorage SQLite file's metadata will change this\n+ value.\n+ If the LocalStorage items were stored in LevelDB, this will be blank.\n+ \"\"\"\n+ super(WebBrowser.LocalStorageItem, self).__init__(\n+ 'local storage', profile=profile, origin=origin, key=key, value=value, last_modified=last_modified)\n+ self.profile = profile\n+ self.origin = origin\n+ self.key = key\n+ self.value = value\n+ self.last_modified = last_modified\n+\n+ class FileSystemItem(StorageItem):\n+ def __init__(self, profile, origin, key, value, last_modified=None):\n+ super(WebBrowser.FileSystemItem, self).__init__(\n+ 'file system', profile=profile, origin=origin, key=key, value=value, last_modified=last_modified)\n+ self.profile = profile\n+ self.origin = origin\n+ self.key = key\n+ self.value = value\n+ self.last_modified = last_modified\ndiff --git a/pyhindsight/plugins/chrome_extensions.py b/pyhindsight/plugins/chrome_extensions.py\n--- a/pyhindsight/plugins/chrome_extensions.py\n+++ b/pyhindsight/plugins/chrome_extensions.py\n@@ -8,13 +8,13 @@\n ###################################################################################################\n \n # Config\n-friendlyName = u\"Chrome Extension Names\"\n-description = u\"Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field\"\n-artifactTypes = (u\"url\", u\"local storage\")\n+friendlyName = \"Chrome Extension Names\"\n+description = \"Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field\"\n+artifactTypes = (\"url\", \"local storage\")\n remoteLookups = 0\n-browser = u\"Chrome\"\n+browser = \"Chrome\"\n browserVersion = 1\n-version = u\"20150125\"\n+version = \"20150125\"\n parsedItems = 0\n \n \n@@ -35,10 +35,10 @@ def plugin(analysis_session=None):\n try:\n for ext in analysis_session.installed_extensions['data']:\n if ext.app_id == m.group(1):\n- item.interpretation = u'{} ({}) [Chrome Extension]'.format(ext.name, ext.description)\n+ item.interpretation = '{} ({}) [Chrome Extension]'.format(ext.name, ext.description)\n parsedItems += 1\n except:\n pass\n \n # Description of what the plugin did\n- return u'{} extension URLs parsed'.format(parsedItems)\n+ return '{} extension URLs parsed'.format(parsedItems)\ndiff --git a/pyhindsight/plugins/generic_timestamps.py b/pyhindsight/plugins/generic_timestamps.py\n--- a/pyhindsight/plugins/generic_timestamps.py\n+++ b/pyhindsight/plugins/generic_timestamps.py\n@@ -35,11 +35,11 @@ def plugin(analysis_session=None):\n m = re.search(timestamp_re, item.value)\n ls_m = re.search(ls_timestamp_re, item.value)\n if m:\n- item.interpretation = friendly_date(int(m.group(0))) + u' [potential timestamp]'\n+ item.interpretation = friendly_date(int(m.group(0))) + ' [potential timestamp]'\n parsedItems += 1\n elif ls_m:\n- item.interpretation = friendly_date(int(ls_m.group(1))) + u' [potential timestamp]'\n+ item.interpretation = friendly_date(int(ls_m.group(1))) + ' [potential timestamp]'\n parsedItems += 1\n \n # Description of what the plugin did\n- return u\"{} timestamps parsed\".format(parsedItems)\n+ return \"{} timestamps parsed\".format(parsedItems)\ndiff --git a/pyhindsight/plugins/google_analytics.py b/pyhindsight/plugins/google_analytics.py\n--- a/pyhindsight/plugins/google_analytics.py\n+++ b/pyhindsight/plugins/google_analytics.py\n@@ -14,7 +14,7 @@\n # Config\n friendlyName = \"Google Analytics Cookie Parser\"\n description = \"Parses Google Analytics cookies\"\n-artifactTypes = u'cookie'\n+artifactTypes = 'cookie'\n remoteLookups = 0\n browser = \"all\"\n browserVersion = 1\n@@ -25,7 +25,7 @@\n def plugin(analysis_session=None):\n from pyhindsight.utils import friendly_date\n import re\n- import urllib\n+ import urllib.request, urllib.parse, urllib.error\n \n utma_re = re.compile(r'(\\d+)\\.(\\d+)\\.(\\d{10})\\.(\\d{10})\\.(\\d{10})\\.(\\d+)')\n utmb_re = re.compile(r'(\\d+)\\.(\\d+)\\.\\d+\\.(\\d{10})')\n@@ -41,98 +41,97 @@ def plugin(analysis_session=None):\n \n for item in analysis_session.parsed_artifacts:\n if item.row_type.startswith(artifactTypes):\n- if item.name == u'__utma':\n+ if item.name == '__utma':\n # TODO: consider adding in extra rows for each timestamp in cookie?\n m = re.search(utma_re, item.value)\n if m:\n- item.interpretation = u'Domain Hash: {} | Unique Visitor ID: {} | First Visit: {} | ' \\\n- u'Previous Visit: {} | Last Visit: {} | Number of Sessions: {} | ' \\\n- u'[Google Analytics Cookie]'\\\n+ item.interpretation = 'Domain Hash: {} | Unique Visitor ID: {} | First Visit: {} | ' \\\n+ 'Previous Visit: {} | Last Visit: {} | Number of Sessions: {} | ' \\\n+ '[Google Analytics Cookie]'\\\n .format(m.group(1), m.group(2), friendly_date(m.group(3)),\n friendly_date(m.group(4)), friendly_date(m.group(5)),\n m.group(6))\n parsedItems += 1\n- if item.name == u'__utmb':\n+ if item.name == '__utmb':\n m = re.search(utmb_re, item.value)\n if m:\n- item.interpretation = u'Domain Hash: {} | Pages Viewed: {} | Last Visit: {} | ' \\\n- u'[Google Analytics Cookie]' \\\n+ item.interpretation = 'Domain Hash: {} | Pages Viewed: {} | Last Visit: {} | ' \\\n+ '[Google Analytics Cookie]' \\\n .format(m.group(1), m.group(2), friendly_date(m.group(3)))\n parsedItems += 1\n- if item.name == u'__utmc':\n+ if item.name == '__utmc':\n m = re.search(utmc_re, item.value)\n if m:\n- item.interpretation = u'Domain Hash: {} | [Google Analytics Cookie]'.format(m.group(1))\n+ item.interpretation = 'Domain Hash: {} | [Google Analytics Cookie]'.format(m.group(1))\n parsedItems += 1\n- if item.name == u'__utmv':\n+ if item.name == '__utmv':\n m = re.search(utmv_re, item.value)\n if m:\n- item.interpretation = u'Domain Hash: {} | Custom Values: {} | [Google Analytics Cookie]' \\\n- .format(m.group(1), urllib.unquote_plus(m.group(2)))\n+ item.interpretation = 'Domain Hash: {} | Custom Values: {} | [Google Analytics Cookie]' \\\n+ .format(m.group(1), urllib.parse.unquote_plus(m.group(2)))\n parsedItems += 1\n- if item.name == u'__utmz':\n+ if item.name == '__utmz':\n m = re.search(utmz_re, item.value)\n if m:\n- derived = u'Domain Hash: {} | Last Visit: {} | Sessions: {} | Sources: {} | ' \\\n+ derived = 'Domain Hash: {} | Last Visit: {} | Sessions: {} | Sources: {} | ' \\\n .format(m.group(1), friendly_date(m.group(2)), m.group(3), m.group(4))\n parsedItems += 1\n p = re.search(utmz_parameters_re, item.value)\n \n parameters = {}\n raw_parameters = p.group(5)[3:] # Strip off first 'utm' so later splitting will work\n- # print(raw_parameters)\n \n- #Parse out cookie fields\n- for pair in raw_parameters.split(u'|utm'): # Split the cookie on the '|' delimiter\n+ # Parse out cookie fields\n+ for pair in raw_parameters.split('|utm'): # Split the cookie on the '|' delimiter\n # print pair\n rp = re.search(utmz_extract_parameters_re, pair) # Split each parameter on the first '='\n try:\n parameters[rp.group(1)] = rp.group(2) # Put the parameter name and value in hash\n except AttributeError:\n pass\n- if u'cmd' in parameters:\n+ if 'cmd' in parameters:\n #Ex: 38950847.1357762586.5.5.utmcsr=google.com|utmccn=(referral)|utmcmd=referral|utmcct=/reader/view\n- if parameters[u'cmd'] == u'referral':\n- if u'csr' in parameters and u'cct' in parameters:\n- derived += u'Referrer: {}{} | '.format(parameters[u'csr'], parameters[u'cct'])\n- if parameters[u'ccn'] != u'(referral)':\n- derived += u'Ad Campaign Info: {} | '.format(urllib.unquote_plus(parameters[u'ccn']))\n+ if parameters['cmd'] == 'referral':\n+ if 'csr' in parameters and 'cct' in parameters:\n+ derived += 'Referrer: {}{} | '.format(parameters['csr'], parameters['cct'])\n+ if parameters['ccn'] != '(referral)':\n+ derived += 'Ad Campaign Info: {} | '.format(urllib.parse.unquote_plus(parameters['ccn']))\n \n #Ex: 120910874.1368486805.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)\n- elif parameters[u'cmd'] == u'organic':\n- derived += u'Last Type of Access: {} | '.format(parameters[u'cmd'])\n- if u'ctr' in parameters:\n- derived += u'Search keywords: {} | '.format(urllib.unquote_plus(parameters[u'ctr']))\n- if parameters[u'ccn'] != u'(organic)':\n- derived += u'Ad Campaign Info: %s | '.format(parameters['ccn'])\n+ elif parameters['cmd'] == 'organic':\n+ derived += 'Last Type of Access: {} | '.format(parameters['cmd'])\n+ if 'ctr' in parameters:\n+ derived += 'Search keywords: {} | '.format(urllib.parse.unquote_plus(parameters['ctr']))\n+ if parameters['ccn'] != '(organic)':\n+ derived += 'Ad Campaign Info: %s | '.format(parameters['ccn'])\n \n #Ex: 27069237.1369840721.3.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)\n- elif parameters[u'cmd'] != u'none' and parameters[u'ccn'] == u'(direct)':\n- derived += u'Last Type of Access: {} | '.format(urllib.unquote_plus(parameters[u'ccn']))\n- if u'ctr' in parameters:\n- derived += u'Search keywords: {} | '.format(urllib.unquote_plus(parameters[u'ctr']))\n+ elif parameters['cmd'] != 'none' and parameters['ccn'] == '(direct)':\n+ derived += 'Last Type of Access: {} | '.format(urllib.parse.unquote_plus(parameters['ccn']))\n+ if 'ctr' in parameters:\n+ derived += 'Search keywords: {} | '.format(urllib.parse.unquote_plus(parameters['ctr']))\n \n # Otherwise, just print out all the fields\n else:\n- if u'csr' in parameters:\n- derived += u'Last Source Site: {} | '.format(parameters[u'csr'])\n- if u'ccn' in parameters:\n- derived += u'Ad Campaign Info: {} | '.format(urllib.unquote_plus(parameters[u'ccn']))\n- if u'cmd' in parameters:\n- derived += u'Last Type of Access: {} | '.format(parameters[u'cmd'])\n- if u'ctr' in parameters:\n- derived += u'Keyword(s) from Search that Found Site: {} | '.format(parameters[u'ctr'])\n- if u'cct' in parameters:\n- derived += u'Path to the page on the site of the referring link: {} | '.format(parameters[u'cct'])\n+ if 'csr' in parameters:\n+ derived += 'Last Source Site: {} | '.format(parameters['csr'])\n+ if 'ccn' in parameters:\n+ derived += 'Ad Campaign Info: {} | '.format(urllib.parse.unquote_plus(parameters['ccn']))\n+ if 'cmd' in parameters:\n+ derived += 'Last Type of Access: {} | '.format(parameters['cmd'])\n+ if 'ctr' in parameters:\n+ derived += 'Keyword(s) from Search that Found Site: {} | '.format(parameters['ctr'])\n+ if 'cct' in parameters:\n+ derived += 'Path to the page on the site of the referring link: {} | '.format(parameters['cct'])\n \n- derived += u'[Google Analytics Cookie] '\n+ derived += '[Google Analytics Cookie] '\n item.interpretation = derived\n- if item.name == u'_ga':\n+ if item.name == '_ga':\n m = re.search(ga_re, item.value)\n if m:\n- item.interpretation = u'Client ID: {}.{} | First Visit: {} | [Google Analytics Cookie]' \\\n+ item.interpretation = 'Client ID: {}.{} | First Visit: {} | [Google Analytics Cookie]' \\\n .format(m.group(1), m.group(2), friendly_date(m.group(2)))\n parsedItems += 1\n \n # Description of what the plugin did\n- return u'{} cookies parsed'.format(parsedItems)\n+ return '{} cookies parsed'.format(parsedItems)\ndiff --git a/pyhindsight/plugins/google_searches.py b/pyhindsight/plugins/google_searches.py\n--- a/pyhindsight/plugins/google_searches.py\n+++ b/pyhindsight/plugins/google_searches.py\n@@ -8,19 +8,19 @@\n ###################################################################################################\n \n # Config\n-friendlyName = u'Google Searches'\n-description = u'Extracts parameters from Google search URLs'\n-artifactTypes = (u'url',)\n+friendlyName = 'Google Searches'\n+description = 'Extracts parameters from Google search URLs'\n+artifactTypes = ('url',)\n remoteLookups = 0\n-browser = u'Chrome'\n+browser = 'Chrome'\n browserVersion = 1\n-version = u'20160912'\n+version = '20160912'\n parsedItems = 0\n \n \n def plugin(analysis_session=None):\n import re\n- import urllib\n+ import urllib.request, urllib.parse, urllib.error\n if analysis_session is None:\n return\n \n@@ -32,8 +32,8 @@ def plugin(analysis_session=None):\n global parsedItems\n parsedItems = 0\n \n- time_abbr = {u's': u'second', u'n': u'minute', u'h': u'hour', u'd': u'day', \n- u'w': u'week', u'm': u'month', u'y': u'year'}\n+ time_abbr = {'s': 'second', 'n': 'minute', 'h': 'hour', 'd': 'day', \n+ 'w': 'week', 'm': 'month', 'y': 'year'}\n \n for item in analysis_session.parsed_artifacts:\n if item.row_type.startswith(artifactTypes):\n@@ -42,113 +42,113 @@ def plugin(analysis_session=None):\n parameters = {}\n raw_parameters = m.group(6)\n \n- if m.group(5) == u'#q':\n- raw_parameters = u'q' + raw_parameters\n+ if m.group(5) == '#q':\n+ raw_parameters = 'q' + raw_parameters\n \n #Parse out search parameters\n # TODO: Figure out # vs & separators\n- raw_parameters = raw_parameters.replace(u'#q=', u'&q=') # Replace #q with &q so it will split correctly\n- for pair in raw_parameters.split(u'&'): # Split the query on the '&' delimiter\n+ raw_parameters = raw_parameters.replace('#q=', '&q=') # Replace #q with &q so it will split correctly\n+ for pair in raw_parameters.split('&'): # Split the query on the '&' delimiter\n # print pair\n p = re.search(extract_parameters_re, pair) # Split each parameter on the first '='\n try:\n- parameters[p.group(1)] = urllib.unquote_plus(p.group(2)) # Put parameter name and value in hash\n+ parameters[p.group(1)] = urllib.parse.unquote_plus(p.group(2)) # Put parameter name and value in hash\n except AttributeError:\n pass\n \n- if u'q' in parameters: # 'q' parameter must be present for rest of parameters to be parsed\n- derived = u'Searched for \"{}\" [ '.format(parameters[u'q'])\n+ if 'q' in parameters: # 'q' parameter must be present for rest of parameters to be parsed\n+ derived = 'Searched for \"{}\" [ '.format(parameters['q'])\n \n- if u'pws' in parameters:\n- derived += u'Google personalization turned '\n- derived += (u'on | ' if parameters[u'pws'] == u'1' else u'off | ')\n+ if 'pws' in parameters:\n+ derived += 'Google personalization turned '\n+ derived += ('on | ' if parameters['pws'] == '1' else 'off | ')\n \n- if u'num' in parameters:\n- derived += u'Showing %s results per page' % (parameters[u'num'])\n+ if 'num' in parameters:\n+ derived += 'Showing %s results per page' % (parameters['num'])\n \n- if u'filter' in parameters:\n- derived += u'Omitted/Similar results filter '\n- derived += (u'on | ' if parameters[u'filter'] == u'1' else u'off | ')\n+ if 'filter' in parameters:\n+ derived += 'Omitted/Similar results filter '\n+ derived += ('on | ' if parameters['filter'] == '1' else 'off | ')\n \n- if u'btnl' in parameters:\n- derived += u'\"I\\'m Feeling Lucky\" search '\n- derived += (u'on | ' if parameters[u'btnl'] == u'1' else u'off | ')\n+ if 'btnl' in parameters:\n+ derived += '\"I\\'m Feeling Lucky\" search '\n+ derived += ('on | ' if parameters['btnl'] == '1' else 'off | ')\n \n- if u'safe' in parameters:\n- derived += u'SafeSearch: {} | '.format(parameters[u'safe'])\n+ if 'safe' in parameters:\n+ derived += 'SafeSearch: {} | '.format(parameters['safe'])\n \n- if u'as_qdr' in parameters:\n- qdr = re.search(qdr_re, parameters[u'as_qdr'])\n+ if 'as_qdr' in parameters:\n+ qdr = re.search(qdr_re, parameters['as_qdr'])\n if qdr:\n if qdr.group(1) and qdr.group(2):\n- derived += u'Results in the past {} {}s | '.format(qdr.group(2), time_abbr[qdr.group(1)])\n+ derived += 'Results in the past {} {}s | '.format(qdr.group(2), time_abbr[qdr.group(1)])\n elif qdr.group(1):\n- derived += u'Results in the past {} | '.format(time_abbr[qdr.group(1)])\n+ derived += 'Results in the past {} | '.format(time_abbr[qdr.group(1)])\n \n- if u'tbs' in parameters:\n- tbs_qdr = re.search(tbs_qdr_re, parameters[u'tbs'])\n+ if 'tbs' in parameters:\n+ tbs_qdr = re.search(tbs_qdr_re, parameters['tbs'])\n if tbs_qdr:\n if tbs_qdr.group(1) and tbs_qdr.group(2):\n- derived += u'Results in the past {} {}s | '.format(tbs_qdr.group(2), time_abbr[tbs_qdr.group(1)])\n+ derived += 'Results in the past {} {}s | '.format(tbs_qdr.group(2), time_abbr[tbs_qdr.group(1)])\n elif tbs_qdr.group(1):\n- derived += u'Results in the past {} | '.format(time_abbr[tbs_qdr.group(1)])\n- elif parameters[u'tbs'][:3].lower() == u'cdr':\n- tbs_cd = re.search(tbs_cd_re, parameters[u'tbs'])\n+ derived += 'Results in the past {} | '.format(time_abbr[tbs_qdr.group(1)])\n+ elif parameters['tbs'][:3].lower() == 'cdr':\n+ tbs_cd = re.search(tbs_cd_re, parameters['tbs'])\n if tbs_cd:\n- derived += u'Results in custom range {} - {} | '.format(tbs_cd.group(1), tbs_cd.group(2))\n- elif parameters[u'tbs'][:3].lower() == u'dfn':\n- derived += u'Dictionary definition | '\n- elif parameters[u'tbs'][:3].lower() == u'img':\n- derived += u'Sites with images | '\n- elif parameters[u'tbs'][:4].lower() == u'clir':\n- derived += u'Translated sites | '\n- elif parameters[u'tbs'][:2].lower() == u'li':\n- derived += u'Verbatim results | '\n- elif parameters[u'tbs'][:3].lower() == u'vid':\n- derived += u'Video results | '\n- elif parameters[u'tbs'][:3].lower() == u'nws':\n- derived += u'News results | '\n- elif parameters[u'tbs'][:3].lower() == u'sbd':\n- derived += u'Sorted by date | '\n-\n- if u'bih' in parameters and 'biw' in parameters:\n- derived += u'Browser screen {}x{} | '.format(parameters[u'biw'], parameters[u'bih'])\n-\n- if u'pq' in parameters:\n- if parameters[u'pq'] != parameters[u'q']: # Don't include PQ if same as Q to save space\n- derived += u'Previous query: \"{}\" | '.format(parameters[u'pq'])\n-\n- if u'oq' in parameters:\n- if parameters[u'oq'] != parameters[u'q']: # Don't include OQ if same as Q to save space\n- if u'aq' in parameters:\n+ derived += 'Results in custom range {} - {} | '.format(tbs_cd.group(1), tbs_cd.group(2))\n+ elif parameters['tbs'][:3].lower() == 'dfn':\n+ derived += 'Dictionary definition | '\n+ elif parameters['tbs'][:3].lower() == 'img':\n+ derived += 'Sites with images | '\n+ elif parameters['tbs'][:4].lower() == 'clir':\n+ derived += 'Translated sites | '\n+ elif parameters['tbs'][:2].lower() == 'li':\n+ derived += 'Verbatim results | '\n+ elif parameters['tbs'][:3].lower() == 'vid':\n+ derived += 'Video results | '\n+ elif parameters['tbs'][:3].lower() == 'nws':\n+ derived += 'News results | '\n+ elif parameters['tbs'][:3].lower() == 'sbd':\n+ derived += 'Sorted by date | '\n+\n+ if 'bih' in parameters and 'biw' in parameters:\n+ derived += 'Browser screen {}x{} | '.format(parameters['biw'], parameters['bih'])\n+\n+ if 'pq' in parameters:\n+ if parameters['pq'] != parameters['q']: # Don't include PQ if same as Q to save space\n+ derived += 'Previous query: \"{}\" | '.format(parameters['pq'])\n+\n+ if 'oq' in parameters:\n+ if parameters['oq'] != parameters['q']: # Don't include OQ if same as Q to save space\n+ if 'aq' in parameters:\n aq_re = re.compile(r'^\\d$')\n- ordinals = [u'first', u'second', u'third', u'fourth', u'fifth',\n- u'sixth', u'seventh', u'eighth', u'ninth']\n- if re.search(aq_re, parameters[u'aq']):\n- derived += u'Typed \"{}\" before clicking on the {} suggestion | ' \\\n- .format(parameters[u'oq'], ordinals[int(parameters[u'aq'])])\n+ ordinals = ['first', 'second', 'third', 'fourth', 'fifth',\n+ 'sixth', 'seventh', 'eighth', 'ninth']\n+ if re.search(aq_re, parameters['aq']):\n+ derived += 'Typed \"{}\" before clicking on the {} suggestion | ' \\\n+ .format(parameters['oq'], ordinals[int(parameters['aq'])])\n else:\n- derived += u'Typed \"{}\" before clicking on a suggestion | '.format(parameters[u'oq'])\n+ derived += 'Typed \"{}\" before clicking on a suggestion | '.format(parameters['oq'])\n \n- if u'as_sitesearch' in parameters:\n- derived += u'Search only {} | '.format(parameters[u'as_sitesearch'])\n+ if 'as_sitesearch' in parameters:\n+ derived += 'Search only {} | '.format(parameters['as_sitesearch'])\n \n- if u'as_filetype' in parameters:\n- derived += u'Show only {} files | '.format(parameters[u'as_filetype'])\n+ if 'as_filetype' in parameters:\n+ derived += 'Show only {} files | '.format(parameters['as_filetype'])\n \n- if u'sourceid' in parameters:\n- derived += u'Using {} | '.format(parameters[u'sourceid'])\n+ if 'sourceid' in parameters:\n+ derived += 'Using {} | '.format(parameters['sourceid'])\n \n # if u'ei' in parameters:\n # derived += u'Using %s | ' % (parameters[u'sourceid'])\n \n- if derived[-2:] == u'[ ':\n+ if derived[-2:] == '[ ':\n derived = derived[:-2]\n- elif derived[-3:] == u' | ':\n- derived = derived[:-3] + u']'\n+ elif derived[-3:] == ' | ':\n+ derived = derived[:-3] + ']'\n \n item.interpretation = derived\n parsedItems += 1\n \n # Description of what the plugin did\n- return u'{} searches parsed'.format(parsedItems)\n+ return '{} searches parsed'.format(parsedItems)\ndiff --git a/pyhindsight/plugins/load_balancer_cookies.py b/pyhindsight/plugins/load_balancer_cookies.py\n--- a/pyhindsight/plugins/load_balancer_cookies.py\n+++ b/pyhindsight/plugins/load_balancer_cookies.py\n@@ -18,20 +18,19 @@\n ###################################################################################################\n \n # Config\n-friendlyName = u\"Load Balancer Cookie Decoder\"\n-description = u\"Decodes persistence cookies set by load balancers\"\n-artifactTypes = (u'cookie',) # Artifacts that this plugin processes\n+friendlyName = \"Load Balancer Cookie Decoder\"\n+description = \"Decodes persistence cookies set by load balancers\"\n+artifactTypes = ('cookie',) # Artifacts that this plugin processes\n remoteLookups = 0 # if this plugin will query online sources/databases\n browser = [] # browsers that the plugin applies to; empty list if no restrictions\n browserVersion = [] # browser versions that the plugin applies to; empty list if no restrictions\n-version = u\"20160621\" # version of the plugin (use the date)\n+version = \"20200213\" # version of the plugin (use the date)\n parsedItems = 0 # count of items that the plugin parsed; initialized to 0\n \n \n def plugin(analysis_session=None):\n import re\n import struct\n- from string import maketrans\n if analysis_session is None:\n return\n \n@@ -39,8 +38,8 @@ def nsc_decode_service_name(service_name):\n \"\"\"Decrypts the Caesar Substitution Cipher Encryption used on the NetScaler Cookie Name\"\"\"\n # This decrypts the Caesar Substitution Cipher Encryption used on the NetScaler Cookie Name\n service_name_s = str(service_name)\n- trans = maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\n- 'zabcdefghijklmnopqrstuvwxyZABCDEFGHIJKLMNOPQRSTUVWXY')\n+ trans = str.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\n+ 'zabcdefghijklmnopqrstuvwxyZABCDEFGHIJKLMNOPQRSTUVWXY')\n real_name = service_name_s.translate(trans)\n return real_name\n \ndiff --git a/pyhindsight/plugins/quantcast_cookies.py b/pyhindsight/plugins/quantcast_cookies.py\n--- a/pyhindsight/plugins/quantcast_cookies.py\n+++ b/pyhindsight/plugins/quantcast_cookies.py\n@@ -30,12 +30,12 @@ def plugin(analysis_session=None):\n \n for item in analysis_session.parsed_artifacts:\n if item.row_type in artifactTypes:\n- if item.name == u'__qca':\n+ if item.name == '__qca':\n m = re.search(timestamp_re, item.value)\n if m:\n item.interpretation = friendly_date(int(m.group(3))) \\\n- + u' [Quantcast Cookie Timestamp]'\n+ + ' [Quantcast Cookie Timestamp]'\n parsedItems += 1\n \n # Description of what the plugin did\n- return u\"{} cookies parsed\".format(parsedItems)\n+ return \"{} cookies parsed\".format(parsedItems)\ndiff --git a/pyhindsight/plugins/query_string_parser.py b/pyhindsight/plugins/query_string_parser.py\n--- a/pyhindsight/plugins/query_string_parser.py\n+++ b/pyhindsight/plugins/query_string_parser.py\n@@ -18,7 +18,7 @@\n \n \n def plugin(analysis_session=None):\n- import urlparse\n+ import urllib.parse\n \n # Setting up our return variable\n global parsedItems\n@@ -27,13 +27,13 @@ def plugin(analysis_session=None):\n for item in analysis_session.parsed_artifacts: # For each item that Hindsight has parsed,\n if item.row_type.startswith(artifactTypes): # if the row if of a supported type for this plugin, and\n if item.interpretation is None: # if there isn't already an interpretation,\n- parsed_url = urlparse.urlparse(item.url)\n- query_string_dict = urlparse.parse_qs(parsed_url.query)\n+ parsed_url = urllib.parse.urlparse(item.url)\n+ query_string_dict = urllib.parse.parse_qs(parsed_url.query)\n \n if len(query_string_dict) > 0: # Check if we have any field/value pairs.\n query_string = '' # Create our return string; start it off empty.\n- for field, value in query_string_dict.items(): # Add each field/value to the return string\n- query_string += u'{}: {} | '.format(field, value[0])\n+ for field, value in list(query_string_dict.items()): # Add each field/value to the return string\n+ query_string += '{}: {} | '.format(field, value[0])\n \n item.interpretation = query_string[:-2] + \" [Query String Parser]\"\n parsedItems += 1 # Increment the count of parsed items\ndiff --git a/pyhindsight/plugins/time_discrepancy_finder.py b/pyhindsight/plugins/time_discrepancy_finder.py\n--- a/pyhindsight/plugins/time_discrepancy_finder.py\n+++ b/pyhindsight/plugins/time_discrepancy_finder.py\n@@ -72,29 +72,29 @@ def plugin(analysis_session=None):\n \n for item in analysis_session.parsed_artifacts:\n if item.row_type.startswith(artifactTypes):\n- if item.row_type == u'cookie (created)':\n+ if item.row_type == 'cookie (created)':\n for site in cookie_set:\n- if item.url in site or site.keys()[0] == '*':\n- if site[site.keys()[0]]['name'] == item.name:\n- m = re.search(site[site.keys()[0]]['regex'], item.value)\n+ if item.url in site or list(site.keys())[0] == '*':\n+ if site[list(site.keys())[0]]['name'] == item.name:\n+ m = re.search(site[list(site.keys())[0]]['regex'], item.value)\n if m:\n server = to_datetime(m.group(1), pytz.utc)\n local = item.timestamp\n delta = abs(server - local)\n- item.interpretation = u'Server-side Timestamp: {} | Local Timestamp: {} | ' \\\n- u'Difference: {} [Time Discrepancy]'.format(server, local, delta)\n+ item.interpretation = 'Server-side Timestamp: {} | Local Timestamp: {} | ' \\\n+ 'Difference: {} [Time Discrepancy]'.format(server, local, delta)\n parsedItems += 1\n \n- elif item.row_type == u'url' or item.row_type == u'url (archived)':\n+ elif item.row_type == 'url' or item.row_type == 'url (archived)':\n for site in url_set:\n m = re.search(site, item.url)\n if m:\n server = to_datetime(m.group(1), pytz.utc)\n local = item.timestamp\n delta = abs(server - local)\n- item.interpretation = u'Server-side Timestamp: {} | Local Timestamp: {} | ' \\\n- u'Difference: {} [Time Discrepancy]'.format(server, local, delta)\n+ item.interpretation = 'Server-side Timestamp: {} | Local Timestamp: {} | ' \\\n+ 'Difference: {} [Time Discrepancy]'.format(server, local, delta)\n parsedItems += 1\n \n # Description of what the plugin did\n- return u\"{} differences parsed\".format(parsedItems)\n+ return \"{} differences parsed\".format(parsedItems)\ndiff --git a/pyhindsight/utils.py b/pyhindsight/utils.py\n--- a/pyhindsight/utils.py\n+++ b/pyhindsight/utils.py\n@@ -1,8 +1,12 @@\n import datetime\n import json\n+import logging\n import pytz\n+import struct\n from pyhindsight import __version__\n \n+log = logging.getLogger(__name__)\n+\n \n def format_plugin_output(name, version, items):\n width = 80\n@@ -26,7 +30,7 @@ def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.isoformat()\n elif isinstance(obj, buffer):\n- return unicode(obj, encoding='utf-8', errors='replace')\n+ return str(obj, encoding='utf-8', errors='replace')\n else:\n return obj.__dict__\n \n@@ -79,17 +83,87 @@ def to_datetime(timestamp, timezone=None):\n return new_timestamp\n else:\n return new_timestamp\n- except Exception, e:\n- print e\n+ except Exception as e:\n+ print(e)\n \n \n def friendly_date(timestamp):\n- if isinstance(timestamp, (str, unicode, long, int)):\n+ if isinstance(timestamp, (str, int)):\n return to_datetime(timestamp).strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3]\n+ elif timestamp is None:\n+ return ''\n else:\n return timestamp.strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3]\n \n \n+def get_ldb_pairs(ldb_path, prefix=''):\n+ \"\"\"Open a LevelDB at given path and return a list of all key/value pairs, optionally\n+ filtered by a prefix string. Key and value are kept as byte strings \"\"\"\n+\n+ try:\n+ import plyvel\n+ except ImportError:\n+ log.warning(f' - Failed to import plyvel; unable to process {ldb_path}')\n+ return []\n+\n+ # The ldb key and value are both bytearrays, so the prefix must be too. We allow\n+ # passing the prefix into this function as a string for convenience.\n+ if isinstance(prefix, str):\n+ prefix = prefix.encode()\n+\n+ try:\n+ db = plyvel.DB(ldb_path, create_if_missing=False)\n+ except Exception as e:\n+ log.warning(f' - Couldn\\'t open {ldb_path} as LevelDB; {e}')\n+ return []\n+\n+ cleaned_pairs = []\n+ pairs = list(db.iterator())\n+ for pair in pairs:\n+ # Each leveldb pair should be a tuple of length 2 (key & value); if not, log it and skip it.\n+ if not isinstance(pair, tuple) or len(pair) is not 2:\n+ log.warning(f' - Found LevelDB key/value pair that is not formed as expected ({str(pair)}); skipping.')\n+ continue\n+\n+ key, value = pair\n+ if key.startswith(prefix):\n+ key = key[len(prefix):]\n+ cleaned_pairs.append({'key': key, 'value': value})\n+\n+ return cleaned_pairs\n+\n+\n+def read_varint(source):\n+ result = 0\n+ bytes_used = 0\n+ for read in source:\n+ result |= ((read & 0x7F) << (bytes_used * 7))\n+ bytes_used += 1\n+ if (read & 0x80) != 0x80:\n+ return result, bytes_used\n+\n+\n+def read_string(input_bytes, ptr):\n+ length = struct.unpack('<i', input_bytes[ptr:ptr+4])[0]\n+ ptr += 4\n+ end_ptr = ptr+length\n+ string_value = input_bytes[ptr:end_ptr]\n+ while end_ptr % 4 != 0:\n+ end_ptr += 1\n+\n+ return string_value.decode(), end_ptr\n+\n+\n+def read_int32(input_bytes, ptr):\n+ value = struct.unpack('<i', input_bytes[ptr:ptr + 4])[0]\n+ return value, ptr + 4\n+\n+\n+def read_int64(input_bytes, ptr):\n+ value = struct.unpack('<Q', input_bytes[ptr:ptr + 8])[0]\n+ return value, ptr + 8\n+\n+\n banner = '''\n ################################################################################\n \ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -4,20 +4,21 @@\n packages=find_packages(),\n include_package_data=True,\n scripts=['hindsight.py', 'hindsight_gui.py'],\n- version='2.4.0',\n- description='Internet history forensics for Google Chrome/Chromium',\n+ version='20200607',\n+ description='Browser forensics for Google Chrome/Chromium',\n url='https://github.com/obsidianforensics/hindsight',\n author='Ryan Benson',\n- author_email='ryan@obsidianforensics.com',\n+ author_email='ryan@dfir.blog',\n license='Apache',\n- keywords=['chrome', 'forensics'],\n+ keywords=['chrome', 'forensics', 'dfir', 'google-chrome', 'chromium'],\n classifiers=[],\n install_requires=[\n- 'keyring>=9.0',\n- 'pytz>=2016.4',\n- 'pycryptodomex>=3.4.3',\n- 'xlsxwriter>=0.8.4',\n+ 'bottle>=0.12.18',\n+ 'keyring>=21.2.1',\n+ # 'plyvel>=1.2',\n+ 'pycryptodomex>=3.9.7',\n # 'pypiwin32>=219',\n- 'bottle>=0.12.9'\n+ 'pytz>=2020.1',\n+ 'xlsxwriter>=1.2.9'\n ]\n )\n", "test_patch": "diff --git a/tests/fixtures/profiles/01/History b/tests/fixtures/profiles/01/History\nnew file mode 100644\nBinary files /dev/null and b/tests/fixtures/profiles/01/History differ\ndiff --git a/tests/fixtures/profiles/10/History b/tests/fixtures/profiles/10/History\nnew file mode 100644\nBinary files /dev/null and b/tests/fixtures/profiles/10/History differ\ndiff --git a/tests/fixtures/profiles/20/History b/tests/fixtures/profiles/20/History\nnew file mode 100644\nBinary files /dev/null and b/tests/fixtures/profiles/20/History differ\ndiff --git a/tests/fixtures/profiles/30/History b/tests/fixtures/profiles/30/History\nnew file mode 100644\nBinary files /dev/null and b/tests/fixtures/profiles/30/History differ\ndiff --git a/tests/fixtures/profiles/60/History b/tests/fixtures/profiles/60/History\nnew file mode 100644\nBinary files /dev/null and b/tests/fixtures/profiles/60/History differ\ndiff --git a/tests/test_downloads.py b/tests/test_downloads.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_downloads.py\n@@ -0,0 +1,44 @@\n+import datetime\n+import os\n+import unittest\n+from pyhindsight.browsers.chrome import Chrome\n+\n+\n+class TestGetDownloads(unittest.TestCase):\n+\n+ def test_get_downloads(self):\n+\n+ test_config = [\n+ {'version': [1], 'record_count': 2, 'wikipedia_record': 0, 'wikipedia_timestamp': datetime.datetime(2013, 6, 5, 4, 28, 30)},\n+ {'version': [10], 'record_count': 2, 'wikipedia_record': 0, 'wikipedia_timestamp': datetime.datetime(2013, 6, 27, 4, 23, 25)},\n+ {'version': [20], 'record_count': 2, 'wikipedia_record': 0, 'wikipedia_timestamp': datetime.datetime(2013, 6, 30, 21, 26, 5)},\n+ {'version': [30], 'record_count': 2, 'wikipedia_record': 0, 'wikipedia_timestamp': datetime.datetime(2013, 10, 2, 23, 17, 29, 397160)},\n+ {'version': [60], 'record_count': 2, 'wikipedia_record': 0, 'wikipedia_timestamp': datetime.datetime(2017, 8, 5, 22, 6, 52, 88356)}\n+ ]\n+\n+ for config in test_config:\n+ with self.subTest(config):\n+ test_instance = Chrome(os.path.join('tests', 'fixtures', 'profiles', '{:02d}'.format(config['version'][0])), version=config['version'])\n+\n+ Chrome.get_downloads(test_instance, test_instance.profile_path, 'History', test_instance.version, 'download')\n+\n+ # Total number of records parsed; make sure we aren't dropping/adding any\n+ self.assertEqual(len(test_instance.parsed_artifacts), config['record_count'])\n+\n+ # Wikipedia Computer Forensics file download record; make sure it parses as expected\n+ self.assertIn(test_instance.parsed_artifacts[config['wikipedia_record']].url,\n+ ['http://upload.wikimedia.org/wikipedia/commons/7/7a/Hard_disk.jpg',\n+ 'https://upload.wikimedia.org/wikipedia/commons/7/7a/Hard_disk.jpg'])\n+\n+ self.assertEqual(test_instance.parsed_artifacts[config['wikipedia_record']].timestamp, config['wikipedia_timestamp'])\n+\n+ self.assertEqual(test_instance.parsed_artifacts[config['wikipedia_record']].received_bytes, 1387537)\n+\n+ self.assertIn(test_instance.parsed_artifacts[config['wikipedia_record']].value,\n+ ['C:\\\\Users\\\\Ryan\\\\Downloads\\\\Hard_disk.jpg',\n+ 'C:\\\\Users\\\\Ryan\\\\Documents\\\\Downloads\\\\Hard_disk.jpg',\n+ 'C:\\\\Users\\\\IEUser\\\\Downloads\\\\Hard_disk.jpg'])\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\ndiff --git a/tests/test_history.py b/tests/test_history.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_history.py\n@@ -0,0 +1,36 @@\n+import datetime\n+import os\n+import unittest\n+from pyhindsight.browsers.chrome import Chrome\n+\n+\n+class TestGetHistory(unittest.TestCase):\n+\n+ def test_get_history(self):\n+\n+ test_config = [\n+ {'version': [1], 'record_count': 46, 'wikipedia_record': 7, 'wikipedia_timestamp': datetime.datetime(2013, 6, 5, 4, 28, 55, 498623)},\n+ {'version': [10], 'record_count': 84, 'wikipedia_record': 7, 'wikipedia_timestamp': datetime.datetime(2013, 6, 27, 4, 23, 14, 176756)},\n+ {'version': [20], 'record_count': 58, 'wikipedia_record': 7, 'wikipedia_timestamp': datetime.datetime(2013, 6, 30, 21, 26, 13, 162176)},\n+ {'version': [30], 'record_count': 46, 'wikipedia_record': 4, 'wikipedia_timestamp': datetime.datetime(2013, 10, 2, 23, 15, 13, 326712)},\n+ {'version': [60], 'record_count': 61, 'wikipedia_record': 5, 'wikipedia_timestamp': datetime.datetime(2017, 8, 5, 22, 6, 56, 507864)}\n+ ]\n+\n+ for config in test_config:\n+ with self.subTest(config):\n+ test_instance = Chrome(os.path.join('tests', 'fixtures', 'profiles', '{:02d}'.format(config['version'][0])), version=config['version'])\n+\n+ Chrome.get_history(test_instance, test_instance.profile_path, 'History', test_instance.version, 'url')\n+\n+ # Total number of records parsed; make sure we aren't dropping/adding any\n+ self.assertEqual(len(test_instance.parsed_artifacts), config['record_count'])\n+\n+ # Wikipedia Computer Forensics page record; make sure it parses as expected\n+ self.assertIn(test_instance.parsed_artifacts[config['wikipedia_record']].url,\n+ ['http://en.wikipedia.org/wiki/Computer_forensics', 'https://en.wikipedia.org/wiki/Computer_forensics'])\n+\n+ self.assertEqual(test_instance.parsed_artifacts[config['wikipedia_record']].timestamp, config['wikipedia_timestamp'])\n+\n+\n+if __name__ == '__main__':\n+ unittest.main()\n", "problem_statement": "", "hints_text": "", "created_at": "2020-06-09T04:34:59Z"}
|