예제 #1
0
def Main():
  """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
  argument_parser = argparse.ArgumentParser(description=(
      'Extracts the program cache from a NTUSER.DAT Registry file.'))

  argument_parser.add_argument(
      '-d', '--debug', dest='debug', action='store_true', default=False,
      help='enable debug output.')

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='PATH', default=None,
      help=(
          'path of the volume containing C:\\Windows, the filename of '
          'a storage media image containing the C:\\Windows directory, '
          'or the path of a NTUSER.DAT Registry file.'))

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  output_writer = output_writers.StdoutOutputWriter()

  if not output_writer.Open():
    print('Unable to open output writer.')
    print('')
    return False

  # TODO: add support to select user.
  volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
  registry_collector = collector.WindowsRegistryCollector(
      mediator=volume_scanner_mediator)
  if not registry_collector.ScanForWindowsVolume(options.source):
    print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
        options.source))
    print('')
    return False

  # TODO: map collector to available Registry keys.
  collector_object = programscache.ProgramsCacheCollector(
      debug=options.debug, output_writer=output_writer)

  result = collector_object.Collect(registry_collector.registry)
  if not result:
    print('No Explorer StartPage or StartPage2 keys found.')

  output_writer.Close()

  return True
예제 #2
0
    def testEncodeString(self):
        """Tests the _EncodeString function."""
        test_mediator = command_line.CLIVolumeScannerMediator()

        encoded_string = test_mediator._EncodeString('ASCII')
        self.assertEqual(encoded_string, b'ASCII')

        test_mediator._preferred_encoding = 'ascii'
        encoded_string = test_mediator._EncodeString('\u00b5')
        self.assertEqual(encoded_string, b'?')
예제 #3
0
    def __init__(self, img, output_dir=None, dedup=False, resume=False):

        self.img = img
        img_name = os.path.basename(self.img)
        self.dedup = dedup
        self.resume = resume
        self.last_file = None

        log_file_mode = "wb"
        if self.resume:
            log_file_mode = "ab"

        # mkdirs
        if output_dir:
            self.output_dir = os.path.abspath(output_dir + "/" + img_name)
            if not os.path.exists(self.output_dir):
                os.makedirs(self.output_dir, exist_ok=True)

            self.dedup_dir = self.output_dir + "_duplicates"
            if not os.path.exists(self.dedup_dir):
                os.makedirs(self.dedup_dir, exist_ok=True)
        else:
            self.output_dir = os.path.abspath(".")

        self.log_file = FileOutputWriter(
            os.path.abspath(self.output_dir + "/../%s.log.csv" % img_name))
        self.err_log_file = FileOutputWriter(
            os.path.abspath(self.output_dir + "/../%s.err.csv" % img_name))
        self.log_file.Open(log_file_mode)
        self.err_log_file.Open(log_file_mode)

        if not self.resume:
            self.log_file.WriteFileEntry(
                "entry_type|size|full_path|hash|duplicate")
            self.err_log_file.WriteFileEntry("full_path|error")

        mediator = command_line.CLIVolumeScannerMediator()
        vol_scanner = volume_scanner.VolumeScanner(mediator=mediator)
        self.stats = {
            "errors": 0,
            "total": 0,
            "duplicates": 0,
            "total_size": 0
        }
        self.hashes = {}
        self.base_path_specs = vol_scanner.GetBasePathSpecs(self.img)
예제 #4
0
    def testPrintAPFSVolumeIdentifiersOverview(self):
        """Tests the _PrintAPFSVolumeIdentifiersOverview function."""
        test_path = self._GetTestFilePath(['apfs.dmg'])
        self._SkipIfPathNotExists(test_path)

        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_tsk_partition_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_TSK_PARTITION,
            location='/p1',
            parent=test_raw_path_spec)
        test_apfs_container_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_APFS_CONTAINER,
            location='/',
            parent=test_tsk_partition_path_spec)

        volume_system = apfs_volume_system.APFSVolumeSystem()
        volume_system.Open(test_apfs_container_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        test_mediator._PrintAPFSVolumeIdentifiersOverview(
            volume_system, ['apfs1'])

        file_object.seek(0, os.SEEK_SET)
        output_data = file_object.read()

        expected_output_data = [
            b'The following Apple File System (APFS) volumes were found:', b'',
            b'Identifier      Name', b'apfs1           SingleVolume', b''
        ]

        if not win32console:
            # Using join here since Python 3 does not support format of bytes.
            expected_output_data[2] = b''.join(
                [b'\x1b[1m', expected_output_data[2], b'\x1b[0m'])

        self.assertEqual(output_data.split(b'\n'), expected_output_data)
예제 #5
0
    def testPrintTSKPartitionIdentifiersOverview(self):
        """Tests the _PrintTSKPartitionIdentifiersOverview function."""
        test_path = self._GetTestFilePath(['tsk_volume_system.raw'])
        self._SkipIfPathNotExists(test_path)

        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_tsk_partition_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_TSK_PARTITION,
            parent=test_raw_path_spec)

        volume_system = tsk_volume_system.TSKVolumeSystem()
        volume_system.Open(test_tsk_partition_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        test_mediator._PrintTSKPartitionIdentifiersOverview(
            volume_system, ['p1', 'p2'])

        file_object.seek(0, os.SEEK_SET)
        output_data = file_object.read()

        expected_output_data = [
            b'The following partitions were found:', b'',
            b'Identifier      Offset (in bytes)       Size (in bytes)',
            (b'p1              512 (0x00000200)        175.0KiB / 179.2kB '
             b'(179200 B)'),
            b'p2              180224 (0x0002c000)     1.2MiB / 1.3MB (1294336 B)',
            b''
        ]

        if not win32console:
            # Using join here since Python 3 does not support format of bytes.
            expected_output_data[2] = b''.join(
                [b'\x1b[1m', expected_output_data[2], b'\x1b[0m'])

        self.assertEqual(output_data.split(b'\n'), expected_output_data)
예제 #6
0
    def testFormatHumanReadableSize(self):
        """Tests the _FormatHumanReadableSize function."""
        test_mediator = command_line.CLIVolumeScannerMediator()

        expected_size_string = '1000 B'
        size_string = test_mediator._FormatHumanReadableSize(1000)
        self.assertEqual(size_string, expected_size_string)

        expected_size_string = '1.0KiB / 1.0kB (1024 B)'
        size_string = test_mediator._FormatHumanReadableSize(1024)
        self.assertEqual(size_string, expected_size_string)

        expected_size_string = '976.6KiB / 1.0MB (1000000 B)'
        size_string = test_mediator._FormatHumanReadableSize(1000000)
        self.assertEqual(size_string, expected_size_string)

        expected_size_string = '1.0MiB / 1.0MB (1048576 B)'
        size_string = test_mediator._FormatHumanReadableSize(1048576)
        self.assertEqual(size_string, expected_size_string)
예제 #7
0
    def testPrintVSSStoreIdentifiersOverview(self):
        """Tests the _PrintVSSStoreIdentifiersOverview function."""
        test_path = self._GetTestFilePath(['vsstest.qcow2'])
        self._SkipIfPathNotExists(test_path)

        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_qcow_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_QCOW, parent=test_os_path_spec)
        test_vss_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_VSHADOW, parent=test_qcow_path_spec)

        volume_system = vshadow_volume_system.VShadowVolumeSystem()
        volume_system.Open(test_vss_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        test_mediator._PrintVSSStoreIdentifiersOverview(
            volume_system, ['vss1', 'vss2'])

        file_object.seek(0, os.SEEK_SET)
        output_data = file_object.read()

        expected_output_data = [
            b'The following Volume Shadow Snapshots (VSS) were found:', b'',
            b'Identifier      Creation Time',
            b'vss1            2013-12-03 06:35:09.7363787',
            b'vss2            2013-12-03 06:37:48.9190583', b''
        ]

        if not win32console:
            # Using join here since Python 3 does not support format of bytes.
            expected_output_data[2] = b''.join(
                [b'\x1b[1m', expected_output_data[2], b'\x1b[0m'])

        self.assertEqual(output_data.split(b'\n'), expected_output_data)
예제 #8
0
    def testPrintLVMVolumeIdentifiersOverview(self):
        """Tests the _PrintLVMVolumeIdentifiersOverview function."""
        test_path = self._GetTestFilePath(['lvm.raw'])
        self._SkipIfPathNotExists(test_path)

        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_lvm_container_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_LVM,
            location='/',
            parent=test_raw_path_spec)

        volume_system = lvm_volume_system.LVMVolumeSystem()
        volume_system.Open(test_lvm_container_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        test_mediator._PrintLVMVolumeIdentifiersOverview(
            volume_system, ['lvm1'])

        file_object.seek(0, os.SEEK_SET)
        output_data = file_object.read()

        expected_output_data = [
            b'The following Logical Volume Manager (LVM) volumes were found:',
            b'', b'Identifier', b'lvm1', b''
        ]

        if not win32console:
            # Using join here since Python 3 does not support format of bytes.
            expected_output_data[2] = b''.join(
                [b'\x1b[1m', expected_output_data[2], b'\x1b[0m'])

        self.assertEqual(output_data.split(b'\n'), expected_output_data)
예제 #9
0
    def testParseVolumeIdentifiersString(self):
        """Tests the _ParseVolumeIdentifiersString function."""
        test_mediator = command_line.CLIVolumeScannerMediator()

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString('')
        self.assertEqual(volume_identifiers, [])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString('all')
        self.assertEqual(volume_identifiers, ['all'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString('v1')
        self.assertEqual(volume_identifiers, ['v1'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString('1')
        self.assertEqual(volume_identifiers, ['v1'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString('1,3')
        self.assertEqual(volume_identifiers, ['v1', 'v3'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString(
            '1..3')
        self.assertEqual(volume_identifiers, ['v1', 'v2', 'v3'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString(
            'v1..v3')
        self.assertEqual(volume_identifiers, ['v1', 'v2', 'v3'])

        volume_identifiers = test_mediator._ParseVolumeIdentifiersString(
            '1..3,5')
        self.assertEqual(volume_identifiers, ['v1', 'v2', 'v3', 'v5'])

        with self.assertRaises(ValueError):
            test_mediator._ParseVolumeIdentifiersString('bogus')

        with self.assertRaises(ValueError):
            test_mediator._ParseVolumeIdentifiersString('1..bogus')
예제 #10
0
파일: mru.py 프로젝트: TED-996/winreg-kb
def Main():
  """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
  argument_parser = argparse.ArgumentParser(description=(
      'Extracts Most Recently Used information from a NTUSER.DAT Registry '
      'file.'))

  argument_parser.add_argument(
      '-d', '--debug', dest='debug', action='store_true', default=False,
      help='enable debug output.')

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='PATH', default=None,
      help=(
          'path of the volume containing C:\\Windows, the filename of '
          'a storage media image containing the C:\\Windows directory,'
          'or the path of a NTUSER.DAT Registry file.'))

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  output_writer = StdoutWriter()

  if not output_writer.Open():
    print('Unable to open output writer.')
    print('')
    return False

  volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
  registry_collector = collector.WindowsRegistryCollector(
      mediator=volume_scanner_mediator)
  if not registry_collector.ScanForWindowsVolume(options.source):
    print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
        options.source))
    print('')
    return False

  # TODO: map collector to available Registry keys.
  collector_object = mru.MostRecentlyUsedCollector(
      debug=options.debug, output_writer=output_writer)

  result = collector_object.Collect(registry_collector.registry)
  if not result:
    print('No Most Recently Used key found.')
  else:
    for mru_entry in collector_object.mru_entries:
      output_writer.WriteValue('Key path', mru_entry.key_path)
      output_writer.WriteValue('Value name', mru_entry.value_name)

      if mru_entry.string:
        output_writer.WriteValue('String', mru_entry.string)

      if mru_entry.shell_item_data:
        shell_item = pyfwsi.item()
        shell_item.copy_from_byte_stream(mru_entry.shell_item_data)

        output_writer.WriteShellItem(shell_item)

      elif mru_entry.shell_item_list_data:
        shell_item_list = pyfwsi.item_list()
        shell_item_list.copy_from_byte_stream(mru_entry.shell_item_list_data)

        for shell_item in iter(shell_item_list.items):
          output_writer.WriteShellItem(shell_item)

      output_writer.WriteText('')

  output_writer.Close()

  return True
