Пример #1
0
        public static void InsertRun(AsaRun run)
        {
            if (run == null)
            {
                return;
            }
            if (MainConnection != null)
            {
                using var cmd = new SqliteCommand(SQL_INSERT_RUN, MainConnection.Connection, MainConnection.Transaction);
                cmd.Parameters.AddWithValue("@run_id", run.RunId);
                cmd.Parameters.AddWithValue("@type", run.Type);
                cmd.Parameters.AddWithValue("@serialized", JsonConvert.SerializeObject(run));

                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (SqliteException e)
                {
                    Log.Warning(e.StackTrace);
                    Log.Warning(e.Message);
                    AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                }
            }
            else
            {
                Log.Debug("Failed to InsertRun because MainConnection is null.");
            }
        }
        public static void InsertRun(string runId, Dictionary <RESULT_TYPE, bool> dictionary)
        {
            if (dictionary == null)
            {
                return;
            }
            string INSERT_RUN = "insert into runs (run_id, file_system, ports, users, services, registry, certificates, firewall, comobjects, eventlogs, type, timestamp, version, platform) values (@run_id, @file_system, @ports, @users, @services, @registry, @certificates, @firewall, @comobjects, @eventlogs, @type, @timestamp, @version, @platform)";

            using var cmd = new SQLiteCommand(INSERT_RUN, Connection, Transaction);
            cmd.Parameters.AddWithValue("@run_id", runId);
            cmd.Parameters.AddWithValue("@file_system", (dictionary.ContainsKey(RESULT_TYPE.FILE) && dictionary[RESULT_TYPE.FILE]) || (dictionary.ContainsKey(RESULT_TYPE.FILEMONITOR) && dictionary[RESULT_TYPE.FILEMONITOR]));
            cmd.Parameters.AddWithValue("@ports", (dictionary.ContainsKey(RESULT_TYPE.PORT) && dictionary[RESULT_TYPE.PORT]));
            cmd.Parameters.AddWithValue("@users", (dictionary.ContainsKey(RESULT_TYPE.USER) && dictionary[RESULT_TYPE.USER]));
            cmd.Parameters.AddWithValue("@services", (dictionary.ContainsKey(RESULT_TYPE.SERVICE) && dictionary[RESULT_TYPE.SERVICE]));
            cmd.Parameters.AddWithValue("@registry", (dictionary.ContainsKey(RESULT_TYPE.REGISTRY) && dictionary[RESULT_TYPE.REGISTRY]));
            cmd.Parameters.AddWithValue("@certificates", (dictionary.ContainsKey(RESULT_TYPE.CERTIFICATE) && dictionary[RESULT_TYPE.CERTIFICATE]));
            cmd.Parameters.AddWithValue("@firewall", (dictionary.ContainsKey(RESULT_TYPE.FIREWALL) && dictionary[RESULT_TYPE.FIREWALL]));
            cmd.Parameters.AddWithValue("@comobjects", (dictionary.ContainsKey(RESULT_TYPE.COM) && dictionary[RESULT_TYPE.COM]));
            cmd.Parameters.AddWithValue("@eventlogs", (dictionary.ContainsKey(RESULT_TYPE.LOG) && dictionary[RESULT_TYPE.LOG]));
            cmd.Parameters.AddWithValue("@type", (dictionary.ContainsKey(RESULT_TYPE.FILEMONITOR) && dictionary[RESULT_TYPE.FILEMONITOR]) ? "monitor" : "collect");
            cmd.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
            cmd.Parameters.AddWithValue("@version", AsaHelpers.GetVersionString());
            cmd.Parameters.AddWithValue("@platform", AsaHelpers.GetPlatformString());
            try
            {
                cmd.ExecuteNonQuery();
                Commit();
            }
            catch (SQLiteException e)
            {
                Log.Warning(e.StackTrace);
                Log.Warning(e.Message);
                AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
            }
        }
Пример #3
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();
        }
Пример #4
0
        /// <summary>
        /// This method distills the output from netstat -a -n -o into a list of ProcessPorts that provide a mapping between
        /// the process (name and id) and the ports that the process is using.
        /// </summary>
        /// <returns></returns>
        private static List <ProcessPort> GetNetStatPorts()
        {
            List <ProcessPort> ProcessPorts = new List <ProcessPort>();

            try
            {
                using (Process Proc = new Process())
                {
                    ProcessStartInfo StartInfo = new ProcessStartInfo()
                    {
                        FileName               = "netstat.exe",
                        Arguments              = "-a -n -o",
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        UseShellExecute        = false,
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true
                    };

                    Proc.StartInfo = StartInfo;
                    Proc.Start();

                    StreamReader StandardOutput = Proc.StandardOutput;
                    StreamReader StandardError  = Proc.StandardError;

                    string NetStatContent = StandardOutput.ReadToEnd() + StandardError.ReadToEnd();

                    if (Proc.ExitCode != 0)
                    {
                        Log.Error("Unable to run netstat.exe. Open ports will not be available.");
                        return(ProcessPorts);
                    }

                    string[] NetStatRows = Regex.Split(NetStatContent, "\r\n");

                    foreach (var _outputLine in NetStatRows)
                    {
                        if (_outputLine == null)
                        {
                            continue;
                        }

                        var outputLine = _outputLine.Trim();

                        string[] Tokens = Regex.Split(outputLine, @"\s+");
                        try
                        {
                            if (Tokens.Length < 4)
                            {
                                continue;
                            }
                            string IpAddress = Regex.Replace(Tokens[1], @"\[(.*?)\]", "1.1.1.1");

                            if (Tokens.Length > 4 && Tokens[0].Equals("TCP"))
                            {
                                if (!Tokens[3].Equals("LISTENING"))
                                {
                                    continue;
                                }
                                ProcessPorts.Add(new ProcessPort(
                                                     GetProcessName(Convert.ToInt32(Tokens[4], CultureInfo.InvariantCulture)),
                                                     Convert.ToInt32(Tokens[4], CultureInfo.InvariantCulture),
                                                     IpAddress.Contains("1.1.1.1") ? $"{Tokens[1]}v6" : $"{Tokens[1]}v4",
                                                     Convert.ToInt32(IpAddress.Split(':')[1], CultureInfo.InvariantCulture)
                                                     ));
                            }
                            else if (Tokens.Length == 4 && (Tokens[0].Equals("UDP")))
                            {
                                ProcessPorts.Add(new ProcessPort(
                                                     GetProcessName(Convert.ToInt32(Tokens[3], CultureInfo.InvariantCulture)),
                                                     Convert.ToInt32(Tokens[3], CultureInfo.InvariantCulture),
                                                     IpAddress.Contains("1.1.1.1") ? $"{Tokens[1]}v6" : $"{Tokens[1]}v4",
                                                     Convert.ToInt32(IpAddress.Split(':')[1], CultureInfo.InvariantCulture)
                                                     ));
                            }
                            else
                            {
                                if (!outputLine.StartsWith("Proto") && !outputLine.StartsWith("Active") && !String.IsNullOrWhiteSpace(outputLine))
                                {
                                    Log.Warning("Primary Parsing error when processing netstat.exe output: {0}", outputLine);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warning("Secondary Parsing error when processing netstat.exe output: {0}", outputLine);
                            AsaTelemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Error processing open ports: {0}", ex.Message);
            }
            return(ProcessPorts);
        }
Пример #5
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)
            {
                Log.Debug($"Failed to open Hive {Hive} for walking.");
            }

            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;
                }

                // 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);
                    }
                    // TODO: Capture that these keys exist but we couldn't access them in the results
                    // 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();
        }