def test_open_close(self): """Tests the open and close functions.""" test_source = unittest.source if not test_source: return lnk_file = pylnk.file() # Test open and close. lnk_file.open(test_source) lnk_file.close() # Test open and close a second time to validate clean up on close. lnk_file.open(test_source) lnk_file.close() if os.path.isfile(test_source): with open(test_source, "rb") as file_object: # Test open_file_object and close. lnk_file.open_file_object(file_object) lnk_file.close() # Test open_file_object and close a second time to validate clean up on close. lnk_file.open_file_object(file_object) lnk_file.close() # Test open_file_object and close and dereferencing file_object. lnk_file.open_file_object(file_object) del file_object lnk_file.close()
def test_open_file_object(self): """Tests the open_file_object function.""" test_source = unittest.source if not test_source: raise unittest.SkipTest("missing source") if not os.path.isfile(test_source): raise unittest.SkipTest("source not a regular file") lnk_file = pylnk.file() with open(test_source, "rb") as file_object: lnk_file.open_file_object(file_object) with self.assertRaises(IOError): lnk_file.open_file_object(file_object) lnk_file.close() with self.assertRaises(TypeError): lnk_file.open_file_object(None) with self.assertRaises(ValueError): lnk_file.open_file_object(file_object, mode="w")
def open_file_as_lnk(lnk_file): file_size = lnk_file.info.meta.size file_content = lnk_file.read_random(0, file_size) file_like_obj = StringIO.StringIO(file_content) lnk = pylnk.file() lnk.open_file_object(file_like_obj) return lnk
def pylnk_test_single_open_close_file_object_with_dereference( filename, mode): """Tests single file-like object open and close with dereference.""" description = ( "Testing single open close of file-like object with dereference of: " "{0:s} with access: {1:s}\t").format( get_filename_string(filename), get_mode_string(mode)) print(description, end="") error_string = None result = True try: file_object = open(filename, "rb") lnk_file = pylnk.file() lnk_file.open_file_object(file_object, mode) del file_object lnk_file.close() except Exception as exception: error_string = str(exception) result = False if not result: print("(FAIL)") else: print("(PASS)") if error_string: print(error_string) return result
def test_open_close(self): """Tests the open and close functions.""" if not unittest.source: return lnk_file = pylnk.file() # Test open and close. lnk_file.open(unittest.source) lnk_file.close() # Test open and close a second time to validate clean up on close. lnk_file.open(unittest.source) lnk_file.close() file_object = open(unittest.source, "rb") # Test open_file_object and close. lnk_file.open_file_object(file_object) lnk_file.close() # Test open_file_object and close a second time to validate clean up on close. lnk_file.open_file_object(file_object) lnk_file.close() # Test open_file_object and close and dereferencing file_object. lnk_file.open_file_object(file_object) del file_object lnk_file.close()
def pylnk_test_multi_open_close_file(filename, mode): """Tests multiple open and close.""" description = ( "Testing multi open close of: {0:s} with access: {1:s}" "\t").format(get_filename_string(filename), get_mode_string(mode)) print(description, end="") error_string = None result = True try: lnk_file = pylnk.file() lnk_file.open(filename, mode) lnk_file.close() lnk_file.open(filename, mode) lnk_file.close() except Exception as exception: error_string = str(exception) result = False if not result: print("(FAIL)") else: print("(PASS)") if error_string: print(error_string) return result
def ParseFileObject(self, parser_context, file_object, file_entry=None, display_name=None): """Parses a Windows Shortcut (LNK) file. The file entry is used to determine the display name if it was not provided. Args: parser_context: A parser context object (instance of ParserContext). file_object: A file-like object. file_entry: Optional file entry object (instance of dfvfs.FileEntry). The default is None. display_name: Optional display name. """ if not display_name and file_entry: display_name = parser_context.GetDisplayName(file_entry) lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_context.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: lnk_file.close() raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s} with error: {2:s}'.format( self.NAME, display_name, exception)) link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. if file_entry: display_name = file_entry.name shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.Parse(parser_context, lnk_file.link_target_identifier_data, codepage=parser_context.codepage) link_target = shell_items_parser.CopyToPath() parser_context.ProduceEvents([ WinLnkLinkEvent(lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file, link_target), WinLnkLinkEvent(lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file, link_target), WinLnkLinkEvent(lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file, link_target) ], parser_name=self.NAME, file_entry=file_entry) # TODO: add support for the distributed link tracker. lnk_file.close()
def Parse(self, file_entry): """Extract data from a Windows Shortcut (LNK) file. Args: file_entry: A file entry object. Yields: An event object (instance of WinLnkLinkEvent) that contains the parsed attributes. """ file_object = file_entry.GetFileObject() lnk_file = pylnk.file() lnk_file.set_ascii_codepage(self._codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s}: {2:s}'.format( self.parser_name, file_entry.name, exception)) yield WinLnkLinkEvent(lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file) yield WinLnkLinkEvent(lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file) yield WinLnkLinkEvent(lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file) # TODO: add support for the distributed link tracker. # TODO: add support for the shell item. file_object.close()
def parse_Compound_File(file_to_parse): file_object = open(file_to_parse, "rb") olecf_file = pyolecf.file() olecf_file.open_file_object(file_object) SQLitedb.CreateTempTable(table_name + '_temp', table_columns) root_item = olecf_file.get_root_item() Base_Name = ntpath.basename(file_to_parse) (File_Name, Extension) = ntpath.splitext(Base_Name) if (App_Id.CheckAppId(File_Name)): App_Id_Desc = App_Id.SelectAppId(File_Name)[0] else: App_Id_Desc = File_Name for i in range(0, root_item.get_number_of_sub_items()): jl_record = [] jl_record.append(File_Name) jl_record.append(App_Id_Desc) new_item = root_item.get_sub_item(i) jl_record.append(new_item.get_name()) if new_item.get_name() == u'DestList': continue new_link_item = pylnk.file() new_link_item.open_file_object(new_item) jl_record = Create_Bind_Values(jl_record, new_link_item) SQLitedb.InsertBindValues(table_name + '_temp', sql_ins_columns, sql_bind, jl_record) if (SQLitedb.TableExists(table_name)): SQLitedb.AppendTempToPermanentTable(table_name) else: SQLitedb.CreatePermanentTable(table_name) SQLitedb.DropTable(table_name + '_temp')
def ParseFileObject(self, parser_mediator, file_object, display_name=None, **kwargs): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator: A parser mediator object (instance of ParserMediator). file_object: A file-like object. display_name: Optional display name. Raises: UnableToParseFile: when the file cannot be parsed. """ if not display_name: display_name = parser_mediator.GetDisplayName() lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_mediator.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s} with error: {2:s}'.format( self.NAME, display_name, exception)) link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. file_entry = parser_mediator.GetFileEntry() display_name = file_entry.name shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.UpdateChainAndParse( parser_mediator, lnk_file.link_target_identifier_data, None, codepage=parser_mediator.codepage) link_target = shell_items_parser.CopyToPath() parser_mediator.ProduceEvents([ WinLnkLinkEvent(lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file, link_target), WinLnkLinkEvent(lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file, link_target), WinLnkLinkEvent(lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file, link_target) ]) # TODO: add support for the distributed link tracker. lnk_file.close()
def test_close(self): """Tests the close function.""" if not unittest.source: return lnk_file = pylnk.file() with self.assertRaises(IOError): lnk_file.close()
def test_close(self): """Tests the close function.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() with self.assertRaises(IOError): lnk_file.close()
def __init__(self, identifier): """Initializes the LNK file entry object. Args: identifier: the LNK file entry identifier. """ super(LNKFileEntry, self).__init__() self._lnk_file = pylnk.file() self.identifier = identifier self.data_size = 0
def __init__(self, identifier): """Initializes the LNK file entry object. Args: identifier (str): LNK file entry identifier. """ super(LNKFileEntry, self).__init__() self._lnk_file = pylnk.file() self.identifier = identifier self.data_size = 0
def ParseFileObject( self, parser_context, file_object, file_entry=None, display_name=None): """Parses a Windows Shortcut (LNK) file. The file entry is used to determine the display name if it was not provided. Args: parser_context: A parser context object (instance of ParserContext). file_object: A file-like object. file_entry: Optional file entry object (instance of dfvfs.FileEntry). The default is None. display_name: Optional display name. """ if not display_name and file_entry: display_name = parser_context.GetDisplayName(file_entry) lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_context.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: lnk_file.close() raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s} with error: {2:s}'.format( self.NAME, display_name, exception)) link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. if file_entry: display_name = file_entry.name shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.Parse( parser_context, lnk_file.link_target_identifier_data, codepage=parser_context.codepage) link_target = shell_items_parser.CopyToPath() parser_context.ProduceEvents( [WinLnkLinkEvent( lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file, link_target), WinLnkLinkEvent( lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file, link_target), WinLnkLinkEvent( lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file, link_target)], parser_name=self.NAME, file_entry=file_entry) # TODO: add support for the distributed link tracker. lnk_file.close()
def ParseFileObject( self, parser_mediator, file_object, display_name=None, **kwargs): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator: A parser mediator object (instance of ParserMediator). file_object: A file-like object. display_name: Optional display name. Raises: UnableToParseFile: when the file cannot be parsed. """ if not display_name: display_name = parser_mediator.GetDisplayName() lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_mediator.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s} with error: {2:s}'.format( self.NAME, display_name, exception)) link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. file_entry = parser_mediator.GetFileEntry() display_name = file_entry.name shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.UpdateChainAndParse( parser_mediator, lnk_file.link_target_identifier_data, None, codepage=parser_mediator.codepage) link_target = shell_items_parser.CopyToPath() parser_mediator.ProduceEvents( [WinLnkLinkEvent( lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file, link_target), WinLnkLinkEvent( lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file, link_target), WinLnkLinkEvent( lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file, link_target)]) # TODO: add support for the distributed link tracker. lnk_file.close()
def test_get_environment_variables_location(self): """Tests the get_environment_variables_location function and environment_variables_location property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_environment_variables_location() _ = lnk_file.environment_variables_location lnk_file.close()
def test_get_machine_identifier(self): """Tests the get_machine_identifier function and machine_identifier property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_machine_identifier() _ = lnk_file.machine_identifier lnk_file.close()
def test_get_command_line_arguments(self): """Tests the get_command_line_arguments function and command_line_arguments property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_command_line_arguments() _ = lnk_file.command_line_arguments lnk_file.close()
def test_get_icon_location(self): """Tests the get_icon_location function and icon_location property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_icon_location() _ = lnk_file.icon_location lnk_file.close()
def test_get_working_directory(self): """Tests the get_working_directory function and working_directory property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_working_directory() _ = lnk_file.working_directory lnk_file.close()
def test_get_relative_path(self): """Tests the get_relative_path function and relative_path property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_relative_path() _ = lnk_file.relative_path lnk_file.close()
def test_get_volume_label(self): """Tests the get_volume_label function and volume_label property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_volume_label() _ = lnk_file.volume_label lnk_file.close()
def test_get_drive_serial_number(self): """Tests the get_drive_serial_number function and drive_serial_number property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) _ = lnk_file.get_drive_serial_number() _ = lnk_file.drive_serial_number lnk_file.close()
def pylnk_test_single_open_close_file(filename, mode): """Tests a single open and close.""" description = ( "Testing single open close of: {0:s} with access: {1:s}" "\t").format(get_filename_string(filename), get_mode_string(mode)) print(description, end="") error_string = None result = True try: lnk_file = pylnk.file() lnk_file.open(filename, mode) lnk_file.close() except TypeError as exception: expected_message = ( "{0:s}: unsupported string object type.").format( "pylnk_file_open") if not filename and str(exception) == expected_message: pass else: error_string = str(exception) result = False except ValueError as exception: expected_message = ( "{0:s}: unsupported mode: w.").format( "pylnk_file_open") if mode != "w" or str(exception) != expected_message: error_string = str(exception) result = False except Exception as exception: error_string = str(exception) result = False if not result: print("(FAIL)") else: print("(PASS)") if error_string: print(error_string) return result
def test_get_hot_key_value(self): """Tests the get_hot_key_value function and hot_key_value property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) hot_key_value = lnk_file.get_hot_key_value() self.assertIsNotNone(hot_key_value) self.assertIsNotNone(lnk_file.hot_key_value) lnk_file.close()
def test_get_description(self): """Tests the get_description function and description property.""" test_source = unittest.source if not test_source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(test_source) _ = lnk_file.get_description() _ = lnk_file.description lnk_file.close()
def test_get_file_attribute_flags(self): """Tests the get_file_attribute_flags function and file_attribute_flags property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) file_attribute_flags = lnk_file.get_file_attribute_flags() self.assertIsNotNone(file_attribute_flags) self.assertIsNotNone(lnk_file.file_attribute_flags) lnk_file.close()
def test_get_ascii_codepage(self): """Tests the get_ascii_codepage function and ascii_codepage property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) ascii_codepage = lnk_file.get_ascii_codepage() self.assertIsNotNone(ascii_codepage) self.assertIsNotNone(lnk_file.ascii_codepage) lnk_file.close()
def test_get_file_size(self): """Tests the get_file_size function and file_size property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) file_size = lnk_file.get_file_size() self.assertIsNotNone(file_size) self.assertIsNotNone(lnk_file.file_size) lnk_file.close()
def test_get_icon_index(self): """Tests the get_icon_index function and icon_index property.""" if not unittest.source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(unittest.source) icon_index = lnk_file.get_icon_index() self.assertIsNotNone(icon_index) self.assertIsNotNone(lnk_file.icon_index) lnk_file.close()
def test_get_network_path(self): """Tests the get_network_path function and network_path property.""" test_source = unittest.source if not test_source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(test_source) _ = lnk_file.get_network_path() _ = lnk_file.network_path lnk_file.close()
def test_get_drive_type(self): """Tests the get_drive_type function and drive_type property.""" test_source = unittest.source if not test_source: raise unittest.SkipTest("missing source") lnk_file = pylnk.file() lnk_file.open(test_source) _ = lnk_file.get_drive_type() _ = lnk_file.drive_type lnk_file.close()
def _ExtractFromLNK(self, file_object, full_path, output_writer): """Extracts Windows shell items from a Windows Shortcut file-like object. Args: file_object: the file-like object. full_path: a string containing the full path of the file entry. output_writer: the output writer (instance of OutputWriter). """ lnk_file = pylnk.file() lnk_file.open_file_object(file_object) try: self._ExtractFromData( lnk_file.link_target_identifier_data, output_writer) finally: lnk_file.close()
def _ExtractFromLNK(self, file_object, unused_full_path, output_writer): """Extracts Windows shell items from a Windows Shortcut file-like object. Args: file_object (dfvfs.FileIO): file-like object. full_path (str): full path of the file entry. output_writer (OutputWriter): output writer. """ lnk_file = pylnk.file() lnk_file.open_file_object(file_object) try: self._ExtractFromData( lnk_file.link_target_identifier_data, output_writer) finally: lnk_file.close()
def pylnk_test_single_open_close_file(filename, mode): if not filename: filename_string = "None" else: filename_string = filename print("Testing single open close of: {0:s} with access: {1:s}\t".format( filename_string, get_mode_string(mode))) result = True try: lnk_file = pylnk.file() lnk_file.open(filename, mode) lnk_file.close() except TypeError as exception: expected_message = ( "{0:s}: unsupported string object type.").format( "pylnk_file_open") if not filename and str(exception) == expected_message: pass else: print(str(exception)) result = False except ValueError as exception: expected_message = ( "{0:s}: unsupported mode: w.").format( "pylnk_file_open") if mode != "w" or str(exception) != expected_message: print(str(exception)) result = False except Exception as exception: print(str(exception)) result = False if not result: print("(FAIL)") else: print("(PASS)") return result
def Main(): """The main program function. Returns: A boolean containing True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( u'Extracts Windows Shell items from the source.')) argument_parser.add_argument( u'-o', u'--output-file', u'--output_file', dest=u'output_file', action=u'store', metavar=u'FILE', default=None, help=( u'name of the output file to write the data to.')) argument_parser.add_argument( u'source', nargs=u'?', action=u'store', metavar=u'PATH', default=None, help=( u'path of the source to extract Windows Shell items from.')) options = argument_parser.parse_args() if not options.source: print(u'Source file missing.') print(u'') argument_parser.print_help() print(u'') return False logging.basicConfig( level=logging.INFO, format=u'[%(levelname)s] %(message)s') lnk_file = pylnk.file() lnk_file.open(options.source) if not options.output_file: print(hexdump.Hexdump(lnk_file.link_target_identifier_data)) else: with open(options.output_file, 'wb') as output_file: output_file.write(lnk_file.link_target_identifier_data) lnk_file.close() return True
def parse_Compound_File(file_to_parse): file_object = open(file_to_parse, "rb") olecf_file = pyolecf.file() olecf_file.open_file_object(file_object) SQLitedb.CreateTempTable(table_name + '_temp', table_columns) root_item = olecf_file.get_root_item() #print ("Root Item Name ==> " + root_item.get_name()) #print ("Number of Sub_Items ==> " + str(root_item.get_number_of_sub_items())) Base_Name = ntpath.basename(file_to_parse) (File_Name, Extension) = ntpath.splitext(Base_Name) if (App_Id.CheckAppId(File_Name)): App_Id_Desc = App_Id.SelectAppId(File_Name)[0] #print ("App id => " + App_Id.SelectAppId(File_Name)[0]) else: App_Id_Desc = File_Name #print ("File Name => " + File_Name) for i in range (0, root_item.get_number_of_sub_items()): jl_record = [] jl_record.append(File_Name) jl_record.append(App_Id_Desc) new_item = root_item.get_sub_item(i) jl_record.append(new_item.get_name()) #print (" Sub Item Name ==> " + new_item.get_name()) #print (" Sub Item Sub Items ==> " + str(new_item.get_number_of_sub_items())) if new_item.get_name() == u'DestList': continue new_link_item = pylnk.file() new_link_item.open_file_object(new_item) jl_record = Create_Bind_Values(jl_record, new_link_item) try: SQLitedb.InsertBindValues(table_name + '_temp', sql_ins_columns, sql_bind, jl_record) except: print ("Error in Link Item ==> " + str(jl_record[1]) + " <==> " + str(jl_record[2])) if (SQLitedb.TableExists(table_name)): SQLitedb.AppendTempToPermanentTable(table_name) else: SQLitedb.CreatePermanentTable(table_name) SQLitedb.DropTable(table_name + '_temp')
def test_open(self): """Tests the open function.""" if not unittest.source: return lnk_file = pylnk.file() lnk_file.open(unittest.source) with self.assertRaises(IOError): lnk_file.open(unittest.source) lnk_file.close() with self.assertRaises(TypeError): lnk_file.open(None) with self.assertRaises(ValueError): lnk_file.open(unittest.source, mode="w")
def test_set_ascii_codepage(self): """Tests the set_ascii_codepage function.""" supported_codepages = ( "ascii", "cp874", "cp932", "cp936", "cp949", "cp950", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258") lnk_file = pylnk.file() for codepage in supported_codepages: lnk_file.set_ascii_codepage(codepage) unsupported_codepages = ( "iso-8859-1", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10", "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "koi8_r", "koi8_u") for codepage in unsupported_codepages: with self.assertRaises(RuntimeError): lnk_file.set_ascii_codepage(codepage)
def pylnk_test_single_open_close_file_object(filename, mode): print(("Testing single open close of file-like object of: {0:s} " "with access: {1:s}\t").format(filename, get_mode_string(mode))) result = True try: file_object = open(filename, "rb") lnk_file = pylnk.file() lnk_file.open_file_object(file_object, mode) lnk_file.close() except Exception as exception: print(str(exception)) result = False if not result: print("(FAIL)") else: print("(PASS)") return result
def pylnk_test_multi_open_close_file(filename, mode): print("Testing multi open close of: {0:s} with access: {1:s}\t".format( filename, get_mode_string(mode))) result = True try: lnk_file = pylnk.file() lnk_file.open(filename, mode) lnk_file.close() lnk_file.open(filename, mode) lnk_file.close() except Exception as exception: print(str(exception)) result = False if not result: print("(FAIL)") else: print("(PASS)") return result
def test_open_file_object(self): """Tests the open_file_object function.""" if not unittest.source: return file_object = open(unittest.source, "rb") lnk_file = pylnk.file() lnk_file.open_file_object(file_object) with self.assertRaises(IOError): lnk_file.open_file_object(file_object) lnk_file.close() # TODO: change IOError into TypeError with self.assertRaises(IOError): lnk_file.open_file_object(None) with self.assertRaises(ValueError): lnk_file.open_file_object(file_object, mode="w")
def Parse(self, file_entry): """Extract data from a Windows Shortcut (LNK) file. Args: file_entry: A file entry object. Yields: An event object (instance of WinLnkLinkEvent) that contains the parsed attributes. """ file_object = file_entry.GetFileObject() lnk_file = pylnk.file() lnk_file.set_ascii_codepage(self._codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: raise errors.UnableToParseFile( u'[{0:s}] unable to parse file {1:s}: {2:s}'.format( self.parser_name, file_entry.name, exception)) yield WinLnkLinkEvent( lnk_file.get_file_access_time_as_integer(), eventdata.EventTimestamp.ACCESS_TIME, lnk_file) yield WinLnkLinkEvent( lnk_file.get_file_creation_time_as_integer(), eventdata.EventTimestamp.CREATION_TIME, lnk_file) yield WinLnkLinkEvent( lnk_file.get_file_modification_time_as_integer(), eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file) # TODO: add support for the distributed link tracker. # TODO: add support for the shell item. file_object.close()
def test_signal_abort(self): """Tests the signal_abort function.""" lnk_file = pylnk.file() lnk_file.signal_abort()
def ParseFileObject( self, parser_mediator, file_object, display_name=None, **kwargs): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator: A parser mediator object (instance of ParserMediator). file_object: A file-like object. display_name: Optional display name. """ if not display_name: display_name = parser_mediator.GetDisplayName() lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_mediator.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionError( u'unable to open file with error: {0:s}'.format(exception)) return link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. display_name = parser_mediator.GetFilename() shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.ParseByteStream( parser_mediator, lnk_file.link_target_identifier_data, codepage=parser_mediator.codepage) link_target = shell_items_parser.CopyToPath() access_time = lnk_file.get_file_access_time_as_integer() if access_time > 0: parser_mediator.ProduceEvent( WinLnkLinkEvent( access_time, eventdata.EventTimestamp.ACCESS_TIME, lnk_file, link_target)) creation_time = lnk_file.get_file_creation_time_as_integer() if creation_time > 0: parser_mediator.ProduceEvent( WinLnkLinkEvent( creation_time, eventdata.EventTimestamp.CREATION_TIME, lnk_file, link_target)) modification_time = lnk_file.get_file_modification_time_as_integer() if modification_time > 0: parser_mediator.ProduceEvent( WinLnkLinkEvent( modification_time, eventdata.EventTimestamp.MODIFICATION_TIME, lnk_file, link_target)) if access_time == 0 and creation_time == 0 and modification_time == 0: parser_mediator.ProduceEvent( WinLnkLinkEvent( 0, eventdata.EventTimestamp.NOT_A_TIME, lnk_file, link_target)) try: uuid_object = uuid.UUID(lnk_file.droid_file_identifier) if uuid_object.version == 1: event_object = ( windows_events.WindowsDistributedLinkTrackingCreationEvent( uuid_object, display_name)) parser_mediator.ProduceEvent(event_object) except (TypeError, ValueError): pass try: uuid_object = uuid.UUID(lnk_file.birth_droid_file_identifier) if uuid_object.version == 1: event_object = ( windows_events.WindowsDistributedLinkTrackingCreationEvent( uuid_object, display_name)) parser_mediator.ProduceEvent(event_object) except (TypeError, ValueError): pass lnk_file.close()
def main(): supported_codepages = [ "ascii", "cp874", "cp932", "cp936", "cp949", "cp950", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258"] unsupported_codepages = [ "iso-8859-1", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-7", "iso-8859-8", "iso-8859-9", "iso-8859-10", "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "koi8_r", "koi8_u"] lnk_file = pylnk.file() result = True for codepage in supported_codepages: print("Testing setting supported ASCII codepage of: {0:s}:\t".format( codepage)), try: lnk_file.ascii_codepage = codepage result = True except: result = False if not result: print("(FAIL)") return False print("(PASS)") print("Testing setting supported ASCII codepage of: {0:s}:\t".format( codepage)), try: lnk_file.set_ascii_codepage(codepage) result = True except: result = False if not result: print("(FAIL)") return False print("(PASS)") for codepage in unsupported_codepages: print("Testing setting unsupported ASCII codepage of: {0:s}:\t".format( codepage)), result = False try: lnk_file.ascii_codepage = codepage except RuntimeError as exception: expected_message = ( "{0:s}: unable to determine ASCII codepage.").format( "pylnk_file_set_ascii_codepage_from_string") if str(exception) == expected_message: result = True except: pass if not result: print("(FAIL)") return False print("(PASS)") print("Testing setting unsupported ASCII codepage of: {0:s}:\t".format( codepage)), result = False try: lnk_file.set_ascii_codepage(codepage) except RuntimeError as exception: expected_message = ( "{0:s}: unable to determine ASCII codepage.").format( "pylnk_file_set_ascii_codepage_from_string") if str(exception) == expected_message: result = True except: pass if not result: print("(FAIL)") return False print("(PASS)") return True
def ParseFileLNKFile( self, parser_mediator, file_object, display_name): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. display_name (str): display name. """ lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_mediator.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionError( 'unable to open file with error: {0!s}'.format(exception)) return link_target = None if lnk_file.link_target_identifier_data: # TODO: change file_entry.name to display name once it is generated # correctly. display_name = parser_mediator.GetFilename() shell_items_parser = shell_items.ShellItemsParser(display_name) shell_items_parser.ParseByteStream( parser_mediator, lnk_file.link_target_identifier_data, codepage=parser_mediator.codepage) link_target = shell_items_parser.CopyToPath() event_data = WinLnkLinkEventData() event_data.birth_droid_file_identifier = ( lnk_file.birth_droid_file_identifier) event_data.birth_droid_volume_identifier = ( lnk_file.birth_droid_volume_identifier) event_data.command_line_arguments = lnk_file.command_line_arguments event_data.description = lnk_file.description event_data.drive_serial_number = lnk_file.drive_serial_number event_data.drive_type = lnk_file.drive_type event_data.droid_file_identifier = lnk_file.droid_file_identifier event_data.droid_volume_identifier = lnk_file.droid_volume_identifier event_data.env_var_location = lnk_file.environment_variables_location event_data.file_attribute_flags = lnk_file.file_attribute_flags event_data.file_size = lnk_file.file_size event_data.icon_location = lnk_file.icon_location event_data.link_target = link_target event_data.local_path = lnk_file.local_path event_data.network_path = lnk_file.network_path event_data.relative_path = lnk_file.relative_path event_data.volume_label = lnk_file.volume_label event_data.working_directory = lnk_file.working_directory access_time = lnk_file.get_file_access_time_as_integer() if access_time != 0: date_time = dfdatetime_filetime.Filetime(timestamp=access_time) event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS) parser_mediator.ProduceEventWithEventData(event, event_data) creation_time = lnk_file.get_file_creation_time_as_integer() if creation_time != 0: date_time = dfdatetime_filetime.Filetime(timestamp=creation_time) event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_CREATION) parser_mediator.ProduceEventWithEventData(event, event_data) modification_time = lnk_file.get_file_modification_time_as_integer() if modification_time != 0: date_time = dfdatetime_filetime.Filetime(timestamp=modification_time) event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_MODIFICATION) parser_mediator.ProduceEventWithEventData(event, event_data) if access_time == 0 and creation_time == 0 and modification_time == 0: date_time = dfdatetime_semantic_time.SemanticTime('Not set') event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME) parser_mediator.ProduceEventWithEventData(event, event_data) if lnk_file.droid_file_identifier: try: self._ParseDistributedTrackingIdentifier( parser_mediator, lnk_file.droid_file_identifier, display_name) except (TypeError, ValueError) as exception: parser_mediator.ProduceExtractionError( 'unable to read droid file identifier with error: {0!s}.'.format( exception)) if lnk_file.birth_droid_file_identifier: try: self._ParseDistributedTrackingIdentifier( parser_mediator, lnk_file.birth_droid_file_identifier, display_name) except (TypeError, ValueError) as exception: parser_mediator.ProduceExtractionError(( 'unable to read birth droid file identifier with error: ' '{0!s}.').format(exception)) lnk_file.close()