예제 #11
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Extracts Security Account Manager information from a SAM Registry '
        'file.'))

    argument_parser.add_argument('-d',
                                 '--debug',
                                 dest='debug',
                                 action='store_true',
                                 default=False,
                                 help='enable debug output.')

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='PATH',
        default=None,
        help=('path of the volume containing C:\\Windows, the filename of '
              'a storage media image containing the C:\\Windows directory, '
              'or the path of a SAM Registry file.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer = output_writers.StdoutOutputWriter()

    if not output_writer.Open():
        print('Unable to open output writer.')
        print('')
        return False

    volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    registry_collector = collector.WindowsRegistryCollector(
        mediator=volume_scanner_mediator)
    if not registry_collector.ScanForWindowsVolume(options.source):
        print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
            options.source))
        print('')
        return False

    # TODO: map collector to available Registry keys.
    collector_object = sam.SecurityAccountManagerCollector(
        debug=options.debug, output_writer=output_writer)

    result = collector_object.Collect(registry_collector.registry)
    if not result:
        output_writer.WriteText('No Security Account Manager key found.')
        output_writer.WriteText('')

    else:
        for user_account in collector_object.user_accounts:
            output_writer.WriteValue('Username', user_account.username)
            output_writer.WriteValue('Relative identifier (RID)',
                                     user_account.rid)
            output_writer.WriteValue('Primary group identifier',
                                     user_account.primary_gid)

            if user_account.full_name:
                output_writer.WriteValue('Full name', user_account.full_name)

            if user_account.comment:
                output_writer.WriteValue('Comment', user_account.comment)

            if user_account.user_comment:
                output_writer.WriteValue('User comment',
                                         user_account.user_comment)

            output_writer.WriteFiletimeValue('Last log-in time',
                                             user_account.last_login_time)

            output_writer.WriteFiletimeValue(
                'Last password set time', user_account.last_password_set_time)

            output_writer.WriteFiletimeValue(
                'Account expiration time',
                user_account.account_expiration_time)

            output_writer.WriteFiletimeValue(
                'Last password failure time',
                user_account.last_password_failure_time)

            output_writer.WriteValue('Number of log-ons',
                                     user_account.number_of_logons)
            output_writer.WriteValue('Number of password failures',
                                     user_account.number_of_password_failures)

            if user_account.codepage:
                output_writer.WriteValue('Codepage', user_account.codepage)

            output_writer.WriteText('')

    output_writer.Close()

    return True
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(
        description=('Checks artifact definitions on a storage media image.'))

    argument_parser.add_argument(
        '--artifact_definitions',
        '--artifact-definitions',
        dest='artifact_definitions',
        type=str,
        metavar='PATH',
        action='store',
        help=('Path to a directory or file containing the artifact definition '
              '.yaml files.'))

    argument_parser.add_argument('--back_end',
                                 '--back-end',
                                 dest='back_end',
                                 action='store',
                                 metavar='NTFS',
                                 default=None,
                                 help='preferred dfVFS back-end.')

    argument_parser.add_argument(
        '--partitions',
        '--partition',
        dest='partitions',
        action='store',
        type=str,
        default=None,
        help=
        ('Define partitions to be processed. A range of partitions can be '
         'defined as: "3..5". Multiple partitions can be defined as: "1,3,5" '
         '(a list of comma separated values). Ranges and lists can also be '
         'combined as: "1,3..5". The first partition is 1. All partitions '
         'can be specified with: "all".'))

    argument_parser.add_argument(
        '--snapshots',
        '--snapshot',
        dest='snapshots',
        action='store',
        type=str,
        default=None,
        help=
        ('Define snapshots to be processed. A range of snapshots can be '
         'defined as: "3..5". Multiple snapshots can be defined as: "1,3,5" '
         '(a list of comma separated values). Ranges and lists can also be '
         'combined as: "1,3..5". The first snapshot is 1. All snapshots can '
         'be specified with: "all".'))

    argument_parser.add_argument(
        '--volumes',
        '--volume',
        dest='volumes',
        action='store',
        type=str,
        default=None,
        help=
        ('Define volumes to be processed. A range of volumes can be defined '
         'as: "3..5". Multiple volumes can be defined as: "1,3,5" (a list '
         'of comma separated values). Ranges and lists can also be combined '
         'as: "1,3..5". The first volume is 1. All volumes can be specified '
         'with: "all".'))

    argument_parser.add_argument(
        '-w',
        '--windows_version',
        '--windows-version',
        dest='windows_version',
        action='store',
        metavar='Windows XP',
        default=None,
        help='string that identifies the Windows version.')

    argument_parser.add_argument('source',
                                 nargs='?',
                                 action='store',
                                 metavar='image.raw',
                                 default=None,
                                 help='path of the storage media image.')

    options = argument_parser.parse_args()

    if not options.source:
        print('Path to source storage media image is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    if not options.artifact_definitions:
        print('Path to artifact definitions is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    dfimagetools_helpers.SetDFVFSBackEnd(options.back_end)

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    registry = artifacts_registry.ArtifactDefinitionsRegistry()
    reader = artifacts_reader.YamlArtifactsReader()

    if os.path.isdir(options.artifact_definitions):
        registry.ReadFromDirectory(reader, options.artifact_definitions)
    elif os.path.isfile(options.artifact_definitions):
        registry.ReadFromFile(reader, options.artifact_definitions)

    mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    scanner = volume_scanner.ArtifactDefinitionsVolumeScanner(
        registry, mediator=mediator)

    volume_scanner_options = dfvfs_volume_scanner.VolumeScannerOptions()
    volume_scanner_options.partitions = mediator.ParseVolumeIdentifiersString(
        options.partitions)

    if options.snapshots == 'none':
        volume_scanner_options.snapshots = ['none']
    else:
        volume_scanner_options.snapshots = mediator.ParseVolumeIdentifiersString(
            options.snapshots)

    volume_scanner_options.volumes = mediator.ParseVolumeIdentifiersString(
        options.volumes)

    try:
        if not scanner.ScanForOperatingSystemVolumes(
                options.source, options=volume_scanner_options):
            print('Unable to retrieve an operating system volume from: {0:s}.'.
                  format(options.source))
            print('')
            return False

        definitions_with_check_results = {}
        for artifact_definition in registry.GetDefinitions():
            group_only = True
            for source in artifact_definition.sources:
                if source.type_indicator != (
                        artifacts_definitions.TYPE_INDICATOR_ARTIFACT_GROUP):
                    group_only = False
                    break

            if group_only:
                # Not interested in results of group-only artifact definitions.
                continue

            check_result = scanner.CheckArtifactDefinition(artifact_definition)
            if check_result.number_of_file_entries:
                definitions_with_check_results[
                    artifact_definition.name] = check_result

    except dfvfs_errors.ScannerError as exception:
        print('[ERROR] {0!s}'.format(exception), file=sys.stderr)
        print('')
        return False

    except KeyboardInterrupt:
        print('Aborted by user.', file=sys.stderr)
        print('')
        return False

    print('Aritfact definitions found:')
    for name, check_result in sorted(definitions_with_check_results.items()):
        text = '* {0:s} [results: {1:d}]'.format(
            name, check_result.number_of_file_entries)
        if check_result.data_formats:
            text = '{0:s} [formats: {1:s}]'.format(
                text, ', '.join(sorted(check_result.data_formats)))

        print(text)
    print('')

    return True
예제 #13
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Extracts Application Compatibility Cache information from '
        'a SYSTEM Registry file.'))

    argument_parser.add_argument(
        '--all',
        dest='all_control_sets',
        action='store_true',
        default=False,
        help=(
            'Process all control sets instead of only the current control set.'
        ))

    argument_parser.add_argument('-d',
                                 '--debug',
                                 dest='debug',
                                 action='store_true',
                                 default=False,
                                 help='enable debug output.')

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='PATH',
        default=None,
        help=('path of the volume containing C:\\Windows, the filename of '
              'a storage media image containing the C:\\Windows directory,'
              'or the path of a SYSTEM Registry file.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer = output_writers.StdoutOutputWriter()

    if not output_writer.Open():
        print('Unable to open output writer.')
        print('')
        return False

    volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    registry_collector = collector.WindowsRegistryCollector(
        mediator=volume_scanner_mediator)
    if not registry_collector.ScanForWindowsVolume(options.source):
        print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
            options.source))
        print('')
        return False

    # TODO: map collector to available Registry keys.
    collector_object = appcompatcache.AppCompatCacheCollector(
        debug=options.debug, output_writer=output_writer)

    result = collector_object.Collect(
        registry_collector.registry, all_control_sets=options.all_control_sets)
    if not result:
        output_writer.WriteText(
            'No Application Compatibility Cache key found.')
        output_writer.WriteText('')

    else:
        for cached_entry in collector_object.cached_entries:
            output_writer.WriteFiletimeValue(
                'Last modification time', cached_entry.last_modification_time)
            output_writer.WriteText('\n')

            output_writer.WriteValue('Path', cached_entry.path)
            output_writer.WriteText('\n')

            output_writer.WriteText('')
            output_writer.WriteText('\n')

    output_writer.Close()

    return True
