/// <summary>
 /// Send the specified local public key to the remote end.
 /// </summary>
 /// <param name="localPublicKey">Local public key as a string.</param>
 internal override void SendPublicKeyAsync(string localPublicKey)
 {
     _transportManager.DataToBeSentCollection.Add <object>(
         RemotingEncoder.GenerateMyPublicKey(_session.RemoteRunspacePoolInternal.InstanceId,
                                             localPublicKey, RemotingDestination.Server));
 }
Esempio n. 2
0
 internal void SendSetMaxRunspacesToServer(int maxRunspaces, long callId)
 {
     using (ClientRunspacePoolDataStructureHandler.tracer.TraceMethod())
         this.SendDataAsync(RemotingEncoder.GenerateSetMaxRunspaces(this.clientRunspacePoolId, maxRunspaces, callId));
 }
 internal void SendGetAvailableRunspacesToServer(long callId)
 {
     this.SendDataAsync(RemotingEncoder.GenerateGetAvailableRunspaces(this.clientRunspacePoolId, callId));
 }
        internal void SendSetMinRunspacesToServer(int minRunspaces, long callId)
        {
            RemoteDataObject data = RemotingEncoder.GenerateSetMinRunspaces(this.clientRunspacePoolId, minRunspaces, callId);

            this.SendDataAsync(data);
        }
 /// <summary>
 /// Send request to the client for sending a public key
 /// </summary>
 internal override void SendRequestForPublicKey()
 {
     _transportManager.SendDataToClient <object>(
         RemotingEncoder.GeneratePublicKeyRequest(Guid.Empty), true);
 }
 private void HandleClientRemoteSessionStateChanged(object sender, RemoteSessionStateEventArgs e)
 {
     if (e.SessionStateInfo.State == RemoteSessionState.NegotiationSending)
     {
         if (this.createRunspaceCalled)
         {
             return;
         }
         lock (this.syncObject)
         {
             if (this.createRunspaceCalled)
             {
                 return;
             }
             this.createRunspaceCalled = true;
         }
         PSPrimitiveDictionary applicationArguments = PSPrimitiveDictionary.CloneAndAddPSVersionTable(this.applicationArguments);
         var createPoolData = RemotingEncoder.GenerateCreateRunspacePool(this.clientRunspacePoolId, this.minRunspaces, this.maxRunspaces, this.remoteSession.RemoteRunspacePoolInternal, this.host, applicationArguments);
         this.SendDataAsync(createPoolData);
     }
     if (e.SessionStateInfo.State == RemoteSessionState.NegotiationSendingOnConnect)
     {
         this.SendDataAsync(RemotingEncoder.GenerateConnectRunspacePool(this.clientRunspacePoolId, this.minRunspaces, this.maxRunspaces));
     }
     else if (e.SessionStateInfo.State == RemoteSessionState.ClosingConnection)
     {
         List <ClientPowerShellDataStructureHandler> list;
         Exception closingReason = this.closingReason;
         if (closingReason == null)
         {
             closingReason      = e.SessionStateInfo.Reason;
             this.closingReason = closingReason;
         }
         lock (this.associationSyncObject)
         {
             list = new List <ClientPowerShellDataStructureHandler>(this.associatedPowerShellDSHandlers.Values);
         }
         foreach (ClientPowerShellDataStructureHandler handler in list)
         {
             handler.CloseConnectionAsync(this.closingReason);
         }
         this.SessionClosing.SafeInvoke <RemoteDataEventArgs <Exception> >(this, new RemoteDataEventArgs <Exception>(closingReason));
     }
     else if (e.SessionStateInfo.State == RemoteSessionState.Closed)
     {
         Exception reason = this.closingReason;
         if (reason == null)
         {
             reason             = e.SessionStateInfo.Reason;
             this.closingReason = reason;
         }
         if (reason != null)
         {
             this.NotifyAssociatedPowerShells(new RunspacePoolStateInfo(RunspacePoolState.Broken, reason));
         }
         else
         {
             this.NotifyAssociatedPowerShells(new RunspacePoolStateInfo(RunspacePoolState.Closed, reason));
         }
         this.SessionClosed.SafeInvoke <RemoteDataEventArgs <Exception> >(this, new RemoteDataEventArgs <Exception>(reason));
     }
     else if (e.SessionStateInfo.State == RemoteSessionState.Connected)
     {
         PSEtwLog.ReplaceActivityIdForCurrentThread(this.clientRunspacePoolId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Runspace, PSTask.CreateRunspace);
     }
     else if (e.SessionStateInfo.State == RemoteSessionState.Disconnected)
     {
         this.NotifyAssociatedPowerShells(new RunspacePoolStateInfo(RunspacePoolState.Disconnected, e.SessionStateInfo.Reason));
         this.SessionDisconnected.SafeInvoke <RemoteDataEventArgs <Exception> >(this, new RemoteDataEventArgs <Exception>(e.SessionStateInfo.Reason));
     }
     else if (this._reconnecting && (e.SessionStateInfo.State == RemoteSessionState.Established))
     {
         this.SessionReconnected.SafeInvoke <RemoteDataEventArgs <Exception> >(this, new RemoteDataEventArgs <Exception>(null));
         this._reconnecting = false;
     }
     else if (e.SessionStateInfo.State == RemoteSessionState.RCDisconnecting)
     {
         this.SessionRCDisconnecting.SafeInvoke <RemoteDataEventArgs <Exception> >(this, new RemoteDataEventArgs <Exception>(null));
     }
     else if (e.SessionStateInfo.Reason != null)
     {
         this.closingReason = e.SessionStateInfo.Reason;
     }
 }
 /// <summary>
 /// Send the encrypted session key to the client side
 /// </summary>
 /// <param name="encryptedSessionKey">encrypted session key
 /// as a string</param>
 internal override void SendEncryptedSessionKey(string encryptedSessionKey)
 {
     _transportManager.SendDataToClient <object>(RemotingEncoder.GenerateEncryptedSessionKeyResponse(
                                                     Guid.Empty, encryptedSessionKey), true);
 }
