public static void InsertAnalyzed(CompareResult objIn)
 {
     if (objIn != null)
     {
         using (var cmd = new SqliteCommand(SQL_INSERT_FINDINGS_RESULT, MainConnection.Connection, MainConnection.Transaction))
         {
             cmd.Parameters.AddWithValue("@comparison_id", AsaHelpers.RunIdsToCompareId(objIn.BaseRunId, objIn.CompareRunId));
             cmd.Parameters.AddWithValue("@result_type", objIn.ResultType);
             cmd.Parameters.AddWithValue("@level", objIn.Analysis);
             cmd.Parameters.AddWithValue("@identity", objIn.Identity);
             cmd.Parameters.AddWithValue("@serialized", JsonSerializer.Serialize(objIn));
             cmd.ExecuteNonQuery();
         }
     }
 }
 public static string GetOsName()
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         return(AsaHelpers.GetPlatformString());
     }
     else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
     {
         if (ExternalCommandRunner.RunExternalCommand("uname", "-s", out string StdOut, out string _) == 0)
         {
             return(StdOut);
         }
     }
     return("");
 }
예제 #3
0
 public static void Setup(bool test = false)
 {
     if (Client == null)
     {
         using var config          = TelemetryConfiguration.CreateDefault();
         Enabled                   = test ? true : DatabaseManager.GetTelemetryEnabled();
         config.InstrumentationKey = INSTRUMENTATION_KEY;
         config.DisableTelemetry   = !Enabled;
         Client = new TelemetryClient(config);
         Client.Context.Component.Version = AsaHelpers.GetVersionString();
         // Force some values to static values to prevent gathering unneeded data
         Client.Context.Cloud.RoleInstance = "Asa";
         Client.Context.Cloud.RoleName     = "Asa";
         Client.Context.Location.Ip        = "1.1.1.1";
     }
 }
 public static void SetOptOut(bool optOut)
 {
     OptOut                           = optOut;
     using var config                 = TelemetryConfiguration.CreateDefault();
     config.InstrumentationKey        = INSTRUMENTATION_KEY;
     config.DisableTelemetry          = OptOut;
     Client                           = new TelemetryClient(config);
     Client.Context.Component.Version = AsaHelpers.GetVersionString();
     // Force some values to static values to prevent gathering unneeded data
     Client.Context.Cloud.RoleInstance = "Asa";
     Client.Context.Cloud.RoleName     = "Asa";
     Client.Context.Location.Ip        = "1.1.1.1";
     using (var cmd = new SqliteCommand(UPDATE_TELEMETRY, DatabaseManager.Connection, DatabaseManager.Transaction))
     {
         cmd.Parameters.AddWithValue("@TelemetryOptOut", OptOut.ToString(CultureInfo.InvariantCulture));
         cmd.ExecuteNonQuery();
         DatabaseManager.Commit();
     }
 }
예제 #5
0
        public static IEnumerable <RegistryObject> WalkHive(RegistryHive Hive, string startingKey = null)
        {
            Stack <RegistryKey> keys = new Stack <RegistryKey>();

            RegistryKey x86_View = RegistryKey.OpenBaseKey(Hive, RegistryView.Registry32);

            if (startingKey != null)
            {
                x86_View = x86_View.OpenSubKey(startingKey);
            }

            keys.Push(x86_View);

            RegistryKey x64_View = RegistryKey.OpenBaseKey(Hive, RegistryView.Registry64);

            if (startingKey != null)
            {
                x64_View = x64_View.OpenSubKey(startingKey);
            }

            keys.Push(x64_View);

            while (keys.Count > 0)
            {
                RegistryKey currentKey = keys.Pop();

                if (currentKey == null)
                {
                    continue;
                }
                if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "Registry", "Key", currentKey.Name))
                {
                    continue;
                }

                // First push all the new subkeys onto our stack.
                foreach (string key in currentKey.GetSubKeyNames())
                {
                    try
                    {
                        var next = currentKey.OpenSubKey(name: key, writable: false);
                        keys.Push(next);
                    }
                    // These are expected as we are running as administrator, not System.
                    catch (System.Security.SecurityException e)
                    {
                        Log.Verbose(e, "Permission Denied: {0}", currentKey.Name);
                    }
                    // There seem to be some keys which are listed as existing by the APIs but don't actually exist.
                    // Unclear if these are just super transient keys or what the other cause might be.
                    // Since this isn't user actionable, also just supress these to the verbose stream.
                    catch (System.IO.IOException e)
                    {
                        Log.Verbose(e, "Error Reading: {0}", currentKey.Name);
                    }
                    catch (Exception e)
                    {
                        Log.Information(e, "Unexpected error when parsing {0}:", currentKey.Name);
                        AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                    }
                }

                var regObj = RegistryKeyToRegistryObject(currentKey);

                if (regObj != null)
                {
                    yield return(regObj);
                }
            }

            x86_View.Dispose();
            x64_View.Dispose();
        }