예제 #14
0
    def testGetLVMVolumeIdentifiers(self):
        """Tests the GetLVMVolumeIdentifiers function."""
        test_path = self._GetTestFilePath(['lvm.raw'])
        self._SkipIfPathNotExists(test_path)

        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_lvm_container_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_LVM,
            location='/',
            parent=test_raw_path_spec)

        volume_system = lvm_volume_system.LVMVolumeSystem()
        volume_system.Open(test_lvm_container_path_spec)

        # Test selection of single volume.
        input_file_object = io.BytesIO(b'1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetLVMVolumeIdentifiers(
            volume_system, ['lvm1'])

        self.assertEqual(volume_identifiers, ['lvm1'])

        # Test selection of single volume.
        input_file_object = io.BytesIO(b'lvm1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetLVMVolumeIdentifiers(
            volume_system, ['lvm1'])

        self.assertEqual(volume_identifiers, ['lvm1'])

        # Test selection of single volume with invalid input on first attempt.
        input_file_object = io.BytesIO(b'bogus\nlvm1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetLVMVolumeIdentifiers(
            volume_system, ['lvm1'])

        self.assertEqual(volume_identifiers, ['lvm1'])

        # Test selection of all volumes.
        input_file_object = io.BytesIO(b'all\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetLVMVolumeIdentifiers(
            volume_system, ['lvm1', 'lvm2'])

        self.assertEqual(volume_identifiers, ['lvm1', 'lvm2'])

        # Test selection of no volumes.
        input_file_object = io.BytesIO(b'\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetLVMVolumeIdentifiers(
            volume_system, ['lvm1'])

        self.assertEqual(volume_identifiers, [])
