public static void FindFiles(string path, string patterns, StyleSheet ss, Dictionary <string, string> color)
        {
            try
            {
                // search every pattern in this directory's files
                foreach (string pattern in patterns.Split(';'))
                {
                    if (Program.using_ansi)
                    {
                        Beaprint.AnsiPrint(String.Join("\n", Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly).Where(filepath => !filepath.Contains(".dll"))), color);
                    }
                    else
                    {
                        Colorful.Console.WriteLineStyled(String.Join("\n", Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly).Where(filepath => !filepath.Contains(".dll"))), ss); // .exe can be contained because of appcmd.exe
                    }
                }

                if (!Program.search_fast)
                {
                    Thread.Sleep(Program.search_time);
                }

                // go recurse in all sub-directories
                foreach (var directory in Directory.GetDirectories(path))
                {
                    FindFiles(directory, patterns, ss, color);
                }
            }
            catch (UnauthorizedAccessException) { }
            catch (PathTooLongException) { }
        }
Esempio n. 2
0
 // From Seatbelt
 public static bool IsVirtualMachine()
 {
     // returns true if the system is likely a virtual machine
     // Adapted from RobSiklos' code from https://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine/11145280#11145280
     try
     {
         using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
         {
             using (var items = searcher.Get())
             {
                 foreach (var item in items)
                 {
                     string manufacturer = item["Manufacturer"].ToString().ToLower();
                     if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) ||
                         manufacturer.Contains("vmware") ||
                         item["Model"].ToString() == "VirtualBox")
                     {
                         return(true);
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
     }
     return(false);
 }
        public static void FindFiles(string path, string patterns, Dictionary <string, string> color)
        {
            try
            {
                // search every pattern in this directory's files
                foreach (string pattern in patterns.Split(';'))
                {
                    Beaprint.AnsiPrint("    " + String.Join("\n    ", Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly).Where(filepath => !filepath.Contains(".dll"))), color);
                }

                if (!Program.search_fast)
                {
                    Thread.Sleep(Program.search_time);
                }

                // go recurse in all sub-directories
                foreach (string directory in Directory.GetDirectories(path))
                {
                    if (!directory.Contains("AppData"))
                    {
                        FindFiles(directory, patterns, color);
                    }
                }
            }
            catch (UnauthorizedAccessException) { }
            catch (PathTooLongException) { }
        }
        public static List <string> GetSAMBackups()
        { //From SharpUP
            List <string> results = new List <string>();

            try
            {
                string   systemRoot      = System.Environment.GetEnvironmentVariable("SystemRoot");
                string[] SearchLocations =
                {
                    String.Format(@"{0}\repair\SAM",                     systemRoot),
                    String.Format(@"{0}\System32\config\RegBack\SAM",    systemRoot),
                    //String.Format(@"{0}\System32\config\SAM", systemRoot),
                    String.Format(@"{0}\repair\SYSTEM",                  systemRoot),
                    //String.Format(@"{0}\System32\config\SYSTEM", systemRoot),
                    String.Format(@"{0}\System32\config\RegBack\SYSTEM", systemRoot),
                };

                foreach (string SearchLocation in SearchLocations)
                {
                    if (System.IO.File.Exists(SearchLocation))
                    {
                        results.Add(SearchLocation);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
        public void ShowResults()
        {
            foreach (Vulnerability vuln in _vulnerabilities.Where(i => i.Vulnerable))
            {
                Beaprint.BadPrint(String.Format("       [!] {0} : VULNERABLE", vuln.Identification));

                foreach (string exploit in vuln.KnownExploits)
                {
                    Beaprint.BadPrint(String.Format("        [>] {0}", exploit));
                }

                System.Console.WriteLine();
            }

            if (_vulnerabilities.Any(e => e.Vulnerable))
            {
                if (Program.using_ansi)
                {
                    System.Console.WriteLine(Beaprint.GRAY + "    Finished. Found " + Beaprint.ansi_color_bad + _vulnerabilities.Count(i => i.Vulnerable) + Beaprint.GRAY + " potential vulnerabilities." + Beaprint.NOCOLOR);
                }
                else
                {
                    string      iniPrint = "    Finished. Found {0} potential vulnerabilities.";
                    Formatter[] colors   = new Formatter[]
                    {
                        new Formatter(_vulnerabilities.Count(i => i.Vulnerable), Beaprint.color_bad),
                    };
                    Colorful.Console.WriteLineFormatted(iniPrint, Color.Gray, colors);
                }
            }
            else
            {
                Beaprint.GrayPrint("      Finished. Found 0 vulnerabilities.\r\n");
            }
        }
        public static string IsDomainJoined()
        {
            // returns Compuer Domain if the system is inside an AD (an nothing if it is not)
            try
            {
                Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus;
                IntPtr pDomain             = IntPtr.Zero;
                int    result = Win32.NetGetJoinInformation(null, out pDomain, out status);
                if (pDomain != IntPtr.Zero)
                {
                    Win32.NetApiBufferFree(pDomain);
                }

                if (result == Win32.ErrorSuccess)
                {
                    // If in domain, return domain name, if not, return empty
                    if (status == Win32.NetJoinStatus.NetSetupDomainName)
                    {
                        return(Environment.UserDomainName);
                    }
                    return("");
                }
            }

            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}\n Trying to check if domain is joined using WMI", ex.Message));
                IsDomainJoinedWmi();
            }
            return("");
        }
Esempio n. 7
0
        //From Seatbelt
        public static Dictionary <string, string> GetPowerShellSettings()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                results["PowerShell v2 Version"]        = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\1\\PowerShellEngine", "PowerShellVersion");
                results["PowerShell v5 Version"]        = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion");
                results["Transcription Settings"]       = "";
                results["Module Logging Settings"]      = "";
                results["Scriptblock Logging Settings"] = "";

                Dictionary <string, object> transcriptionSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription");
                if ((transcriptionSettings == null) || (transcriptionSettings.Count == 0))
                {
                    transcriptionSettings = MyUtils.GetRegValues("HKLM", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription");
                }

                if ((transcriptionSettings != null) && (transcriptionSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in transcriptionSettings)
                    {
                        results["Transcription Settings"] += String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }

                Dictionary <string, object> moduleLoggingSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging");
                if ((moduleLoggingSettings == null) || (moduleLoggingSettings.Count == 0))
                {
                    moduleLoggingSettings = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging");
                }

                if ((moduleLoggingSettings != null) && (moduleLoggingSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in moduleLoggingSettings)
                    {
                        results["Module Logging Settings"] += String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }

                Dictionary <string, object> scriptBlockSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging");
                if ((scriptBlockSettings == null) || (scriptBlockSettings.Count == 0))
                {
                    scriptBlockSettings = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging");
                }

                if ((scriptBlockSettings != null) && (scriptBlockSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in scriptBlockSettings)
                    {
                        results["Scriptblock Logging Settings"] = String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 8
0
        //From Seatbelt
        public static Dictionary <string, string> GetWEFSettings()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                Dictionary <string, object> settings = MyUtils.GetRegValues("HKLM", "Software\\Policies\\Microsoft\\Windows\\EventLog\\EventForwarding\\SubscriptionManager");
                if ((settings != null) && (settings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in settings)
                    {
                        if (kvp.Value.GetType().IsArray&& (kvp.Value.GetType().GetElementType().ToString() == "System.String"))
                        {
                            string result = string.Join(",", (string[])kvp.Value);
                            results.Add(kvp.Key, result);
                        }
                        else
                        {
                            results.Add(kvp.Key, (string)kvp.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 9
0
        //From Seatbelt
        public static List <Dictionary <string, string> > GetDNSCache()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                ManagementObjectSearcher   wmiData = new ManagementObjectSearcher(@"root\standardcimv2", "SELECT * FROM MSFT_DNSClientCache");
                ManagementObjectCollection data    = wmiData.Get();

                foreach (ManagementObject result in data)
                {
                    Dictionary <string, string> dnsEntry = new Dictionary <string, string>();
                    string entry   = String.Format("{0}", result["Entry"]);
                    string name    = String.Format("{0}", result["Name"]);
                    string dataDns = String.Format("{0}", result["Data"]);
                    dnsEntry["Entry"] = (entry.Length > 33) ? "..." + result["Entry"].ToString().Substring(entry.Length - 32) : entry;
                    dnsEntry["Name"]  = (name.Length > 33) ? "..." + name.Substring(name.Length - 32) : name;
                    dnsEntry["Data"]  = (dataDns.Length > 33) ? "..." + dataDns.Substring(dataDns.Length - 32) : dataDns;
                    results.Add(dnsEntry);
                }
            }
            catch (ManagementException ex) when(ex.ErrorCode == ManagementStatus.InvalidNamespace)
            {
                Console.WriteLine("  [X] 'MSFT_DNSClientCache' WMI class unavailable (minimum supported versions of Windows: 8/2012)", ex.Message);
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 10
0
        //From Seatbelt
        public static Dictionary <string, string> GetLapsSettings()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                string AdmPwdEnabled = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdmPwdEnabled");

                if (AdmPwdEnabled != "")
                {
                    results["LAPS Enabled"]                       = AdmPwdEnabled;
                    results["LAPS Admin Account Name"]            = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "AdminAccountName");
                    results["LAPS Password Complexity"]           = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordComplexity");
                    results["LAPS Password Length"]               = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PasswordLength");
                    results["LAPS Expiration Protection Enabled"] = MyUtils.GetRegValue("HKLM", "Software\\Policies\\Microsoft Services\\AdmPwd", "PwdExpirationProtectionEnabled");
                }
                else
                {
                    results["LAPS Enabled"] = "LAPS not installed";
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 11
0
        //////////////////////////////////////
        ////////  PATH DLL Hijacking /////////
        //////////////////////////////////////
        /// Look for write or equivalent permissions on ay folder in PATH
        public static Dictionary <string, string> GetPathDLLHijacking()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                // grabbed from the registry instead of System.Environment.GetEnvironmentVariable to prevent false positives
                string path = MyUtils.GetRegValue("HKLM", "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "Path");
                if (String.IsNullOrEmpty(path))
                {
                    path = Environment.GetEnvironmentVariable("PATH");
                }

                List <string> folders = path.Split(';').ToList();

                foreach (string folder in folders)
                {
                    results[folder] = String.Join(", ", MyUtils.GetPermissionsFolder(folder, Program.currentUserSIDs));
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 12
0
        //////////////////////////////////////////
        ///////  Find Write reg. Services ////////
        //////////////////////////////////////////
        /// Find Services which Reg you have write or equivalent access
        public static List <Dictionary <string, string> > GetWriteServiceRegs(Dictionary <string, string> NtAccountNames)
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"system\currentcontrolset\services");
                foreach (string serviceRegName in regKey.GetSubKeyNames())
                {
                    RegistryKey   key   = Registry.LocalMachine.OpenSubKey(@"system\currentcontrolset\services\" + serviceRegName);
                    List <string> perms = MyUtils.GetMyPermissionsR(key, NtAccountNames);
                    if (perms.Count > 0)
                    {
                        results.Add(new Dictionary <string, string> {
                            { "Path", @"HKLM\system\currentcontrolset\services\" + serviceRegName },
                            { "Permissions", string.Join(", ", perms) }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 13
0
        public static string permInt2Str(int current_perm)
        {
            Dictionary <string, int> interesting_perms = new Dictionary <string, int>()
            {
                { "GenericAll", 268435456 },
                { "FullControl", (int)FileSystemRights.FullControl },
                { "TakeOwnership", (int)FileSystemRights.TakeOwnership },
                { "GenericWrite", 1073741824 },
                { "WriteData/CreateFiles", (int)FileSystemRights.WriteData },
                { "Modify", (int)FileSystemRights.Modify },
                { "Write", (int)FileSystemRights.Write },
                { "ChangePermissions", (int)FileSystemRights.ChangePermissions },
                { "Delete", (int)FileSystemRights.Delete },
                { "DeleteSubdirectoriesAndFiles", (int)FileSystemRights.DeleteSubdirectoriesAndFiles },
                { "AppendData/CreateDirectories", (int)FileSystemRights.AppendData },
                { "WriteAttributes", (int)FileSystemRights.WriteAttributes },
                { "WriteExtendedAttributes", (int)FileSystemRights.WriteExtendedAttributes },
            };

            try
            {
                foreach (KeyValuePair <string, int> entry in interesting_perms)
                {
                    if ((entry.Value & current_perm) == entry.Value)
                    {
                        return(entry.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error in permInt2Str: " + ex);
            }
            return("");
        }
        // https://stackoverflow.com/questions/31464835/how-to-programmatically-check-the-password-must-meet-complexity-requirements-g
        public static List <Dictionary <string, string> > GetPasswordPolicy()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                using (SamServer server = new SamServer(null, SamServer.SERVER_ACCESS_MASK.SAM_SERVER_ENUMERATE_DOMAINS | SamServer.SERVER_ACCESS_MASK.SAM_SERVER_LOOKUP_DOMAIN))
                {
                    foreach (string domain in server.EnumerateDomains())
                    {
                        var sid = server.GetDomainSid(domain);
                        var pi  = server.GetDomainPasswordInformation(sid);

                        results.Add(new Dictionary <string, string>()
                        {
                            { "Domain", domain },
                            { "SID", String.Format("{0}", sid) },
                            { "MaxPasswordAge", String.Format("{0}", pi.MaxPasswordAge) },
                            { "MinPasswordAge", String.Format("{0}", pi.MinPasswordAge) },
                            { "MinPasswordLength", String.Format("{0}", pi.MinPasswordLength) },
                            { "PasswordHistoryLength", String.Format("{0}", pi.PasswordHistoryLength) },
                            { "PasswordProperties", String.Format("{0}", pi.PasswordProperties) },
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex));
            }
            return(results);
        }
        // https://stackoverflow.com/questions/3679579/check-for-groups-a-local-user-is-a-member-of/3681442#3681442
        public static List <string> GetUserGroups(string sUserName, string domain)
        {
            List <string> myItems = new List <string>();

            try
            {
                if (Program.currentUserIsLocal && domain != Program.currentUserDomainName)
                {
                    return(myItems); //If local user and other domain, do not look
                }
                UserPrincipal oUserPrincipal = GetUser(sUserName, domain);
                if (oUserPrincipal != null)
                {
                    PrincipalSearchResult <Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
                    foreach (Principal oResult in oPrincipalSearchResult)
                    {
                        myItems.Add(oResult.Name);
                    }
                }
                else
                {
                    Beaprint.GrayPrint("  [-] Controlled exception, info about " + domain + "\\" + sUserName + " not found");
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(myItems);
        }
Esempio n. 16
0
        //From https://stackoverflow.com/questions/1331887/detect-antivirus-on-windows-using-c-sharp
        public static Dictionary <string, string> GetAVInfo()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();
            string whitelistpaths = "";

            try
            {
                whitelistpaths = String.Join("\n    ", MyUtils.GetRegValues("HKLM", @"SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths").Keys);
                ManagementObjectSearcher   wmiData = new ManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct");
                ManagementObjectCollection data    = wmiData.Get();

                foreach (ManagementObject virusChecker in data)
                {
                    results["Name"]       = (string)virusChecker["displayName"];
                    results["ProductEXE"] = (string)virusChecker["pathToSignedProductExe"];
                    results["pathToSignedReportingExe"] = (string)virusChecker["pathToSignedReportingExe"];
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            if (!String.IsNullOrEmpty(whitelistpaths))
            {
                results["whitelistpaths"] = "    " + whitelistpaths; //Add this info the last
            }
            return(results);
        }
        public static string PermInt2Str(int current_perm, bool only_write_or_equivalent = false, bool is_service = false)
        {
            Dictionary <string, int> interesting_perms = new Dictionary <string, int>()
            {
                // This isn't an exhaustive list of possible permissions. Just the interesting ones.
                { "AllAccess", 0xf01ff },
                { "GenericAll", 0x10000000 },
                { "FullControl", (int)FileSystemRights.FullControl },
                { "TakeOwnership", (int)FileSystemRights.TakeOwnership },
                { "GenericWrite", 0x40000000 },
                { "WriteData/CreateFiles", (int)FileSystemRights.WriteData },
                { "Modify", (int)FileSystemRights.Modify },
                { "Write", (int)FileSystemRights.Write },
                { "ChangePermissions", (int)FileSystemRights.ChangePermissions },
                { "Delete", (int)FileSystemRights.Delete },
                { "DeleteSubdirectoriesAndFiles", (int)FileSystemRights.DeleteSubdirectoriesAndFiles },
                { "AppendData/CreateDirectories", (int)FileSystemRights.AppendData },
                { "WriteAttributes", (int)FileSystemRights.WriteAttributes },
                { "WriteExtendedAttributes", (int)FileSystemRights.WriteExtendedAttributes },
            };

            if (only_write_or_equivalent)
            {
                interesting_perms = new Dictionary <string, int>()
                {
                    { "AllAccess", 0xf01ff },
                    { "GenericAll", 0x10000000 },
                    { "FullControl", (int)FileSystemRights.FullControl },             //0x1f01ff
                    { "TakeOwnership", (int)FileSystemRights.TakeOwnership },         //0x80000
                    { "GenericWrite", 0x40000000 },
                    { "WriteData/CreateFiles", (int)FileSystemRights.WriteData },     //0x2
                    { "Modify", (int)FileSystemRights.Modify },                       //0x301bf
                    { "Write", (int)FileSystemRights.Write },                         //0x116
                    { "ChangePermissions", (int)FileSystemRights.ChangePermissions }, //0x40000
                };
            }

            if (is_service)
            {
                interesting_perms["Start"] = 0x00000010;
                interesting_perms["Stop"]  = 0x00000020;
            }

            try
            {
                foreach (KeyValuePair <string, int> entry in interesting_perms)
                {
                    if ((entry.Value & current_perm) == entry.Value)
                    {
                        return(entry.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error in PermInt2Str: " + ex);
            }
            return("");
        }
        // TODO: check out https://github.com/harleyQu1nn/AggressorScripts/blob/master/ProcessColor.cna#L10
        public static List <Dictionary <string, string> > GetProcessInfo()
        {
            List <Dictionary <string, string> > final_results = new List <Dictionary <string, string> >();

            try
            {
                var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
                using (var searcher = new ManagementObjectSearcher(wmiQueryString))
                    using (var results = searcher.Get())
                    {
                        var query = from p in Process.GetProcesses()
                                    join mo in results.Cast <ManagementObject>()
                                    on p.Id equals(int)(uint) mo["ProcessId"]
                                    select new
                        {
                            Process     = p,
                            Path        = (string)mo["ExecutablePath"],
                            CommandLine = (string)mo["CommandLine"],
                            Owner       = GetProcessUser(p),   //Needed inside the next foreach
                        };

                        foreach (var item in query)
                        {
                            if (item.Path != null)
                            {
                                string companyName = "";
                                string isDotNet    = "";
                                try
                                {
                                    FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(item.Path);
                                    companyName = myFileVersionInfo.CompanyName;
                                    isDotNet    = MyUtils.CheckIfDotNet(item.Path) ? "isDotNet" : "";
                                }
                                catch (Exception ex)
                                {
                                    // Not enough privileges
                                }
                                if ((String.IsNullOrEmpty(companyName)) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
                                {
                                    Dictionary <string, string> toadd = new Dictionary <string, string>();
                                    toadd["Name"]           = item.Process.ProcessName;
                                    toadd["ProcessID"]      = item.Process.Id.ToString();
                                    toadd["ExecutablePath"] = item.Path;
                                    toadd["Product"]        = companyName;
                                    toadd["Owner"]          = item.Owner == null ? "" : item.Owner;
                                    toadd["isDotNet"]       = isDotNet;
                                    toadd["CommandLine"]    = item.CommandLine;
                                    final_results.Add(toadd);
                                }
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(final_results);
        }
        public static List <string> GetMyPermissionsR(RegistryKey key, Dictionary <string, string> SIDs)
        {
            // Get interesting permissions in rSecurity (Only Registry)
            List <string> results = new List <string>();
            Dictionary <string, string> container = new Dictionary <string, string>();

            try
            {
                var rSecurity = key.GetAccessControl();

                //Go through the rules returned from the DirectorySecurity
                foreach (RegistryAccessRule rule in rSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)))
                {
                    int    current_perm     = (int)rule.RegistryRights;
                    string current_perm_str = PermInt2Str(current_perm, true);
                    if (current_perm_str == "")
                    {
                        continue;
                    }

                    foreach (KeyValuePair <string, string> mySID in SIDs)
                    {
                        // If the rule is interesting, check if any of my SIDs is in the rule
                        if (rule.IdentityReference.Value.ToLower() == mySID.Key.ToLower())
                        {
                            string SID_name = String.IsNullOrEmpty(mySID.Value) ? mySID.Key : mySID.Value;

                            if (container.ContainsKey(SID_name))
                            {
                                if (!container[SID_name].Contains(current_perm_str))
                                {
                                    container[SID_name] += " " + current_perm_str;
                                }
                            }
                            else
                            {
                                container[SID_name] = current_perm_str;
                            }

                            string to_add = String.Format("{0} [{1}]", SID_name, current_perm_str);
                        }
                    }
                }
                foreach (KeyValuePair <string, string> SID_input in container)
                {
                    string to_add = String.Format("{0} [{1}]", SID_input.Key, SID_input.Value);
                    results.Add(to_add);
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 20
0
        //From Seatbelt
        public static Dictionary <string, string> GetUACSystemPolicies()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                string ConsentPromptBehaviorAdmin = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "ConsentPromptBehaviorAdmin");
                switch (ConsentPromptBehaviorAdmin)
                {
                case "0":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - No prompting", ConsentPromptBehaviorAdmin);
                    break;

                case "1":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptOnSecureDesktop", ConsentPromptBehaviorAdmin);
                    break;

                case "2":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptPermitDenyOnSecureDesktop", ConsentPromptBehaviorAdmin);
                    break;

                case "3":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptForCredsNotOnSecureDesktop", ConsentPromptBehaviorAdmin);
                    break;

                case "4":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptForPermitDenyNotOnSecureDesktop", ConsentPromptBehaviorAdmin);
                    break;

                case "5":
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptForNonWindowsBinaries", ConsentPromptBehaviorAdmin);
                    break;

                default:
                    results["ConsentPromptBehaviorAdmin"] = String.Format("{0} - PromptForNonWindowsBinaries", ConsentPromptBehaviorAdmin);
                    break;
                }

                string EnableLUA = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "EnableLUA");
                results["EnableLUA"] = EnableLUA;

                string LocalAccountTokenFilterPolicy = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "LocalAccountTokenFilterPolicy");
                results["LocalAccountTokenFilterPolicy"] = LocalAccountTokenFilterPolicy;

                string FilterAdministratorToken = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", "FilterAdministratorToken");
                results["FilterAdministratorToken"] = FilterAdministratorToken;
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
        public static string PermInt2Str(int current_perm, bool only_write_or_equivalent = false)
        {
            Dictionary <string, int> interesting_perms = new Dictionary <string, int>()
            {
                { "AllAccess", 0xf01ff },
                { "GenericAll", 0x10000000 },
                { "FullControl", (int)FileSystemRights.FullControl },
                { "TakeOwnership", (int)FileSystemRights.TakeOwnership },
                { "GenericWrite", 0x40000000 },
                { "WriteData/CreateFiles", (int)FileSystemRights.WriteData },
                { "Modify", (int)FileSystemRights.Modify },
                { "Write", (int)FileSystemRights.Write },
                { "ChangePermissions", (int)FileSystemRights.ChangePermissions },
                { "Delete", (int)FileSystemRights.Delete },
                { "DeleteSubdirectoriesAndFiles", (int)FileSystemRights.DeleteSubdirectoriesAndFiles },
                { "AppendData/CreateDirectories", (int)FileSystemRights.AppendData },
                { "WriteAttributes", (int)FileSystemRights.WriteAttributes },
                { "WriteExtendedAttributes", (int)FileSystemRights.WriteExtendedAttributes },
            };

            if (only_write_or_equivalent)
            {
                interesting_perms = new Dictionary <string, int>()
                {
                    { "AllAccess", 0xf01ff },
                    { "GenericAll", 0x10000000 },
                    { "FullControl", (int)FileSystemRights.FullControl },
                    { "TakeOwnership", (int)FileSystemRights.TakeOwnership },
                    { "GenericWrite", 0x40000000 },
                    { "WriteData/CreateFiles", (int)FileSystemRights.WriteData },
                    { "Modify", (int)FileSystemRights.Modify },
                    { "Write", (int)FileSystemRights.Write },
                    { "ChangePermissions", (int)FileSystemRights.ChangePermissions },
                };
            }

            try
            {
                foreach (KeyValuePair <string, int> entry in interesting_perms)
                {
                    if ((entry.Value & current_perm) == entry.Value)
                    {
                        return(entry.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error in PermInt2Str: " + ex);
            }
            return("");
        }
Esempio n. 22
0
        public static List <Dictionary <string, string> > GetScheduledAppsNoMicrosoft()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                void EnumFolderTasks(TaskFolder fld)
                {
                    foreach (Microsoft.Win32.TaskScheduler.Task task in fld.Tasks)
                    {
                        ActOnTask(task);
                    }
                    //task.Name
                    //task.Enabled
                    //task.Definition.Actions
                    //task.Definition
                    foreach (TaskFolder sfld in fld.SubFolders)
                    {
                        EnumFolderTasks(sfld);
                    }
                }

                void ActOnTask(Microsoft.Win32.TaskScheduler.Task t)
                {
                    if (t.Enabled && (!String.IsNullOrEmpty(t.Definition.RegistrationInfo.Author) && !t.Definition.RegistrationInfo.Author.Contains("Microsoft")))
                    {
                        List <string> f_trigger = new List <string>();
                        foreach (Trigger trigger in t.Definition.Triggers)
                        {
                            f_trigger.Add(String.Format("{0}", trigger));
                        }

                        results.Add(new Dictionary <string, string>()
                        {
                            { "Name", t.Name },
                            { "Action", Environment.ExpandEnvironmentVariables(String.Format("{0}", t.Definition.Actions)) },
                            { "Trigger", String.Join("\n             ", f_trigger) },
                            { "Author", String.Join(", ", t.Definition.RegistrationInfo.Author) },
                            { "Description", String.Join(", ", t.Definition.RegistrationInfo.Description) },
                        });
                    }
                }
                EnumFolderTasks(TaskService.Instance.RootFolder);
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error: " + ex);
            }
            return(results);
        }
Esempio n. 23
0
        ///////////////////////////////////////////////
        //// Non Standard Services (Non Microsoft) ////
        ///////////////////////////////////////////////
        public static List <Dictionary <string, string> > GetNonstandardServices()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                ManagementObjectSearcher   wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT * FROM win32_service");
                ManagementObjectCollection data    = wmiData.Get();

                foreach (ManagementObject result in data)
                {
                    if (result["PathName"] != null)
                    {
                        string binaryPath  = MyUtils.GetExecutableFromPath(result["PathName"].ToString());
                        string companyName = "";
                        string isDotNet    = "";
                        try
                        {
                            FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(binaryPath);
                            companyName = myFileVersionInfo.CompanyName;
                            isDotNet    = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : "";
                        }
                        catch (Exception ex)
                        {
                            // Not enough privileges
                        }

                        if (String.IsNullOrEmpty(companyName) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
                        {
                            Dictionary <string, string> toadd = new Dictionary <string, string>();
                            toadd["Name"]         = String.Format("{0}", result["Name"]);
                            toadd["DisplayName"]  = String.Format("{0}", result["DisplayName"]);
                            toadd["CompanyName"]  = companyName;
                            toadd["State"]        = String.Format("{0}", result["State"]);
                            toadd["StartMode"]    = String.Format("{0}", result["StartMode"]);
                            toadd["PathName"]     = String.Format("{0}", result["PathName"]);
                            toadd["FilteredPath"] = binaryPath;
                            toadd["isDotNet"]     = isDotNet;
                            toadd["Description"]  = String.Format("{0}", result["Description"]);
                            results.Add(toadd);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
        // https://stackoverflow.com/questions/5247798/get-list-of-local-computer-usernames-in-windows
        public static List <string> GetMachineUsers(Boolean onlyActive, Boolean onlyDisabled, Boolean onlyLockout, Boolean onlyAdmins, Boolean fullInfo)
        {
            List <string> retList = new List <string>();

            try
            {
                foreach (ManagementObject user in Program.win32_users)
                {
                    if (onlyActive && !(bool)user["Disabled"] && !(bool)user["Lockout"])
                    {
                        retList.Add((string)user["Name"]);
                    }
                    else if (onlyDisabled && (bool)user["Disabled"] && !(bool)user["Lockout"])
                    {
                        retList.Add((string)user["Name"]);
                    }
                    else if (onlyLockout && (bool)user["Lockout"])
                    {
                        retList.Add((string)user["Name"]);
                    }
                    else if (onlyAdmins)
                    {
                        string domain = (string)user["Domain"];
                        if (string.Join(",", GetUserGroups((string)user["Name"], domain)).Contains("Admin"))
                        {
                            retList.Add((string)user["Name"]);
                        }
                    }
                    else if (fullInfo)
                    {
                        string        domain      = (string)user["Domain"];
                        string        userLine    = user["Caption"] + ((bool)user["Disabled"] ? "(Disabled)" : "") + ((bool)user["Lockout"] ? "(Lockout)" : "") + ((string)user["Fullname"] != "false" ? "" : "(" + user["Fullname"] + ")") + (((string)user["Description"]).Length > 1 ? ": " + user["Description"] : "");
                        List <string> user_groups = GetUserGroups((string)user["Name"], domain);
                        string        groupsLine  = "";
                        if (user_groups.Count > 0)
                        {
                            groupsLine = "\n        |->Groups: " + string.Join(",", user_groups);
                        }
                        string passLine = "\n        |->Password: "******"PasswordChangeable"] ? "CanChange" : "NotChange") + "-" + ((bool)user["PasswordExpires"] ? "Expi" : "NotExpi") + "-" + ((bool)user["PasswordRequired"] ? "Req" : "NotReq") + "\n";
                        retList.Add(userLine + groupsLine + passLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex));
            }
            return(retList);
        }
Esempio n. 25
0
        //////////////////////////////////////
        ///////  Get Autorun Registry ////////
        //////////////////////////////////////
        /// Find Autoru registry where you have write or equivalent access
        public static List <Dictionary <string, string> > GetRegistryAutoRuns(Dictionary <string, string> NtAccountNames)
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                string[] autorunLocations = new string[] {
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
                    "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run",
                    "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunService",
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnceService",
                    "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunService",
                    "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnceService"
                };

                foreach (string autorunLocation in autorunLocations)
                {
                    Dictionary <string, object> settings = MyUtils.GetRegValues("HKLM", autorunLocation);
                    if ((settings != null) && (settings.Count != 0))
                    {
                        foreach (KeyValuePair <string, object> kvp in settings)
                        {
                            RegistryKey key = Registry.LocalMachine.OpenSubKey(autorunLocation);

                            string filepath = Environment.ExpandEnvironmentVariables(String.Format("{0}", kvp.Value));
                            string folder   = System.IO.Path.GetDirectoryName(filepath.Replace("'", "").Replace("\"", ""));
                            results.Add(new Dictionary <string, string>()
                            {
                                { "Reg", "HKLM\\" + autorunLocation },
                                { "Folder", folder },
                                { "File", filepath },
                                { "RegPermissions", string.Join(", ", MyUtils.GetMyPermissionsR(key, NtAccountNames)) },
                                { "interestingFolderRights", String.Join(", ", MyUtils.GetPermissionsFolder(folder, Program.currentUserSIDs)) },
                                { "interestingFileRights", String.Join(", ", MyUtils.GetPermissionsFile(filepath, Program.currentUserSIDs)) },
                                { "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(filepath).ToString() }
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Esempio n. 26
0
        //From Seatbelt
        public static Dictionary <string, string> GetUserEnvVariables()
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            try
            {
                foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                {
                    result[(string)env.Key] = (string)env.Value;
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(result);
        }
Esempio n. 27
0
        public static string GetFirewallProfiles()
        {
            string result = "";

            try
            {
                Type   firewall    = Type.GetTypeFromCLSID(new Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD"));
                Object firewallObj = Activator.CreateInstance(firewall);
                Object types       = firewallObj.GetType().InvokeMember("CurrentProfileTypes", BindingFlags.GetProperty, null, firewallObj, null);
                result = String.Format("{0}", (FirewallProfiles)Int32.Parse(types.ToString()));
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(result);
        }
Esempio n. 28
0
        public static List <string> GetAppsRegistry()
        {
            List <string> retList = new List <string>();

            try
            {
                RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("SOFTWARE");
                foreach (string subKeyName in softwareKey.GetSubKeyNames())
                {
                    retList.Add(subKeyName);
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error: " + ex);
            }
            return(retList);
        }
        public static string GetConsoleHostHistory()
        {
            string result = "";

            try
            {
                string searchLocation = String.Format("{0}\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadline\\ConsoleHost_history.txt", Environment.GetEnvironmentVariable("USERPROFILE"));
                if (System.IO.File.Exists(searchLocation))
                {
                    result = searchLocation;
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error: " + ex);
            }
            return(result);
        }
        public static List <string> ListUsersDocs()
        {
            List <string> results = new List <string>();

            try
            {
                // returns files (w/ modification dates) that match the given pattern below
                string patterns = "*diagram*;*.pdf;*.vsd;*.doc;*docx;*.xls;*.xlsx";

                if (MyUtils.IsHighIntegrity())
                {
                    string searchPath = String.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive"));

                    List <string> files = MyUtils.FindFiles(searchPath, patterns);

                    foreach (string file in files)
                    {
                        DateTime lastAccessed = System.IO.File.GetLastAccessTime(file);
                        DateTime lastModified = System.IO.File.GetLastWriteTime(file);
                        results.Add(file);
                    }
                }

                else
                {
                    string searchPath = Environment.GetEnvironmentVariable("USERPROFILE");

                    List <string> files = MyUtils.FindFiles(searchPath, patterns);

                    foreach (string file in files)
                    {
                        DateTime lastAccessed = System.IO.File.GetLastAccessTime(file);
                        DateTime lastModified = System.IO.File.GetLastWriteTime(file);
                        results.Add(file);
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error: " + ex);
            }
            return(results);
        }