Esempio n. 8
0
        /// <summary>
        /// Returns this object as a PSObject property bag
        /// that can be used in a remoting protocol data object.
        /// </summary>
        /// <param name="psRPVersion">PowerShell remoting protocol version.</param>
        /// <returns>This object as a PSObject property bag.</returns>
        internal PSObject ToPSObjectForRemoting(Version psRPVersion)
        {
            PSObject commandAsPSObject = RemotingEncoder.CreateEmptyPSObject();

            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CommandText, this.CommandText));
            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.IsScript, this.IsScript));
            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.UseLocalScopeNullable, this.UseLocalScopeNullable));

            // For V2 backwards compatibility.
            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeMyResult, this.MergeMyResult));
            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeToResult, this.MergeToResult));

            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeUnclaimedPreviousCommandResults, this.MergeUnclaimedPreviousCommandResults));

            if (psRPVersion != null &&
                psRPVersion >= RemotingConstants.ProtocolVersionWin10RTM)
            {
                // V5 merge instructions
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeError, MergeInstructions[(int)MergeType.Error]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeWarning, MergeInstructions[(int)MergeType.Warning]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeVerbose, MergeInstructions[(int)MergeType.Verbose]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeDebug, MergeInstructions[(int)MergeType.Debug]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeInformation, MergeInstructions[(int)MergeType.Information]));
            }
            else if (psRPVersion != null &&
                     psRPVersion >= RemotingConstants.ProtocolVersionWin8RTM)
            {
                // V3 merge instructions.
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeError, MergeInstructions[(int)MergeType.Error]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeWarning, MergeInstructions[(int)MergeType.Warning]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeVerbose, MergeInstructions[(int)MergeType.Verbose]));
                commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeDebug, MergeInstructions[(int)MergeType.Debug]));

                // If they've explicitly redirected the Information stream, generate an error. Don't
                // generate an error if they've done "*", as that makes any new stream a breaking change.
                if ((MergeInstructions[(int)MergeType.Information] == PipelineResultTypes.Output) &&
                    (MergeInstructions.Length != MaxMergeType))
                {
                    throw new RuntimeException(
                              StringUtil.Format(RunspaceStrings.InformationRedirectionNotSupported));
                }
            }
            else
            {
                // If they've explicitly redirected an unsupported stream, generate an error. Don't
                // generate an error if they've done "*", as that makes any new stream a breaking change.
                if (MergeInstructions.Length != MaxMergeType)
                {
                    if (MergeInstructions[(int)MergeType.Warning] == PipelineResultTypes.Output)
                    {
                        throw new RuntimeException(
                                  StringUtil.Format(RunspaceStrings.WarningRedirectionNotSupported));
                    }

                    if (MergeInstructions[(int)MergeType.Verbose] == PipelineResultTypes.Output)
                    {
                        throw new RuntimeException(
                                  StringUtil.Format(RunspaceStrings.VerboseRedirectionNotSupported));
                    }

                    if (MergeInstructions[(int)MergeType.Debug] == PipelineResultTypes.Output)
                    {
                        throw new RuntimeException(
                                  StringUtil.Format(RunspaceStrings.DebugRedirectionNotSupported));
                    }

                    if (MergeInstructions[(int)MergeType.Information] == PipelineResultTypes.Output)
                    {
                        throw new RuntimeException(
                                  StringUtil.Format(RunspaceStrings.InformationRedirectionNotSupported));
                    }
                }
            }

            List <PSObject> parametersAsListOfPSObjects = new List <PSObject>(this.Parameters.Count);

            foreach (CommandParameter parameter in this.Parameters)
            {
                parametersAsListOfPSObjects.Add(parameter.ToPSObjectForRemoting());
            }

            commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.Parameters, parametersAsListOfPSObjects));

            return(commandAsPSObject);
        }