예제 #15
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Lists file entries in a directory or storage media image.'))

    argument_parser.add_argument(
        '--output_file',
        '--output-file',
        dest='output_file',
        action='store',
        metavar='source.hashes',
        default=None,
        help=('path of the output file, default is to output to stdout.'))

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='image.raw',
        default=None,
        help='path of the directory or storage media image.')

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    if options.output_file:
        output_writer = FileOutputWriter(options.output_file)
    else:
        output_writer = StdoutWriter()

    try:
        output_writer.Open()
    except IOError as exception:
        print('Unable to open output writer with error: {0!s}.'.format(
            exception))
        print('')
        return False

    return_value = True
    mediator = command_line.CLIVolumeScannerMediator()
    file_entry_lister = FileEntryLister(mediator=mediator)

    try:
        base_path_specs = file_entry_lister.GetBasePathSpecs(options.source)
        if not base_path_specs:
            print('No supported file system found in source.')
            print('')
            return False

        file_entry_lister.ListFileEntries(base_path_specs, output_writer)

        print('')
        print('Completed.')

    except errors.ScannerError as exception:
        return_value = False

        print('')
        print('[ERROR] {0!s}'.format(exception))

    except KeyboardInterrupt:
        return_value = False

        print('')
        print('Aborted by user.')

    output_writer.Close()

    return return_value
