Ejemplo n.º 1
0
 public static string[] GetRegSubkeys(string hive, string path)
 {
     // returns an array of the subkeys names under the specified path in the specified hive (HKLM/HKCU/HKU)
     try
     {
         Microsoft.Win32.RegistryKey myKey = null;
         if (hive == "HKLM")
         {
             myKey = Registry.LocalMachine.OpenSubKey(path);
         }
         else if (hive == "HKU")
         {
             myKey = Registry.Users.OpenSubKey(path);
         }
         else
         {
             myKey = Registry.CurrentUser.OpenSubKey(path);
         }
         String[] subkeyNames = myKey.GetSubKeyNames();
         return(myKey.GetSubKeyNames());
     }
     catch (Exception)
     {
         PrintUtils.Debug(String.Format(@"Registry {0}\{1} was not found", hive, path));
         return(new string[0]);
     }
 }
Ejemplo n.º 2
0
        public static Dictionary <string, string> GetPasswordComplexityPolicy()
        {
            /*
             * public uint usrmod0_min_passwd_len;
             * public uint usrmod0_max_passwd_age;
             * public uint usrmod0_min_passwd_age;
             * public uint usrmod0_force_logoff;
             * public uint usrmod0_password_hist_len;
             */
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                USER_MODALS_INFO_0 objUserModalsInfo0 = new USER_MODALS_INFO_0();
                IntPtr             bufPtr;
                uint lngReturn = NetUserModalsGet(@"\\" + Environment.MachineName, 0, out bufPtr);
                if (lngReturn == 0)
                {
                    objUserModalsInfo0 = (USER_MODALS_INFO_0)Marshal.PtrToStructure(bufPtr, typeof(USER_MODALS_INFO_0));
                }
                results.Add("Minimum Password Length", objUserModalsInfo0.usrmod0_min_passwd_len.ToString());
                results.Add("Max Password Age", objUserModalsInfo0.usrmod0_max_passwd_age.ToString());
                results.Add("Min Password Age", objUserModalsInfo0.usrmod0_min_passwd_age.ToString());
                results.Add("Force Logoff", objUserModalsInfo0.usrmod0_force_logoff.ToString());
                results.Add("Password History Length", objUserModalsInfo0.usrmod0_password_hist_len.ToString());

                //NetApiBufferFree(bufPtr);
                bufPtr = IntPtr.Zero;
            }
            catch (Exception ex)
            {
                PrintUtils.Debug(ex.StackTrace);
            }
            return(results);
        }
Ejemplo n.º 3
0
        public static Dictionary <string, string> GetLockoutPolicy()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                USER_MODALS_INFO_3 objUserModalsInfo3 = new USER_MODALS_INFO_3();
                IntPtr             bufPtr;
                uint lngReturn = NetUserModalsGet(@"\\" + Environment.MachineName, 3, out bufPtr);
                if (lngReturn == 0)
                {
                    objUserModalsInfo3 = (USER_MODALS_INFO_3)Marshal.PtrToStructure(bufPtr, typeof(USER_MODALS_INFO_3));
                }
                results.Add("Lockout duration", String.Format("{0}", objUserModalsInfo3.usrmod3_lockout_duration));
                results.Add("Lockout Obversation Window", String.Format("{0}", objUserModalsInfo3.usrmod3_lockout_observation_window));
                results.Add("Lockout Threshold", String.Format("{0}", objUserModalsInfo3.usrmod3_lockout_threshold));
                //NetApiBufferFree(bufPtr);
                bufPtr = IntPtr.Zero;
            }
            catch (Exception ex)
            {
                PrintUtils.Debug(ex.StackTrace);
            }
            return(results);
        }
Ejemplo n.º 4
0
        public static bool 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(true);
                    }
                    return(false);
                }
            }

            catch (Exception ex)
            {
                PrintUtils.Debug(ex.StackTrace);
                IsDomainJoinedWmi();
            }
            return(false);
        }
Ejemplo n.º 5
0
        /// From winpeas
        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)
            {
                PrintUtils.TestError("Error in PermInt2Str: " + ex);
            }
            return("");
        }
