Пример #1
0
        private static void Main(string[] args)
        {
            ExceptionlessClient.Default.Startup("wPXTiiouhEbK0s19lCgjiDThpfrW0ODU8RskdPEk");


            SetupNLog();

            _logger = LogManager.GetCurrentClassLogger();


            _fluentCommandLineParser = new FluentCommandLineParser <ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.FileDb)
            .As('f')
            .WithDescription("SRUDB.dat file to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.FileReg)
            .As('r')
            .WithDescription("SOFTWARE hive to process. This is optional, but recommended\r\n");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
            .As('d')
            .WithDescription("Directory to recursively process, looking for SRUDB.dat and SOFTWARE hive. This mode is primarily used with KAPE so both SRUDB.dat and SOFTWARE hive can be located");

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
            .As("csv")
            .WithDescription(
                "Directory to save CSV formatted results to. Be sure to include the full path in double quotes\r\n");

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
            .As("dt")
            .WithDescription(
                "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss.fffffff\r\n")
            .SetDefault("yyyy-MM-dd HH:mm:ss.fffffff");

            _fluentCommandLineParser.Setup(arg => arg.Debug)
            .As("debug")
            .WithDescription("Show debug information during processing").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.Trace)
            .As("trace")
            .WithDescription("Show trace information during processing\r\n").SetDefault(false);


            var header =
                $"SrumECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/Srum";


            var footer = @"Examples: SrumECmd.exe -f ""C:\Temp\SRUDB.dat"" -r ""C:\Temp\SOFTWARE"" --csv ""C:\Temp\"" " + "\r\n\t " +
                         @" SrumECmd.exe -f ""C:\Temp\SRUDB.dat"" --csv ""c:\temp""" + "\r\n\t " +
                         @" SrumECmd.exe -d ""C:\Temp"" --csv ""c:\temp""" + "\r\n\t " +
                         "\r\n\t" +
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
            .WithHeader(header)
            .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (_fluentCommandLineParser.Object.FileDb.IsNullOrEmpty() &&
                _fluentCommandLineParser.Object.Directory.IsNullOrEmpty())
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting\r\n");
                return;
            }

            if (_fluentCommandLineParser.Object.FileDb.IsNullOrEmpty() == false &&
                !File.Exists(_fluentCommandLineParser.Object.FileDb))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.FileDb}' not found. Exiting");
                return;
            }

            if (_fluentCommandLineParser.Object.Directory.IsNullOrEmpty() == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            if (_fluentCommandLineParser.Object.CsvDirectory.IsNullOrEmpty())
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("--csv is required. Exiting\r\n");
                return;
            }

            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");

            if (IsAdministrator() == false)
            {
                _logger.Fatal("Warning: Administrator privileges not found!\r\n");
            }

            if (_fluentCommandLineParser.Object.Debug)
            {
                LogManager.Configuration.LoggingRules.First().EnableLoggingForLevel(LogLevel.Debug);
            }

            if (_fluentCommandLineParser.Object.Trace)
            {
                LogManager.Configuration.LoggingRules.First().EnableLoggingForLevel(LogLevel.Trace);
            }

            LogManager.ReconfigExistingLoggers();

            var sw = new Stopwatch();

            sw.Start();

            var ts = DateTimeOffset.UtcNow;

            CsvWriter    _csvWriter = null;
            StreamWriter _swCsv     = null;

            Srum sr = null;

            if (_fluentCommandLineParser.Object.Directory.IsNullOrEmpty() == false)
            {
                //kape mode, so find the files
                var f = new DirectoryEnumerationFilters();
                f.InclusionFilter = fsei =>
                {
                    if (fsei.FileSize == 0)
                    {
                        return(false);
                    }

                    if (fsei.FileName.ToUpperInvariant() == "SRUDB.DAT")
                    {
                        return(true);
                    }

                    return(false);
                };

                f.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

                f.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

                var dirEnumOptions =
                    DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
                    DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
                    DirectoryEnumerationOptions.BasicSearch;

                var files2 =
                    Directory.EnumerateFileSystemEntries(_fluentCommandLineParser.Object.Directory, dirEnumOptions, f);

                _fluentCommandLineParser.Object.FileDb = files2.FirstOrDefault();

                if (_fluentCommandLineParser.Object.FileDb.IsNullOrEmpty())
                {
                    _logger.Warn("Did not locate any files named 'SRUDB.dat'! Exiting");
                    return;
                }

                _logger.Info($"Found SRUM database file '{_fluentCommandLineParser.Object.FileDb}'!");

                f = new DirectoryEnumerationFilters();
                f.InclusionFilter = fsei =>
                {
                    if (fsei.FileSize == 0)
                    {
                        return(false);
                    }

                    if (fsei.FileName.ToUpperInvariant() == "SOFTWARE")
                    {
                        return(true);
                    }

                    return(false);
                };

                f.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

                f.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

                files2 =
                    Directory.EnumerateFileSystemEntries(_fluentCommandLineParser.Object.Directory, dirEnumOptions, f);

                _fluentCommandLineParser.Object.FileReg = files2.FirstOrDefault();

                if (_fluentCommandLineParser.Object.FileReg.IsNullOrEmpty())
                {
                    _logger.Warn("Did not locate any files named 'SOFTWARE'! Registry data will not be extracted");
                }
                else
                {
                    _logger.Info($"Found SOFTWARE hive '{_fluentCommandLineParser.Object.FileReg}'!");
                }

                Console.WriteLine();
            }

            try
            {
                _logger.Info($"Processing '{_fluentCommandLineParser.Object.FileDb}'...");
                sr = new Srum(_fluentCommandLineParser.Object.FileDb, _fluentCommandLineParser.Object.FileReg);

                _logger.Warn("\r\nProcessing complete!\r\n");
                _logger.Info($"{"Energy Usage count:".PadRight(30)} {sr.EnergyUsages.Count:N0}");
                _logger.Info($"{"Unknown 312 count:".PadRight(30)} {sr.Unknown312s.Count:N0}");
                _logger.Info($"{"Unknown D8F count:".PadRight(30)} {sr.UnknownD8Fs.Count:N0}");
                _logger.Info($"{"App Resource Usage count:".PadRight(30)} {sr.AppResourceUseInfos.Count:N0}");
                _logger.Info($"{"Network Connection count:".PadRight(30)} {sr.NetworkConnections.Count:N0}");
                _logger.Info($"{"Network Usage count:".PadRight(30)} {sr.NetworkUsages.Count:N0}");
                _logger.Info($"{"Push Notification count:".PadRight(30)} {sr.PushNotifications.Count:N0}");
                Console.WriteLine();
            }
            catch (Exception e)
            {
                _logger.Error($"Error processing file! Message: {e.Message}.\r\n\r\nThis almost always means the database is dirty and must be repaired. This can be verified by running 'esentutl.exe /mh SRUDB.dat' and examining the 'State' property");
                Console.WriteLine();
                _logger.Info("If the database is dirty, **make a copy of your files**, ensure all files in the directory are not Read-only, open a PowerShell session as an admin, and repair by using the following commands (change directories to the location of SRUDB.dat first):\r\n\r\n'esentutl.exe /r sru /i'\r\n'esentutl.exe /p SRUDB.dat'\r\n\r\n");
                Environment.Exit(0);
            }

            if (_fluentCommandLineParser.Object.CsvDirectory.IsNullOrEmpty() == false)
            {
                if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                {
                    _logger.Warn(
                        $"Path to '{_fluentCommandLineParser.Object.CsvDirectory}' doesn't exist. Creating...");

                    try
                    {
                        Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                    }
                    catch (Exception)
                    {
                        _logger.Fatal(
                            $"Unable to create directory '{_fluentCommandLineParser.Object.CsvDirectory}'. Does a file with the same name exist? Exiting");
                        return;
                    }
                }


                var outName = string.Empty;

                var outFile = string.Empty;

                _logger.Warn($"CSV output will be saved to '{_fluentCommandLineParser.Object.CsvDirectory}'\r\n");

                try
                {
                    _logger.Debug($"Dumping Energy Usage tables '{EnergyUsage.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_EnergyUsage_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <EnergyUsage>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");
                    foo.Map(t => t.EventTimestamp).ConvertUsing(t =>
                                                                $"{t.EventTimestamp?.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <EnergyUsage>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.EnergyUsages.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'EnergyUsage' data! Error: {e.Message}");
                }


                try
                {
                    _logger.Debug($"Dumping Unknown 312 table '{Unknown312.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_Unknown312_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <Unknown312>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");
                    foo.Map(t => t.EndTime).ConvertUsing(t =>
                                                         $"{t.EndTime.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <Unknown312>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.Unknown312s.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'Unknown312' data! Error: {e.Message}");
                }

                try
                {
                    _logger.Debug($"Dumping Unknown D8F table '{UnknownD8F.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_UnknownD8F_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <UnknownD8F>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");
                    foo.Map(t => t.EndTime).ConvertUsing(t =>
                                                         $"{t.EndTime.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");
                    foo.Map(t => t.StartTime).ConvertUsing(t =>
                                                           $"{t.StartTime.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <UnknownD8F>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.UnknownD8Fs.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'UnknownD8F' data! Error: {e.Message}");
                }

                try
                {
                    _logger.Debug($"Dumping AppResourceUseInfo table '{AppResourceUseInfo.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_AppResourceUseInfo_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <AppResourceUseInfo>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <AppResourceUseInfo>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.AppResourceUseInfos.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'AppResourceUseInfo' data! Error: {e.Message}");
                }

                try
                {
                    _logger.Debug($"Dumping NetworkConnection table '{NetworkConnection.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkConnections_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <NetworkConnection>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");
                    foo.Map(t => t.ConnectStartTime).ConvertUsing(t =>
                                                                  $"{t.ConnectStartTime.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <NetworkConnection>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.NetworkConnections.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'NetworkConnection' data! Error: {e.Message}");
                }

                try
                {
                    _logger.Debug($"Dumping NetworkUsage table '{NetworkUsage.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkUsages_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <NetworkUsage>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <NetworkUsage>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.NetworkUsages.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'NetworkUsage' data! Error: {e.Message}");
                }

                try
                {
                    _logger.Debug($"Dumping PushNotification table '{PushNotification.TableName}'");

                    outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_PushNotifications_Output.csv";

                    outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);

                    var foo = _csvWriter.Configuration.AutoMap <PushNotification>();
                    foo.Map(t => t.Timestamp).ConvertUsing(t =>
                                                           $"{t.Timestamp:yyyy-MM-dd HH:mm:ss}");

                    _csvWriter.Configuration.RegisterClassMap(foo);
                    _csvWriter.WriteHeader <PushNotification>();
                    _csvWriter.NextRecord();

                    _csvWriter.WriteRecords(sr.PushNotifications.Values);

                    _csvWriter.Flush();
                    _swCsv.Flush();
                }
                catch (Exception e)
                {
                    _logger.Error($"Error exporting 'PushNotification' data! Error: {e.Message}");
                }


                sw.Stop();

                _logger.Debug("");

                _logger.Error(
                    $"Processing completed in {sw.Elapsed.TotalSeconds:N4} seconds\r\n");
            }
        }