예제 #16
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Calculates a message digest hash for every file in a directory or '
        'storage media image.'))

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='image.raw',
        default=None,
        help=('path of the directory or filename of a storage media image '
              'containing the file.'))

    argument_parser.add_argument('--back_end',
                                 '--back-end',
                                 dest='back_end',
                                 action='store',
                                 metavar='NTFS',
                                 default=None,
                                 help='preferred dfVFS back-end.')

    argument_parser.add_argument(
        '--no-auto-recurse',
        '--no_auto_recurse',
        dest='no_auto_recurse',
        action='store_true',
        default=False,
        help=('Indicate that the source scanner should not auto-recurse.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    helpers.SetDFVFSBackEnd(options.back_end)

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer = StdoutWriter()

    mediator = command_line.CLIVolumeScannerMediator(
        output_writer=output_writer)

    source_analyzer = SourceAnalyzer(auto_recurse=not options.no_auto_recurse,
                                     mediator=mediator)

    return_value = True

    try:
        source_analyzer.Analyze(options.source, output_writer)

        print('Completed.')

    except KeyboardInterrupt:
        return_value = False

        print('Aborted by user.')

    return return_value
예제 #17
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Lists file entries in a directory or storage media image.'))

    argument_parser.add_argument('--back_end',
                                 '--back-end',
                                 dest='back_end',
                                 action='store',
                                 metavar='NTFS',
                                 default=None,
                                 help='preferred dfVFS back-end.')

    argument_parser.add_argument(
        '--output_file',
        '--output-file',
        dest='output_file',
        action='store',
        metavar='source.hashes',
        default=None,
        help=('path of the output file, default is to output to stdout.'))

    argument_parser.add_argument(
        '--partitions',
        '--partition',
        dest='partitions',
        action='store',
        type=str,
        default=None,
        help=
        ('Define partitions to be processed. A range of partitions can be '
         'defined as: "3..5". Multiple partitions can be defined as: "1,3,5" '
         '(a list of comma separated values). Ranges and lists can also be '
         'combined as: "1,3..5". The first partition is 1. All partitions '
         'can be specified with: "all".'))

    argument_parser.add_argument(
        '--snapshots',
        '--snapshot',
        dest='snapshots',
        action='store',
        type=str,
        default=None,
        help=
        ('Define snapshots to be processed. A range of snapshots can be '
         'defined as: "3..5". Multiple snapshots can be defined as: "1,3,5" '
         '(a list of comma separated values). Ranges and lists can also be '
         'combined as: "1,3..5". The first snapshot is 1. All snapshots can '
         'be specified with: "all".'))

    argument_parser.add_argument(
        '--volumes',
        '--volume',
        dest='volumes',
        action='store',
        type=str,
        default=None,
        help=
        ('Define volumes to be processed. A range of volumes can be defined '
         'as: "3..5". Multiple volumes can be defined as: "1,3,5" (a list '
         'of comma separated values). Ranges and lists can also be combined '
         'as: "1,3..5". The first volume is 1. All volumes can be specified '
         'with: "all".'))

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='image.raw',
        default=None,
        help='path of the directory or storage media image.')

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    helpers.SetDFVFSBackEnd(options.back_end)

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    if options.output_file:
        output_writer = FileOutputWriter(options.output_file)
    else:
        output_writer = StdoutWriter()

    try:
        output_writer.Open()
    except IOError as exception:
        print('Unable to open output writer with error: {0!s}.'.format(
            exception))
        print('')
        return False

    mediator = command_line.CLIVolumeScannerMediator()
    file_entry_lister = FileEntryLister(mediator=mediator)

    volume_scanner_options = volume_scanner.VolumeScannerOptions()
    volume_scanner_options.partitions = mediator.ParseVolumeIdentifiersString(
        options.partitions)

    if options.snapshots == 'none':
        volume_scanner_options.snapshots = ['none']
    else:
        volume_scanner_options.snapshots = mediator.ParseVolumeIdentifiersString(
            options.snapshots)

    volume_scanner_options.volumes = mediator.ParseVolumeIdentifiersString(
        options.volumes)

    return_value = True

    try:
        base_path_specs = file_entry_lister.GetBasePathSpecs(
            options.source, options=volume_scanner_options)
        if not base_path_specs:
            print('No supported file system found in source.')
            print('')
            return False

        file_entry_lister.ListFileEntries(base_path_specs, output_writer)

        print('')
        print('Completed.')

    except errors.ScannerError as exception:
        return_value = False

        print('')
        print('[ERROR] {0!s}'.format(exception))

    except KeyboardInterrupt:
        return_value = False

        print('')
        print('Aborted by user.')

    output_writer.Close()

    return return_value
예제 #18
0
    def testGetVSSStoreIdentifiers(self):
        """Tests the GetVSSStoreIdentifiers function."""
        test_path = self._GetTestFilePath(['vsstest.qcow2'])
        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_qcow_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_QCOW, parent=test_os_path_spec)
        test_vss_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_VSHADOW, parent=test_qcow_path_spec)

        volume_system = vshadow_volume_system.VShadowVolumeSystem()
        volume_system.Open(test_vss_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        # Test selection of single store.
        input_file_object = io.BytesIO(b'2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetVSSStoreIdentifiers(
            volume_system, ['vss1', 'vss2'])

        self.assertEqual(volume_identifiers, ['vss2'])

        # Test selection of single store.
        input_file_object = io.BytesIO(b'vss2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetVSSStoreIdentifiers(
            volume_system, ['vss1', 'vss2'])

        self.assertEqual(volume_identifiers, ['vss2'])

        # Test selection of single store with invalid input on first attempt.
        input_file_object = io.BytesIO(b'bogus\nvss2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetVSSStoreIdentifiers(
            volume_system, ['vss1', 'vss2'])

        self.assertEqual(volume_identifiers, ['vss2'])

        # Test selection of all stores.
        input_file_object = io.BytesIO(b'all\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetVSSStoreIdentifiers(
            volume_system, ['vss1', 'vss2'])

        self.assertEqual(volume_identifiers, ['vss1', 'vss2'])

        # Test selection of no stores.
        input_file_object = io.BytesIO(b'\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetVSSStoreIdentifiers(
            volume_system, ['vss1', 'vss2'])

        self.assertEqual(volume_identifiers, [])
예제 #19
0
    def testGetAPFSVolumeIdentifiers(self):
        """Tests the GetAPFSVolumeIdentifiers function."""
        test_path = self._GetTestFilePath(['apfs.dmg'])
        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_tsk_partition_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_TSK_PARTITION,
            location='/p1',
            parent=test_raw_path_spec)
        test_apfs_container_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_APFS_CONTAINER,
            location='/',
            parent=test_tsk_partition_path_spec)

        volume_system = apfs_volume_system.APFSVolumeSystem()
        volume_system.Open(test_apfs_container_path_spec)

        # Test selection of single volume.
        input_file_object = io.BytesIO(b'1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetAPFSVolumeIdentifiers(
            volume_system, ['apfs1'])

        self.assertEqual(volume_identifiers, ['apfs1'])

        # Test selection of single volume.
        input_file_object = io.BytesIO(b'apfs1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetAPFSVolumeIdentifiers(
            volume_system, ['apfs1'])

        self.assertEqual(volume_identifiers, ['apfs1'])

        # Test selection of single volume with invalid input on first attempt.
        input_file_object = io.BytesIO(b'bogus\napfs1\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetAPFSVolumeIdentifiers(
            volume_system, ['apfs1'])

        self.assertEqual(volume_identifiers, ['apfs1'])

        # Test selection of all volumes.
        input_file_object = io.BytesIO(b'all\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetAPFSVolumeIdentifiers(
            volume_system, ['apfs1'])

        self.assertEqual(volume_identifiers, ['apfs1'])

        # Test selection of no volumes.
        input_file_object = io.BytesIO(b'\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetAPFSVolumeIdentifiers(
            volume_system, ['apfs1'])

        self.assertEqual(volume_identifiers, [])