Ejemplo n.º 6
0
        public AttackCTI(string Url)
        {
            CTIRoot AllAttack;
            string  json;

            if (String.IsNullOrEmpty(Program.Arguments.AttackPath))
            {
                using (var w = new WebClient())
                {
                    try
                    {
                        // Need to find a way to switch to MITRE TAXII server instead of the json file
                        PrintUtils.Warning("Pulling latest ATT&CK matrix data from github.com/mitre/cti");
                        json = w.DownloadString(Url);
                    }
                    catch
                    {
                        throw new Exception("Unable to obtain latest Mitre Att&CK information. Please ensure that the device is connected to the internet. Consider using the -AttackPath flag to point to the file on disk");
                    }
                }
            }
            else
            {
                try
                {
                    PrintUtils.Warning($"Pulling latest ATT&CK matrix data from {Program.Arguments.AttackPath}");
                    json = File.ReadAllText(Program.Arguments.AttackPath);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Unable to read {Program.Arguments.AttackPath} due to: {ex.Message}");
                }
            }

            try
            {
                var JSON = new JavaScriptSerializer();
                JSON.MaxJsonLength = int.MaxValue;
                AllAttack          = JSON.Deserialize <CTIRoot>(json);
            }
            catch (Exception ex)
            {
                throw new Exception("ATT&CK Json deserialiazation failed");
            }

            Technique[] items = AllAttack.objects;
            // Filtering all techniques
            var AllTechniques = items.Where(o => o.type == "attack-pattern" && o.revoked == false);

            // Getting all win techniques
            WindowsTechniques = AllTechniques.Where(o => o.x_mitre_platforms.Contains("Windows"));
            // Getting all windows mitigations
            MitigationRelationships = items.Where(o => o.type == "relationship" && o.relationship_type == "mitigates");
            Mitigations             = items.Where(o => o.type == "course-of-action");
            AllAttack = null;
            items     = null;
        }
Ejemplo n.º 7
0
        public static Dictionary <string, bool> GetBITSConfigInfo()
        {
            Dictionary <string, bool> info = new Dictionary <string, bool>();
            var regKeys = GetBITSJobLifetime();

            info["Job Inactivity Timeout < 90 days"]  = false;
            info["Max Download Time < 54000 seconds"] = false;
            if (string.IsNullOrEmpty(regKeys["JobInactivityTimeout"]))
            {
                info["Job Inactivity Timeout < 90 days"] = false;
            }
            else
            {
                try
                {
                    int timeout = int.Parse(regKeys["JobInactivityTimeout"]);
                    if (timeout < 90)
                    {
                        info["Job Inactivity Timeout < 90 days"] = true;
                    }
                }
                catch (Exception ex)
                {
                    PrintUtils.Debug(ex.StackTrace);
                }
            }
            if (regKeys["MaxDownloadTime"] == null)
            {
                info["Max Download Time < 54000 seconds"] = false;
            }
            else
            {
                try
                {
                    int timeout = int.Parse(regKeys["MaxDownloadTime"]);
                    if (timeout < 54000)
                    {
                        info["Max Download Time < 54000 seconds"] = true;
                    }
                }
                catch (Exception ex)
                {
                    PrintUtils.Debug(ex.StackTrace);
                }
            }
            return(info);
        }
Ejemplo n.º 8
0
        public static string GetFirewallProfiles()
        {
            string result = "";

            try
            {
                Type          tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
                INetFwPolicy2 fwPolicy2     = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
                var           types         = fwPolicy2.CurrentProfileTypes.ToString();
                result = String.Format("{0}", (FirewallProfiles)Int32.Parse(types.ToString()));
            }
            catch (Exception ex)
            {
                PrintUtils.TestError(ex.Message);
            }
            return(result);
        }
Ejemplo n.º 9
0
 public static bool IsDomainJoinedWmi()
 {
     try
     {
         ManagementObject ComputerSystem;
         using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)))
         {
             ComputerSystem.Get();
             object Result = ComputerSystem["PartOfDomain"];
             return(Result != null && (bool)Result);
         }
     }
     catch (Exception ex)
     {
         PrintUtils.Debug(ex.StackTrace);
     }
     //By default local
     return(false);
 }