Пример #2
0
    private static void DoWork(string f, string r, string d, string csv, string dt, bool debug, bool trace)
    {
        var levelSwitch = new LoggingLevelSwitch();

        var template = "{Message:lj}{NewLine}{Exception}";

        if (debug)
        {
            levelSwitch.MinimumLevel = LogEventLevel.Debug;
            template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
        }

        if (trace)
        {
            levelSwitch.MinimumLevel = LogEventLevel.Verbose;
            template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
        }

        var conf = new LoggerConfiguration()
                   .WriteTo.Console(outputTemplate: template)
                   .MinimumLevel.ControlledBy(levelSwitch);

        Log.Logger = conf.CreateLogger();

        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Console.WriteLine();
            Log.Fatal("Non-Windows platforms not supported due to the need to load ESI specific Windows libraries! Exiting...");
            Console.WriteLine();
            Environment.Exit(0);
            return;
        }

        if (f.IsNullOrEmpty() && d.IsNullOrEmpty())
        {
            var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);

            var hc = new HelpContext(helpBld, _rootCommand, Console.Out);

            helpBld.Write(hc);

            Log.Warning("Either -f or -d is required. Exiting\r\n");
            return;
        }


        if (f.IsNullOrEmpty() == false && !File.Exists(f))
        {
            Log.Warning("File '{File}' not found. Exiting", f);
            return;
        }

        if (d.IsNullOrEmpty() == false && !Directory.Exists(d))
        {
            Log.Warning("Directory '{D}' not found. Exiting", d);
            return;
        }

        if (csv.IsNullOrEmpty())
        {
            var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);

            var hc = new HelpContext(helpBld, _rootCommand, Console.Out);

            helpBld.Write(hc);

            Log.Warning("--csv is required. Exiting\r\n");
            return;
        }

        Log.Information("{Header}", Header);
        Console.WriteLine();
        Log.Information("Command line: {Args}\r\n", string.Join(" ", _args));

        if (IsAdministrator() == false)
        {
            Log.Warning("Warning: Administrator privileges not found!\r\n");
        }

        var sw = new Stopwatch();

        sw.Start();

        var ts = DateTimeOffset.UtcNow;

        Srum sr = null;

        if (d.IsNullOrEmpty() == false)
        {
            IEnumerable <string> files2;

#if NET6_0
            var enumerationOptions = new EnumerationOptions
            {
                IgnoreInaccessible    = true,
                MatchCasing           = MatchCasing.CaseInsensitive,
                RecurseSubdirectories = true,
                AttributesToSkip      = 0
            };

            files2 =
                Directory.EnumerateFileSystemEntries(d, "SRUDB.DAT", enumerationOptions);

            f = files2.FirstOrDefault();

            if (f.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SRUDB.dat'! Exiting");
                return;
            }

            Log.Information("Found SRUM database file '{F}'!", f);

            files2 =
                Directory.EnumerateFileSystemEntries(d, "SOFTWARE", enumerationOptions);

            r = files2.FirstOrDefault();

            if (r.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SOFTWARE'! Registry data will not be extracted");
            }
            else
            {
                Log.Information("Found SOFTWARE hive '{R}'!", r);
            }
            #elif NET462
            //kape mode, so find the files
            var ilter = new DirectoryEnumerationFilters();
            ilter.InclusionFilter = fsei =>
            {
                if (fsei.FileSize == 0)
                {
                    return(false);
                }

                if (fsei.FileName.ToUpperInvariant() == "SRUDB.DAT")
                {
                    return(true);
                }

                return(false);
            };

            ilter.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

            ilter.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

            const DirectoryEnumerationOptions dirEnumOptions =
                DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
                DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
                DirectoryEnumerationOptions.BasicSearch;

            files2 =
                Directory.EnumerateFileSystemEntries(d, dirEnumOptions, ilter);

            f = files2.FirstOrDefault();

            if (f.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SRUDB.dat'! Exiting");
                return;
            }

            Log.Information("Found SRUM database file '{F}'!", f);

            ilter = new DirectoryEnumerationFilters();
            ilter.InclusionFilter = fsei =>
            {
                if (fsei.FileSize == 0)
                {
                    return(false);
                }

                if (fsei.FileName.ToUpperInvariant() == "SOFTWARE")
                {
                    return(true);
                }

                return(false);
            };

            ilter.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

            ilter.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

            files2 =
                Directory.EnumerateFileSystemEntries(d, dirEnumOptions, ilter);


            r = files2.FirstOrDefault();

            if (r.IsNullOrEmpty())
            {
                Log.Warning("Did not locate any files named 'SOFTWARE'! Registry data will not be extracted");
            }
            else
            {
                Log.Information("Found SOFTWARE hive '{R}'!", r);
            }
#endif



            Console.WriteLine();
        }

        try
        {
            Log.Information("Processing '{F}'...", f);
            sr = new Srum(f, r);

            Console.WriteLine();
            Log.Information("Processing complete!");
            Console.WriteLine();

            Log.Information("{EnergyUse} {EnergyUsagesCount:N0}", "Energy Usage count:".PadRight(30),
                            sr.EnergyUsages.Count);
            Log.Information("{Unknown312s} {Unknown312sCount:N0}", "Unknown 312 count:".PadRight(30),
                            sr.TimelineProviders.Count);
            Log.Information("{UnknownD8Fs} {UnknownD8FsCount:N0}", "Unknown D8F count:".PadRight(30),
                            sr.Vfuprovs.Count);
            Log.Information("{AppResourceUseInfos} {AppResourceUseInfosCount:N0}",
                            "App Resource Usage count:".PadRight(30), sr.AppResourceUseInfos.Count);
            Log.Information("{NetworkConnections} {NetworkConnectionsCount:N0}",
                            "Network Connection count:".PadRight(30), sr.NetworkConnections.Count);
            Log.Information("{NetworkUsages} {NetworkUsagesCount}", "Network Usage count:".PadRight(30),
                            sr.NetworkUsages.Count);
            Log.Information("{PushNotifications} {PushNotificationsCount:N0}", "Push Notification count:".PadRight(30),
                            sr.PushNotifications.Count);
            Console.WriteLine();
        }
        catch (Exception e)
        {
            Log.Error(e,
                      "Error processing file! Message: {Message}.\r\n\r\nThis almost always means the database is dirty and must be repaired. This can be verified by running 'esentutl.exe /mh SRUDB.dat' and examining the 'State' property",
                      e.Message);
            Console.WriteLine();
            Log.Information(
                "If the database is dirty, **make a copy of your files**, ensure all files in the directory are not Read-only, open a PowerShell session as an admin, and repair by using the following commands (change directories to the location of SRUDB.dat first):\r\n\r\n'esentutl.exe /r sru /i'\r\n'esentutl.exe /p SRUDB.dat'\r\n\r\n");
            Environment.Exit(0);
        }

        if (csv.IsNullOrEmpty() == false)
        {
            if (Directory.Exists(csv) == false)
            {
                Log.Information(
                    "Path to '{Csv}' doesn't exist. Creating...", csv);

                try
                {
                    Directory.CreateDirectory(csv);
                }
                catch (Exception)
                {
                    Log.Fatal(
                        "Unable to create directory '{Csv}'. Does a file with the same name exist? Exiting", csv);
                    return;
                }
            }


            string outName;

            string outFile;

            Log.Information("CSV output will be saved to '{Csv}'\r\n", csv);

            StreamWriter swCsv;
            CsvWriter    csvWriter;
            try
            {
                Log.Debug("Dumping Energy Usage tables '{TableName}'", EnergyUsage.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_EnergyUsage_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <EnergyUsage>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EventTimestamp).Convert(t =>
                                                       $"{t.Value.EventTimestamp?.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <EnergyUsage>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.EnergyUsages.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'EnergyUsage' data! Error: {Message}", e.Message);
            }


            try
            {
                Log.Debug("Dumping Unknown 312 table '{TableName}'", TimelineProvider.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_Unknown312_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <TimelineProvider>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EndTime).Convert(t =>
                                                $"{t.Value.EndTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <TimelineProvider>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.TimelineProviders.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'Unknown312' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Unknown D8F table '{TableName}'", Vfuprov.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_UnknownD8F_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <Vfuprov>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.EndTime).Convert(t =>
                                                $"{t.Value.EndTime.ToString(dt)}");
                foo.Map(t => t.StartTime).Convert(t =>
                                                  $"{t.Value.StartTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <Vfuprov>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.Vfuprovs.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'UnknownD8F' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping App Resource Use Info table '{TableName}'", AppResourceUseInfo.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_AppResourceUseInfo_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <AppResourceUseInfo>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <AppResourceUseInfo>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.AppResourceUseInfos.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'AppResourceUseInfo' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Network Connection table '{TableName}'", NetworkConnection.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkConnections_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <NetworkConnection>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");
                foo.Map(t => t.ConnectStartTime).Convert(t =>
                                                         $"{t.Value.ConnectStartTime.ToString(dt)}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <NetworkConnection>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.NetworkConnections.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'NetworkConnection' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Network Usage table '{TableName}'", NetworkUsage.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_NetworkUsages_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <NetworkUsage>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <NetworkUsage>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.NetworkUsages.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'NetworkUsage' data! Error: {Message}", e.Message);
            }

            try
            {
                Log.Debug("Dumping Push Notification table '{TableName}'", PushNotification.TableName);

                outName = $"{ts:yyyyMMddHHmmss}_SrumECmd_PushNotifications_Output.csv";

                outFile = Path.Combine(csv, outName);

                swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                csvWriter = new CsvWriter(swCsv, CultureInfo.InvariantCulture);

                var foo = csvWriter.Context.AutoMap <PushNotification>();
                foo.Map(t => t.Timestamp).Convert(t =>
                                                  $"{t.Value.Timestamp:yyyy-MM-dd HH:mm:ss}");

                csvWriter.Context.RegisterClassMap(foo);
                csvWriter.WriteHeader <PushNotification>();
                csvWriter.NextRecord();

                csvWriter.WriteRecords(sr.PushNotifications.Values);

                csvWriter.Flush();
                swCsv.Flush();
            }
            catch (Exception e)
            {
                Log.Error(e, "Error exporting 'PushNotification' data! Error: {Message}", e.Message);
            }

            sw.Stop();

            Log.Information("Processing completed in {TotalSeconds:N4} seconds\r\n", sw.Elapsed.TotalSeconds);
        }
    }