Esempio n. 9
0
        protected BaseClientCommandTransportManager(
            ClientRemotePowerShell shell,
            PSRemotingCryptoHelper cryptoHelper,
            BaseClientSessionTransportManager sessnTM)
            : base(sessnTM.RunspacePoolInstanceId, cryptoHelper)
        {
            this.Fragmentor.FragmentSize = sessnTM.Fragmentor.FragmentSize;
            this.Fragmentor.TypeTable    = sessnTM.Fragmentor.TypeTable;
            this.dataToBeSent.Fragmentor = this.Fragmentor;
            this.powershellInstanceId    = shell.PowerShell.InstanceId;
            this.cmdText = new StringBuilder();
            foreach (Command command in (Collection <Command>)shell.PowerShell.Commands.Commands)
            {
                this.cmdText.Append(command.CommandText);
                this.cmdText.Append(" | ");
            }
            this.cmdText.Remove(this.cmdText.Length - 3, 3);
            RemoteDataObject remoteDataObject = !shell.PowerShell.IsGetCommandMetadataSpecialPipeline ? RemotingEncoder.GenerateCreatePowerShell(shell) : RemotingEncoder.GenerateGetCommandMetadata(shell);

            this.serializedPipeline = new SerializedDataStream(this.Fragmentor.FragmentSize);
            this.Fragmentor.Fragment <object>((RemoteDataObject <object>)remoteDataObject, this.serializedPipeline);
        }
Esempio n. 10
0
        public override PSObject ToPSObjectForRemoting()
        {
            var obj = RemotingEncoder.CreateEmptyPSObject();

            return(obj);
        }