Ejemplo n.º 10
0
        public static bool CheckForRestrictions(string ExecPath, string UserName)
        {
            if (String.IsNullOrEmpty(ExecPath))
            {
                throw new ArgumentNullException();
            }
            if (String.IsNullOrEmpty(UserName))
            {
                throw new ArgumentNullException();
            }

            if (!File.Exists(ExecPath))
            {
                PrintUtils.Debug($"File '{ExecPath}' was not found");
                return(true);
            }
            // Check 1: AppLocker
            if (SystemUtils.IsAppLockerEnabled())
            {
                if (!SystemUtils.IsAppLockerRunning())
                {
                    throw new Exception("AppLocker SVC is not running");
                }
                if (CheckApplockerPolicyforDenied(ExecPath, UserName))
                {
                    return(true);
                }
            }
            // Check 2: SRP
            // TODO

            // Check 3: WDAG
            // TODO

            return(false);
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            /////////////////////
            /// Initial setup ///
            /////////////////////
            PrintUtils.DisableConsoleQuickEdit();
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            // Arg Parsing
            try
            {
                Arguments = new MitigateArgumentParser(args);
            }
            catch (Exception ex)
            {
                PrintUtils.Error(ex.Message);
                MitigateArgumentParser.PrintUsage();
                Environment.Exit(1);
            }

            PrintUtils.PrintBanner();
            PrintUtils.PrintInit(version);
            PrintUtils.PrintLegend();
            IsDomainJoined = SystemUtils.IsDomainJoined();

            // Check if it's running as admin
            if (!UserUtils.IsItRunningAsAdmin())
            {
                PrintUtils.Warning("Mitigate is not running as an administrator." +
                                   " This might restrict its ability to perform the necessary checks");
            }
            AttackCTI ATTCK     = null;
            Navigator navigator = null;

            // Pulling ATT&CK json from GitHub
            try
            {
                ATTCK     = new AttackCTI(AttackUrl);
                navigator = new Navigator();
            }
            catch (Exception ex)
            {
                PrintUtils.Error(ex.Message);
                Environment.Exit(1);
            }
            // Getting some user info and deciding the user for least priv checks
            PrintUtils.Warning("Collecting some machine information. This might take some time...");
            if (!string.IsNullOrEmpty(Arguments.Username))
            {
                try
                {
                    UserToCheck = UserUtils.GetUser(Arguments.Username);
                    SIDsToCheck = UserUtils.GetGroups(UserToCheck);
                }
                catch (Exception ex)
                {
                    PrintUtils.Error(ex.Message);
                    Environment.Exit(1);
                }
            }
            else
            {
                try
                {
                    UserToCheck = UserUtils.GetLastLoggedInUser();
                    SIDsToCheck = UserUtils.GetGroups(UserToCheck);
                }
                catch (Exception ex)
                {
                    PrintUtils.Error(ex.Message);
                    Environment.Exit(1);
                }
            }
            PrintUtils.Warning($"Least privilege checks will be performed for user {UserToCheck.SamAccountName}");
            /////////////////
            /// Main Loop ///
            /////////////////

            // Keeping track on tested techniques to stop from testing twice
            HashSet <string> TestedTechniques = new HashSet <string>();

            // For all tactics
            foreach (string tactic in ATTCK.GetAllTactics())
            {
                PrintUtils.PrintTactic(tactic);
                // For all techniques
                foreach (Technique technique in ATTCK.GetRootTechniquesByTactic(tactic))
                {
                    // Check if the technique has been already tested
                    if (TestedTechniques.Contains(technique.GetID()))
                    {
                        // If it has:
                        continue;
                    }
                    TestedTechniques.Add(technique.GetID());
                    var subtechniques = ATTCK.GetSubTechniquesByTechnique(technique);
                    // Does it have subtechniques?
                    if (subtechniques.Count() > 0)
                    {
                        // Subtechniques found. Handle them
                        Tests.Execute(technique, subtechniques, navigator, ATTCK);
                    }
                    else
                    {
                        // No subtechniques. Just handle root technique
                        Tests.Execute(technique, navigator, ATTCK);
                    }
                }
            }

            // Exporting the file for the navigator
            navigator.ToJSON(Arguments.OutFile);
            if (Arguments.ExportCoverage)
            {
                navigator.ExportCoverage("Coverage.json");
            }
        }