Пример #3
0
        public void BuildingAutomation()
        {
            //var r = new Srum(@"D:\OneDrive\HPSpectreSrum\Windows\System32\SRU\SRUDB.dat",@"D:\OneDrive\HPSpectreSrum\Windows\System32\config\SOFTWARE");


            try
            {
                var r = new Srum(@"D:\OneDrive\HPSpectreSrum\2\SRU\SRUDB.dat", @"D:\OneDrive\HPSpectreSrum\2\config\SOFTWARE");
                Console.WriteLine($"r.EnergyUsages {r.EnergyUsages.Count} {EnergyUsage.TableName}");
                Console.WriteLine($"r.Unknown312 {r.Unknown312s.Count} {Unknown312.TableName}");
                Console.WriteLine($"r.UnknownD8Fs {r.UnknownD8Fs.Count} {UnknownD8F.TableName}");
                Console.WriteLine($"r.AppResourceUseInfos {r.AppResourceUseInfos.Count} {AppResourceUseInfo.TableName}");
                Console.WriteLine($"r.NetworkConnections {r.NetworkConnections.Count} {NetworkConnection.TableName}");
                Console.WriteLine($"r.NetworkUsages {r.NetworkUsages.Count} {NetworkUsage.TableName}");
                Console.WriteLine($"r.PushNotifications {r.PushNotifications.Count} {PushNotification.TableName}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // throw;
            }


            var r1 = new Srum(@"D:\OneDrive\HPSpectreSrum\2\SRUclean\SRUDB.dat", @"D:\OneDrive\HPSpectreSrum\2\config\SOFTWARE");

            //     var r = new Srum(@"C:\Temp\tout\c\Windows\System32\SRU\SRUDB.dat",null);


            Console.WriteLine($"r1.EnergyUsages {r1.EnergyUsages.Count} {EnergyUsage.TableName}");
            Console.WriteLine($"r1.Unknown312 {r1.Unknown312s.Count} {Unknown312.TableName}");
            Console.WriteLine($"r1.UnknownD8Fs {r1.UnknownD8Fs.Count} {UnknownD8F.TableName}");

            // foreach (var idMapInfo in r.PushNotifications)
            // {
            //     var user = r.UserMaps[idMapInfo.Value.UserId];
            //     var app = r.AppMaps[idMapInfo.Value.AppId];
            //
            //
            //
            //     Console.WriteLine($"id: {idMapInfo.Value.Id}, Time: {idMapInfo.Value.Timestamp}, User: {user.UserName}, {user.Sid}, {app.ExeInfo} , Payload Size: {idMapInfo.Value.PayloadSize}");
            //
            // }

            // foreach (var idMapInfo in r.NetworkUsages)
            // {
            //     var user = r.UserMaps[idMapInfo.Value.UserId];
            //     var app = r.AppMaps[idMapInfo.Value.AppId];
            //
            //
            //
            //     Console.WriteLine($"id: {idMapInfo.Value.Id}, Time: {idMapInfo.Value.Timestamp}, User: {user.UserName}, {user.Sid}, {app.ExeInfo} , BytesReceived: {idMapInfo.Value.BytesReceived}");
            //
            // }


            // foreach (var idMapInfo in r.EnergyUsages)
            // {
            //     var user = r.UserMaps[idMapInfo.Value.UserId];
            //     var app = r.AppMaps[idMapInfo.Value.AppId];
            //
            //
            //
            //     Console.WriteLine($"id: {idMapInfo.Value.Id}, Time: {idMapInfo.Value.Timestamp}, isLt: {idMapInfo.Value.IsLt} User: {user.UserName}, {user.Sid}, {app.ExeInfo} , FullChargedCapacity: {idMapInfo.Value.FullChargedCapacity} EventTS: {idMapInfo.Value.EventTimestamp}");
            //
            // }

            // foreach (var idMapInfo in r.Unknown312s)
            // {
            //     var user = r.UserMaps[idMapInfo.Value.UserId];
            //     var app = r.AppMaps[idMapInfo.Value.AppId];
            //
            //
            //
            //     Console.WriteLine($"id: {idMapInfo.Value.Id}, Time: {idMapInfo.Value.Timestamp}, User: {user.UserName}, {user.Sid}, EXE: {app.ExeInfo} ,  ET: {idMapInfo.Value.EndTime} Dur: {idMapInfo.Value.DurationMs}");
            //
            // }

            // Srum.DumpTableInfo(@"D:\OneDrive\HPSpectreSrum\Windows\System32\SRU\SRUDB.dat");
        }