예제 #20
0
    def testGetPartitionIdentifiers(self):
        """Tests the GetPartitionIdentifiers function."""
        test_path = self._GetTestFilePath(['tsk_volume_system.raw'])
        test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_OS, location=test_path)
        test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
        test_tsk_partition_path_spec = path_spec_factory.Factory.NewPathSpec(
            definitions.TYPE_INDICATOR_TSK_PARTITION,
            parent=test_raw_path_spec)

        volume_system = tsk_volume_system.TSKVolumeSystem()
        volume_system.Open(test_tsk_partition_path_spec)

        file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            output_writer=test_output_writer)

        # Test selection of single partition.
        input_file_object = io.BytesIO(b'2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetPartitionIdentifiers(
            volume_system, ['p1', 'p2'])

        self.assertEqual(volume_identifiers, ['p2'])

        # Test selection of single partition.
        input_file_object = io.BytesIO(b'p2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetPartitionIdentifiers(
            volume_system, ['p1', 'p2'])

        self.assertEqual(volume_identifiers, ['p2'])

        # Test selection of single partition with invalid input on first attempt.
        input_file_object = io.BytesIO(b'bogus\np2\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetPartitionIdentifiers(
            volume_system, ['p1', 'p2'])

        self.assertEqual(volume_identifiers, ['p2'])

        # Test selection of all partitions.
        input_file_object = io.BytesIO(b'all\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetPartitionIdentifiers(
            volume_system, ['p1', 'p2'])

        self.assertEqual(volume_identifiers, ['p1', 'p2'])

        # Test selection of no partitions.
        input_file_object = io.BytesIO(b'\n')
        test_input_reader = command_line.FileObjectInputReader(
            input_file_object)

        output_file_object = io.BytesIO()
        test_output_writer = command_line.FileObjectOutputWriter(
            output_file_object)

        test_mediator = command_line.CLIVolumeScannerMediator(
            input_reader=test_input_reader, output_writer=test_output_writer)

        volume_identifiers = test_mediator.GetPartitionIdentifiers(
            volume_system, ['p1', 'p2'])

        self.assertEqual(volume_identifiers, [])