예제 #6
0
        public static IEnumerable <string> WalkDirectory(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack <string> dirs = new Stack <string>();
            // Master list of all directories seen, to prevent loops from Hard Links.
            HashSet <string> dirsSet = new HashSet <string>();

            if (System.IO.Directory.Exists(root))
            {
                dirs.Push(root);
                dirsSet.Add(root);
            }

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "File", "Path", currentDir))
                {
                    continue;
                }
                else
                {
                    yield return(currentDir);

                    try
                    {
                        var fileInfo = new DirectoryInfo(currentDir);
                        // Skip symlinks to avoid loops
                        if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            Log.Verbose($"Skipping symlink at {currentDir}");
                            continue;
                        }
                    }
                    catch (Exception e) when(
                        e is UnauthorizedAccessException)
                    {
                    }
                    catch (Exception e)
                    {
                        Log.Debug("Should be catching {0} in DirectoryWalker.", e.GetType().ToString());
                    }
                }

                string[] subDirs;
                try
                {
                    subDirs = Directory.GetDirectories(currentDir);
                }
                catch (Exception e) when(
                    e is ArgumentException ||
                    e is ArgumentNullException ||
                    e is PathTooLongException ||
                    e is IOException ||
                    e is DirectoryNotFoundException ||
                    e is UnauthorizedAccessException)
                {
                    Log.Verbose("Failed to get Directories for {0} {1}", currentDir, e.GetType().ToString());
                    continue;
                }

                string[] files;
                try
                {
                    files = Directory.GetFiles(currentDir);
                }

                catch (Exception e) when(
                    e is UnauthorizedAccessException ||
                    e is IOException ||
                    e is ArgumentException ||
                    e is ArgumentNullException ||
                    e is PathTooLongException ||
                    e is DirectoryNotFoundException)
                {
                    Log.Verbose("Failed to get files for {0} {1}", currentDir, e.GetType().ToString());
                    continue;
                }

                foreach (string file in files)
                {
                    if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "File", "Path", file))
                    {
                        continue;
                    }

                    yield return(file);
                    //FileInfo fileInfo = null;
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string dir in subDirs)
                {
                    try
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(dir);

                        // Skip symlinks to avoid loops
                        // Future improvement: log it as a symlink in the data
                        if (directoryInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            continue;
                        }
                        if (!dirsSet.Contains(dir))
                        {
                            dirs.Push(dir);
                            dirsSet.Add(dir);
                        }
                        else
                        {
                            Log.Verbose("Loop detected. Skipping duplicate directory {0} as a subdirectory of {1}", dir, currentDir);
                        }
                    }
                    catch (Exception e) when(
                        e is SecurityException ||
                        e is ArgumentException ||
                        e is ArgumentException ||
                        e is PathTooLongException ||
                        e is UnauthorizedAccessException ||
                        e is IOException)
                    {
                        Log.Verbose("Failed to create DirectoryInfo from Directory at {0} {1}", dir, e.GetType().ToString());
                        continue;
                    }
                }
            }
        }