Esempio n. 11
0
        internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData)
        {
            RemoteSessionCapability sessionCapability;

            connectResponseData = null;
            Fragmentor fragmentor   = new Fragmentor(0x7fffffff, null);
            Fragmentor defragmentor = fragmentor;
            int        length       = connectData.Length;

            if (length < 0x15)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            FragmentedRemoteObject.GetFragmentId(connectData, 0);
            bool isStartFragment = FragmentedRemoteObject.GetIsStartFragment(connectData, 0);
            bool isEndFragment   = FragmentedRemoteObject.GetIsEndFragment(connectData, 0);
            int  blobLength      = FragmentedRemoteObject.GetBlobLength(connectData, 0);

            if (blobLength > (length - 0x15))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            if (!isStartFragment || !isEndFragment)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            RemoteSessionState state = this.SessionDataStructureHandler.StateMachine.State;

            if ((state != RemoteSessionState.Established) && (state != RemoteSessionState.EstablishedAndKeyExchanged))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation);
            }
            MemoryStream serializedDataStream = new MemoryStream();

            serializedDataStream.Write(connectData, 0x15, blobLength);
            serializedDataStream.Seek(0L, SeekOrigin.Begin);
            RemoteDataObject <PSObject> obj2 = RemoteDataObject <PSObject> .CreateFrom(serializedDataStream, defragmentor);

            if (obj2 == null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            if ((obj2.Destination != (RemotingDestination.InvalidDestination | RemotingDestination.Server)) || (obj2.DataType != RemotingDataType.SessionCapability))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            int num3 = (length - 0x15) - blobLength;

            if (num3 < 0x15)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            byte[] destinationArray = new byte[num3];
            Array.Copy(connectData, 0x15 + blobLength, destinationArray, 0, num3);
            FragmentedRemoteObject.GetFragmentId(destinationArray, 0);
            isStartFragment = FragmentedRemoteObject.GetIsStartFragment(destinationArray, 0);
            isEndFragment   = FragmentedRemoteObject.GetIsEndFragment(destinationArray, 0);
            blobLength      = FragmentedRemoteObject.GetBlobLength(destinationArray, 0);
            if (blobLength != (num3 - 0x15))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            if (!isStartFragment || !isEndFragment)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            serializedDataStream = new MemoryStream();
            serializedDataStream.Write(destinationArray, 0x15, blobLength);
            serializedDataStream.Seek(0L, SeekOrigin.Begin);
            RemoteDataObject <PSObject> obj3 = RemoteDataObject <PSObject> .CreateFrom(serializedDataStream, defragmentor);

            if (obj3 == null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation);
            }
            if ((obj3.Destination != (RemotingDestination.InvalidDestination | RemotingDestination.Server)) || (obj3.DataType != RemotingDataType.ConnectRunspacePool))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            try
            {
                sessionCapability = RemotingDecoder.GetSessionCapability(obj2.Data);
            }
            catch (PSRemotingDataStructureException)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            try
            {
                this.RunServerNegotiationAlgorithm(sessionCapability, true);
            }
            catch (PSRemotingDataStructureException exception)
            {
                throw exception;
            }
            int  minRunspaces = -1;
            int  maxRunspaces = -1;
            bool flag3        = false;

            if ((obj3.Data.Properties["MinRunspaces"] != null) && (obj3.Data.Properties["MinRunspaces"] != null))
            {
                try
                {
                    minRunspaces = RemotingDecoder.GetMinRunspaces(obj3.Data);
                    maxRunspaces = RemotingDecoder.GetMaxRunspaces(obj3.Data);
                    flag3        = true;
                }
                catch (PSRemotingDataStructureException)
                {
                    throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
                }
            }
            if (flag3 && (((minRunspaces == -1) || (maxRunspaces == -1)) || (minRunspaces > maxRunspaces)))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            if (this._runspacePoolDriver == null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation);
            }
            if (obj3.RunspacePoolId != this._runspacePoolDriver.InstanceId)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation);
            }
            if ((flag3 && (this._runspacePoolDriver.RunspacePool.GetMaxRunspaces() != maxRunspaces)) && (this._runspacePoolDriver.RunspacePool.GetMinRunspaces() != minRunspaces))
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnMismatchedRunspacePoolProperties);
            }
            RemoteDataObject     obj4            = RemotingEncoder.GenerateServerSessionCapability(this._context.ServerCapability, this._runspacePoolDriver.InstanceId);
            RemoteDataObject     obj5            = RemotingEncoder.GenerateRunspacePoolInitData(this._runspacePoolDriver.InstanceId, this._runspacePoolDriver.RunspacePool.GetMaxRunspaces(), this._runspacePoolDriver.RunspacePool.GetMinRunspaces());
            SerializedDataStream streamToWriteTo = new SerializedDataStream(0x1000);

            streamToWriteTo.Enter();
            obj4.Serialize(streamToWriteTo, fragmentor);
            streamToWriteTo.Exit();
            streamToWriteTo.Enter();
            obj5.Serialize(streamToWriteTo, fragmentor);
            streamToWriteTo.Exit();
            byte[] buffer2 = streamToWriteTo.Read();
            streamToWriteTo.Dispose();
            connectResponseData = buffer2;
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object s) {
                RemoteSessionStateMachineEventArgs fsmEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ConnectSession);
                this._sessionDSHandler.StateMachine.RaiseEvent(fsmEventArg);
            }));
            this._runspacePoolDriver.DataStructureHandler.ProcessConnect();
        }