예제 #21
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Extracts the services information from a SYSTEM Registry file.'))

    argument_parser.add_argument(
        '--all',
        dest='all_control_sets',
        action='store_true',
        default=False,
        help=(
            'Process all control sets instead of only the current control set.'
        ))

    argument_parser.add_argument(
        '--diff',
        dest='diff_control_sets',
        action='store_true',
        default=False,
        help='Only list differences between control sets.')

    argument_parser.add_argument('--tsv',
                                 dest='use_tsv',
                                 action='store_true',
                                 default=False,
                                 help='Use tab separated value (TSV) output.')

    argument_parser.add_argument('-d',
                                 '--debug',
                                 dest='debug',
                                 action='store_true',
                                 default=False,
                                 help='enable debug output.')

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='PATH',
        default=None,
        help=('path of the volume containing C:\\Windows, the filename of '
              'a storage media image containing the C:\\Windows directory,'
              'or the path of a SYSTEM Registry file.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer_object = StdoutWriter(use_tsv=options.use_tsv)

    if not output_writer_object.Open():
        print('Unable to open output writer.')
        print('')
        return False

    volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    registry_collector = collector.WindowsRegistryCollector(
        mediator=volume_scanner_mediator)
    if not registry_collector.ScanForWindowsVolume(options.source):
        print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
            options.source))
        print('')
        return False

    # TODO: map collector to available Registry keys.
    collector_object = services.WindowsServicesCollector(debug=options.debug)

    if options.diff_control_sets:
        result = collector_object.Compare(registry_collector.registry,
                                          output_writer_object)
    else:
        result = collector_object.Collect(
            registry_collector.registry,
            output_writer_object,
            all_control_sets=options.all_control_sets)

    if not result:
        print('No Services key found.')

    output_writer_object.Close()

    return True
예제 #22
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Extracts the UserAssist information from a NTUSER.DAT Registry file.'
    ))

    argument_parser.add_argument(
        '--codepage',
        dest='codepage',
        action='store',
        metavar='CODEPAGE',
        default='cp1252',
        help='the codepage of the extended ASCII strings.')

    argument_parser.add_argument('-d',
                                 '--debug',
                                 dest='debug',
                                 action='store_true',
                                 default=False,
                                 help='enable debug output.')

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='PATH',
        default=None,
        help=('path of the volume containing C:\\Windows, the filename of '
              'a storage media image containing the C:\\Windows directory,'
              'or the path of a NTUSER.DAT Registry file.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer = output_writers.StdoutOutputWriter()

    if not output_writer.Open():
        print('Unable to open output writer.')
        print('')
        return False

    volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    registry_collector = collector.WindowsRegistryCollector(
        mediator=volume_scanner_mediator)
    if not registry_collector.ScanForWindowsVolume(options.source):
        print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
            options.source))
        print('')
        return False

    # TODO: map collector to available Registry keys.
    collector_object = userassist.UserAssistCollector(debug=options.debug)

    result = collector_object.Collect(registry_collector.registry)
    if not result:
        print('No UserAssist key found.')
    else:
        guid = None
        for user_assist_entry in collector_object.user_assist_entries:
            if user_assist_entry.guid != guid:
                print('GUID\t\t: {0:s}'.format(user_assist_entry.guid))
                guid = user_assist_entry.guid

            print('Original name\t: {0:s}'.format(
                user_assist_entry.value_name))
            print('Converted name\t: {0:s}'.format(user_assist_entry.name))

    print('')
    output_writer.Close()

    return True