예제 #7
0
        public static IEnumerable <RegistryKey> WalkHive(RegistryHive Hive, RegistryView View, string startingKey = "")
        {
            Stack <RegistryKey> keys = new Stack <RegistryKey>();



            RegistryKey?BaseKey = null;

            try
            {
                BaseKey = RegistryKey.OpenBaseKey(Hive, View);
            }
            catch (Exception e) when(
                e is IOException ||
                e is ArgumentException ||
                e is UnauthorizedAccessException ||
                e is System.Security.SecurityException)
            {
            }

            if (BaseKey != null)
            {
                if (startingKey != null)
                {
                    BaseKey = BaseKey.OpenSubKey(startingKey, writable: false);
                }
                keys.Push(BaseKey);
            }

            while (keys.Count > 0)
            {
                RegistryKey currentKey = keys.Pop();

                if (currentKey == null)
                {
                    continue;
                }
                if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "Registry", "Key", currentKey.Name))
                {
                    continue;
                }

                // First push all the new subkeys onto our stack.
                foreach (string key in currentKey.GetSubKeyNames())
                {
                    try
                    {
                        var next = currentKey.OpenSubKey(name: key, writable: false);
                        keys.Push(next);
                    }
                    // These are expected as we are running as administrator, not System.
                    catch (System.Security.SecurityException)
                    {
                        Log.Debug("Permission Denied Opening Subkey: {0}\\{1}", currentKey.Name, key);
                    }
                    // There seem to be some keys which are listed as existing by the APIs but don't actually exist.
                    // Unclear if these are just super transient keys or what the other cause might be.
                    // Since this isn't user actionable, also just supress these to the verbose stream.
                    catch (System.IO.IOException)
                    {
                        Log.Debug("IOError Reading: {0}\\{1}", currentKey.Name, key);
                    }
                    catch (Exception e)
                    {
                        Log.Information(e, "Unexpected error when parsing {0}\\{1}", currentKey.Name, key);
                        AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                    }
                }

                yield return(currentKey);
            }

            BaseKey?.Dispose();
        }
예제 #8
0
        public static IEnumerable <FileSystemInfo> WalkDirectory(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack <string> dirs = new Stack <string>();

            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException("Unable to find [" + root + "]");
            }
            dirs.Push(root);

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "File", "Path", currentDir))
                {
                    continue;
                }

                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable
                // to ignore the exception and continue enumerating the remaining files and
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The
                // choice of which exceptions to catch depends entirely on the specific task
                // you are intending to perform and also on how much you know with certainty
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException)
                {
                    Log.Debug("Unable to access: {0}", currentDir);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException)
                {
                    Log.Debug("Directory not found: {0}", currentDir);
                    continue;
                }
                // @TODO: Improve this catch.
                // This catches a case where we sometimes try to walk a file
                // even though its not a directory on Mac OS.
                // System.IO.Directory.GetDirectories is how we get the
                // directories which sometimes gives you things that aren't directories.
                catch (IOException)
                {
                    Log.Debug("IO Error: {0}", currentDir);
                    continue;
                }

                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(currentDir);
                }

                catch (UnauthorizedAccessException e)
                {
                    Log.Debug(e.Message);
                    continue;
                }

                catch (System.IO.DirectoryNotFoundException e)
                {
                    Log.Debug(e.Message);
                    continue;
                }
                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    FileInfo fileInfo = null;
                    try
                    {
                        fileInfo = new FileInfo(file);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Log.Debug(e.Message);
                        continue;
                    }
                    if (Filter.IsFiltered(AsaHelpers.GetPlatformString(), "Scan", "File", "Path", file))
                    {
                        continue;
                    }
                    yield return(fileInfo);
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                {
                    DirectoryInfo fileInfo = null;
                    try
                    {
                        fileInfo = new DirectoryInfo(str);

                        // Skip symlinks to avoid loops
                        // Future improvement: log it as a symlink in the data
                        if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
                        {
                            continue;
                        }
                    }
                    catch (System.IO.DirectoryNotFoundException)
                    {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        continue;
                    }
                    catch (IOException)
                    {
                        continue;
                    }
                    dirs.Push(str);
                    yield return(fileInfo);
                }
            }
        }