예제 #23
0
def Main():
  """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
  argument_parser = argparse.ArgumentParser(description=(
      'Extracts the shell folder class identifiers from a SOFTWARE Registry '
      'file.'))

  argument_parser.add_argument(
      '-d', '--debug', dest='debug', action='store_true', default=False,
      help='enable debug output.')

  argument_parser.add_argument(
      '--db', dest='database', action='store', metavar='shellitems.db',
      default=None, help='path of the sqlite3 database to write to.')

  argument_parser.add_argument(
      '--winver', dest='windows_version', action='store', metavar='xp',
      default=None, help=(
          'string that identifies the Windows version in the database.'))

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='PATH', default=None,
      help=(
          'path of the volume containing C:\\Windows, the filename of '
          'a storage media image containing the C:\\Windows directory, '
          'or the path of a SOFTWARE Registry file.'))

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  if options.database and not options.windows_version:
    print('Windows version missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  if not options.database:
    output_writer_object = StdoutWriter()
  else:
    output_writer_object = Sqlite3Writer(
        options.database, options.windows_version)

  if not output_writer_object.Open():
    print('Unable to open output writer.')
    print('')
    return False

  volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
  registry_collector = collector.WindowsRegistryCollector(
      mediator=volume_scanner_mediator)
  if not registry_collector.ScanForWindowsVolume(options.source):
    print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
        options.source))
    print('')
    return False

  # TODO: map collector to available Registry keys.
  collector_object = shellfolders.ShellFoldersCollector(
      debug=options.debug)

  result = collector_object.Collect(
      registry_collector.registry, output_writer_object)
  if not result:
    print('No shell folder identifier keys found.')

  output_writer_object.Close()

  return True
예제 #24
0
def Main():
    """The main program function.

  Returns:
    bool: True if successful or False if not.
  """
    argument_parser = argparse.ArgumentParser(description=(
        'Extracts the system information from a SOFTWARE Registry file.'))

    argument_parser.add_argument('-d',
                                 '--debug',
                                 dest='debug',
                                 action='store_true',
                                 default=False,
                                 help=('enable debug output.'))

    argument_parser.add_argument(
        'source',
        nargs='?',
        action='store',
        metavar='PATH',
        default=None,
        help=('path of the volume containing C:\\Windows, the filename of '
              'a storage media image containing the C:\\Windows directory, '
              'or the path of a SOFTWARE Registry file.'))

    options = argument_parser.parse_args()

    if not options.source:
        print('Source value is missing.')
        print('')
        argument_parser.print_help()
        print('')
        return False

    logging.basicConfig(level=logging.INFO,
                        format='[%(levelname)s] %(message)s')

    output_writer = output_writers.StdoutOutputWriter()

    if not output_writer.Open():
        print('Unable to open output writer.')
        print('')
        return False

    volume_scanner_mediator = dfvfs_command_line.CLIVolumeScannerMediator()
    registry_collector = collector.WindowsRegistryCollector(
        mediator=volume_scanner_mediator)
    if not registry_collector.ScanForWindowsVolume(options.source):
        print('Unable to retrieve the Windows Registry from: {0:s}.'.format(
            options.source))
        print('')
        return False

    # TODO: map collector to available Registry keys.
    collector_object = sysinfo.SystemInfoCollector(debug=options.debug,
                                                   output_writer=output_writer)

    result = collector_object.Collect(registry_collector.registry)
    if not result:
        print('No Current Version key found.')
    else:
        output_writer.WriteValue(
            'Product name', collector_object.system_information.product_name)
        output_writer.WriteValue(
            'Product identifier',
            collector_object.system_information.product_identifier)

        output_writer.WriteValue(
            'Current version',
            collector_object.system_information.current_version)
        output_writer.WriteValue(
            'Current type', collector_object.system_information.current_type)
        output_writer.WriteValue(
            'Current build number',
            collector_object.system_information.current_build_number)
        output_writer.WriteValue(
            'CSD version', collector_object.system_information.csd_version)

        output_writer.WriteValue(
            'Registered organization',
            collector_object.system_information.registered_organization)
        output_writer.WriteValue(
            'Registered owner',
            collector_object.system_information.registered_owner)

        date_time_value = collector_object.system_information.installation_date
        date_time_string = date_time_value.CopyToDateTimeString()
        output_writer.WriteValue('Installation date', date_time_string)

        output_writer.WriteValue('Path name',
                                 collector_object.system_information.path_name)
        output_writer.WriteValue(
            '%SystemRoot%', collector_object.system_information.system_root)

        output_writer.WriteText('\n')

    output_writer.Close()

    return True
예제 #25
0
def sunday_funday_569():
    # Handle arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("-v",
                        "--verbosity",
                        help="increase output verbosity",
                        choices=LOG_VERBOSITY)
    parser.add_argument("-i",
                        "--image",
                        required=True,
                        help="filename of a storage media image")
    parser.add_argument("--target",
                        required=True,
                        help="file to extract / compute hash")

    parser.add_argument("--extract", help="Output folder")
    parser.add_argument("--hash",
                        action='store_true',
                        help="compute hash of the specified file")
    parser.add_argument("--list",
                        action='store_true',
                        help="print the specified target file if it exists")

    parser.add_argument("--filter", type=re.compile, help="Output folder")
    parser.add_argument("--csv", help="CSV output file for hashes")

    parser.add_argument("--algo", default='sha256', help="Output folder")
    parser.add_argument("--recurse",
                        action='store_true',
                        help="Enable recursivity if target is a folder")
    parser.add_argument("--noads",
                        action='store_false',
                        help="Disable ADS (Alternate Data Stream) processing")

    args = parser.parse_args()

    # configure logging
    logging.basicConfig(format=LOG_FORMAT,
                        level=LOG_VERBOSITY.get(args.verbosity, 'INFO'),
                        datefmt='%Y-%m-%d %I:%M:%S')

    if not args.extract and not args.hash and not args.list:
        logging.error(
            'Please specify at least an action --list, --hash or --extract <folder>'
        )
        return

    try:
        # Instanciate the processing class
        extractor = Extractor(extract_folder=args.extract,
                              process_hash=args.hash,
                              process_list=args.list,
                              hash_algo=args.algo)
        try:
            csv_out = None
            if args.csv:
                csv_out = open(args.csv, 'wb')
                csv_out.write('Filename|Hash({})\n'.format(args.algo))
        except Exception as e:
            logging.error('Cannot create CSV file: {} [{}]'.format(
                args.csv, e))

        # dfvfs mediator for handling shadow // using interactive command line
        mediator = command_line.CLIVolumeScannerMediator()
        # Scan the given image
        vscanner = volume_scanner.VolumeScanner(mediator=mediator)
        base_path_specs = vscanner.GetBasePathSpecs(args.image)
        # Iterate over each partition/fs found
        for base_path_spec in base_path_specs:
            logging.info('Start processing {}'.format(
                base_path_spec.parent.location))

            # Converting "args.target" to a dfvfs "path_spec" object
            tsk_path_spec = path_spec_factory.Factory.NewPathSpec(
                definitions.TYPE_INDICATOR_TSK,
                location=args.target,
                parent=base_path_spec.parent)
            file_entry = resolver.Resolver.OpenFileEntry(tsk_path_spec)

            if not file_entry:
                logging.debug('   - {} was not found on {}'.format(
                    args.target, base_path_spec.parent.location))
                continue

            # Building prefix, this will be the prefixw of the extracted file(s)
            #   <partition_name>_<path>_<filename>
            #   or
            #   <partition_name>_<path>
            if file_entry.IsDirectory():
                basepath = args.target.replace('/', '_').strip('_')
            else:
                basepath = '_'.join(
                    args.target.split('/')[:-1]).strip('_') + '_'
            prefix = '{}_{}'.format(base_path_spec.parent.location.strip('/'),
                                    basepath)

            # Process
            for filename, filehash in extractor.process(file_entry,
                                                        prefix=prefix,
                                                        recurse=args.recurse,
                                                        ads=args.noads,
                                                        filter=args.filter):
                logging.info('   - {}: {}'.format(filename, filehash))
                if csv_out:
                    csv_out.write('{}|{}\n'.format(filename, filehash))
    except Exception as e:
        logging.error(e)
        raise e

    finally:
        if csv_out:
            csv_out.close()