internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo, string initializationScriptForOutOfProcessRunspace, AbstractServerSessionTransportManager transportManager)
        {
            ServerRemoteSession session = CreateServerRemoteSession(senderInfo, "Microsoft.PowerShell", "", transportManager);

            session._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace;
            return(session);
        }
 public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
 {
     if (sessionConfigurationData == null)
     {
         throw new ArgumentNullException("sessionConfigurationData");
     }
     if (senderInfo == null)
     {
         throw new ArgumentNullException("senderInfo");
     }
     if (configProviderId == null)
     {
         throw new ArgumentNullException("configProviderId");
     }
     InitialSessionState state = InitialSessionState.CreateDefault();
     if ((sessionConfigurationData != null) && (sessionConfigurationData.ModulesToImport != null))
     {
         foreach (string str in sessionConfigurationData.ModulesToImport)
         {
             state.ImportPSModulesFromPath(str);
         }
     }
     if ((senderInfo.ConnectionString != null) && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
     {
         PSSessionConfigurationData.IsServerManager = true;
     }
     return state;
 }
Exemple #3
0
 private PSSenderInfo(SerializationInfo info, StreamingContext context)
 {
     if (info != null)
     {
         string source = null;
         try
         {
             source = info.GetValue("CliXml", typeof(string)) as string;
         }
         catch (Exception)
         {
             return;
         }
         if (source != null)
         {
             try
             {
                 PSSenderInfo info2 = DeserializingTypeConverter.RehydratePSSenderInfo(PSObject.AsPSObject(PSSerializer.Deserialize(source)));
                 this.userPrinicpal        = info2.userPrinicpal;
                 this.clientTimeZone       = info2.ClientTimeZone;
                 this.connectionString     = info2.connectionString;
                 this.applicationArguments = info2.applicationArguments;
             }
             catch (Exception)
             {
                 return;
             }
         }
     }
 }
		public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
		{
			Tracer tracer = new Tracer();
			tracer.Correlate();
			if (sessionConfigurationData != null)
			{
				if (senderInfo != null)
				{
					if (!string.IsNullOrEmpty(configProviderId))
					{
						if (Interlocked.CompareExchange(ref PSWorkflowSessionConfiguration._modulesLoaded, 1, 0) == 0)
						{
							try
							{
								PSWorkflowConfigurationProvider configuration = WorkflowJobSourceAdapter.GetInstance().GetPSWorkflowRuntime().Configuration;
								if (configuration != null)
								{
									configuration.Populate(sessionConfigurationData.PrivateData, configProviderId, senderInfo);
									if (sessionConfigurationData.ModulesToImport != null)
									{
										foreach (string modulesToImport in sessionConfigurationData.ModulesToImport)
										{
											PSWorkflowSessionConfiguration.InitialSessionState.ImportPSModulesFromPath(modulesToImport);
										}
									}
								}
								else
								{
									throw new InvalidOperationException("PSWorkflowConfigurationProvider is null");
								}
							}
							catch (Exception exception)
							{
								Interlocked.CompareExchange(ref PSWorkflowSessionConfiguration._modulesLoaded, 0, 1);
								throw;
							}
						}
						if (configProviderId.ToLower(CultureInfo.InvariantCulture).Equals("http://schemas.microsoft.com/powershell/microsoft.windows.servermanagerworkflows"))
						{
							PSSessionConfigurationData.IsServerManager = true;
						}
						return PSWorkflowSessionConfiguration.InitialSessionState;
					}
					else
					{
						throw new ArgumentNullException("configProviderId");
					}
				}
				else
				{
					throw new ArgumentNullException("senderInfo");
				}
			}
			else
			{
				throw new ArgumentNullException("sessionConfigurationData");
			}
		}
 private OutOfProcessServerSessionTransportManager CreateSessionTransportManager()
 {
     WindowsIdentity current = WindowsIdentity.GetCurrent();
     PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, current.Name, null), current);
     PSSenderInfo senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
     OutOfProcessServerSessionTransportManager transportManager = new OutOfProcessServerSessionTransportManager(this.originalStdOut);
     ServerRemoteSession.CreateServerRemoteSession(senderInfo, this._initialCommand, transportManager);
     return transportManager;
 }
 public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
 {
     InitialSessionState state = InitialSessionState.CreateDefault();
     if ((senderInfo.ConnectionString != null) && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
     {
         PSSessionConfigurationData.IsServerManager = true;
     }
     return state;
 }
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            InitialSessionState state = InitialSessionState.CreateDefault();

            if ((senderInfo.ConnectionString != null) && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
            {
                PSSessionConfigurationData.IsServerManager = true;
            }
            return(state);
        }
Exemple #8
0
 internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager)
 {
     _trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Finding InitialSessionState provider for id : {0}", new object[] { configurationProviderId }), new object[0]);
     if (string.IsNullOrEmpty(configurationProviderId))
     {
         throw PSTraceSource.NewInvalidOperationException("remotingerroridstrings", "NonExistentInitialSessionStateProvider", new object[] { configurationProviderId });
     }
     ServerRemoteSession session = new ServerRemoteSession(senderInfo, configurationProviderId, initializationParameters, transportManager);
     RemoteSessionStateMachineEventArgs fsmEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession);
     session._sessionDSHandler.StateMachine.RaiseEvent(fsmEventArg);
     return session;
 }
Exemple #9
0
		public Guid CreateSession(string connection, string username, string password, int authMechanism, int protocolVersion)
		{
			Guid sessionId = Guid.NewGuid ();
			var identity = new PSIdentity ("", true, username, null);
			var principal = new PSPrincipal (identity, WindowsIdentity.GetCurrent ());
			var sender = new PSSenderInfo (principal, connection);
			var session = ServerRemoteSession.CreateServerRemoteSession (sender, null, new WSManServerSessionTransportManager());
			lock (_lock) {
				_sessions.Add (sessionId, session);
			}
			return sessionId;
		}
		public Guid CreateSession ()
		{
			var username = System.Threading.Thread.CurrentPrincipal.Identity.Name;
			string connection =  OperationContext.Current.Host.Description.Endpoints[0].Address.Uri.ToString ();
			var identity = new PSIdentity ("", true, username, null);
			var principal = new PSPrincipal (identity, WindowsIdentity.GetCurrent ());
			var sender = new PSSenderInfo (principal, connection);
			var session = ServerRemoteSession.CreateServerRemoteSession (sender, null, sessionTransportManager);
			lock (_lock) {
				_sessions.Add (session.InstanceId, session);
			}
			return session.InstanceId;
		}
        internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager)
        {
            _trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Finding InitialSessionState provider for id : {0}", new object[] { configurationProviderId }), new object[0]);
            if (string.IsNullOrEmpty(configurationProviderId))
            {
                throw PSTraceSource.NewInvalidOperationException("remotingerroridstrings", "NonExistentInitialSessionStateProvider", new object[] { configurationProviderId });
            }
            ServerRemoteSession session = new ServerRemoteSession(senderInfo, configurationProviderId, initializationParameters, transportManager);
            RemoteSessionStateMachineEventArgs fsmEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession);

            session._sessionDSHandler.StateMachine.RaiseEvent(fsmEventArg);
            return(session);
        }
        /// <summary>
        /// Gets custom initial session state
        /// It relies on the RBAC system to give list of commands allowed for a user
        /// and creates Initial Session state from that
        /// </summary>
        /// <param name="senderInfo">Sender information</param>
        /// <returns>Custom initial Session state</returns>
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            if (senderInfo == null)
            {
                throw new ArgumentNullException("senderInfo");
            }

            if (senderInfo.UserInfo == null)
            {
                throw new ArgumentException("senderInfo.UserInfo is null");
            }

            InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
            foreach (SessionStateCommandEntry command in initialSessionState.Commands)
            {
                command.Visibility = SessionStateEntryVisibility.Private;
            }

            List<string> scripts = RbacSystem.Current.GetScripts(senderInfo.UserInfo);
            foreach (string script in scripts)
            {
                initialSessionState.Commands.Add(new SessionStateScriptEntry(script));
            }

            List<string> modules = RbacSystem.Current.GetModules(senderInfo.UserInfo);
            if (modules.Count > 0)
            {
                initialSessionState.ImportPSModule(modules.ToArray());
            }

            // enable execution of scripts in this process
            System.Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", "unrestricted");

            List<string> cmdletsFromRbac = RbacSystem.Current.GetCmdlets(senderInfo.UserInfo);

            // Add all commands from Rbac system to Initial Session State commands
            foreach (string cmdlet in cmdletsFromRbac)
            {
                SessionStateCommandEntry cmdletFromRbac = initialSessionState.Commands.FirstOrDefault(item => string.Equals(item.Name, cmdlet, StringComparison.OrdinalIgnoreCase));
                if (cmdletFromRbac == null)
                {
                    throw new ArgumentException("Command not found in InitialSessionState " + cmdlet);
                }

                cmdletFromRbac.Visibility = SessionStateEntryVisibility.Public;
            }

            return initialSessionState;
        }
Exemple #13
0
        /// <summary>
        /// Gets custom initial session state
        /// </summary>
        /// <param name="senderInfo">Sender information</param>
        /// <returns>Custom initial Session state</returns>
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            var initialSessionState = InitialSessionState.CreateDefault();

            var dir = HttpContext.Current != null ? HttpContext.Current.Server.MapPath(".") : Directory.GetCurrentDirectory();

            initialSessionState.ImportPSModule(Directory.EnumerateFiles(dir, "*.psm1")
                .Select(s => Path.Combine(dir, Path.GetFileNameWithoutExtension(s))).ToArray());

            foreach (var cmdletFileName in Directory.EnumerateFiles(dir, "*-*.ps1"))
            {
                initialSessionState.Commands.Add(
                    new SessionStateFunctionEntry(Path.GetFileNameWithoutExtension(cmdletFileName), File.ReadAllText(Path.Combine(dir, cmdletFileName))));
            }

            return initialSessionState;
        }
Exemple #14
0
        internal ServerRemoteSession(PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager)
        {
            NativeCommandProcessor.IsServerSide = true;
            this._senderInfo = senderInfo;
            this._configProviderId = configurationProviderId;
            this._initParameters = initializationParameters;
            this._cryptoHelper = (PSRemotingCryptoHelperServer) transportManager.CryptoHelper;
			this._cryptoHelper.Session = this;
            this._context = new ServerRemoteSessionContext();
            this._sessionDSHandler = new ServerRemoteSessionDSHandlerlImpl(this, transportManager);
            base.BaseSessionDataStructureHandler = this._sessionDSHandler;
            this._sessionDSHandler.CreateRunspacePoolReceived += new EventHandler<RemoteDataEventArgs>(this.HandleCreateRunspacePool);
            this._sessionDSHandler.NegotiationReceived += new EventHandler<RemoteSessionNegotiationEventArgs>(this.HandleNegotiationReceived);
            this._sessionDSHandler.SessionClosing += new EventHandler<EventArgs>(this.HandleSessionDSHandlerClosing);
            this._sessionDSHandler.PublicKeyReceived += new EventHandler<RemoteDataEventArgs<string>>(this.HandlePublicKeyReceived);
            transportManager.Closing += new EventHandler(this.HandleResourceClosing);
            transportManager.ReceivedDataCollection.MaximumReceivedObjectSize = 0xa00000;
            transportManager.ReceivedDataCollection.MaximumReceivedDataSize = null;
        }
 internal ServerRemoteSession(PSSenderInfo senderInfo, string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager)
 {
     NativeCommandProcessor.IsServerSide = true;
     this._senderInfo           = senderInfo;
     this._configProviderId     = configurationProviderId;
     this._initParameters       = initializationParameters;
     this._cryptoHelper         = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper;
     this._cryptoHelper.Session = this;
     this._context          = new ServerRemoteSessionContext();
     this._sessionDSHandler = new ServerRemoteSessionDSHandlerlImpl(this, transportManager);
     base.BaseSessionDataStructureHandler = this._sessionDSHandler;
     this._sessionDSHandler.CreateRunspacePoolReceived += new EventHandler <RemoteDataEventArgs>(this.HandleCreateRunspacePool);
     this._sessionDSHandler.NegotiationReceived        += new EventHandler <RemoteSessionNegotiationEventArgs>(this.HandleNegotiationReceived);
     this._sessionDSHandler.SessionClosing             += new EventHandler <EventArgs>(this.HandleSessionDSHandlerClosing);
     this._sessionDSHandler.PublicKeyReceived          += new EventHandler <RemoteDataEventArgs <string> >(this.HandlePublicKeyReceived);
     transportManager.Closing += new EventHandler(this.HandleResourceClosing);
     transportManager.ReceivedDataCollection.MaximumReceivedObjectSize = 0xa00000;
     transportManager.ReceivedDataCollection.MaximumReceivedDataSize   = null;
 }
Exemple #16
0
        /// <summary>
        /// Deserialization constructor
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        private PSSenderInfo(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                return;
            }

            string serializedData = null;

            try
            {
                serializedData = info.GetValue("CliXml", typeof(string)) as string;
            }
            catch (Exception)
            {
                // When a workflow is run locally, there won't be PSSenderInfo
                return;
            }

            if (serializedData == null)
            {
                return;
            }

            try
            {
                PSObject     result     = PSObject.AsPSObject(PSSerializer.Deserialize(serializedData));
                PSSenderInfo senderInfo = DeserializingTypeConverter.RehydratePSSenderInfo(result);

                UserInfo              = senderInfo.UserInfo;
                ConnectionString      = senderInfo.ConnectionString;
                _applicationArguments = senderInfo._applicationArguments;

#if !CORECLR // TimeZone Not In CoreCLR
                this.clientTimeZone = senderInfo.ClientTimeZone;
#endif
            }
            catch (Exception)
            {
                // Ignore conversion errors
                return;
            }
        }
        /// <summary>
        /// This constructor instantiates a ServerRemoteSession object and 
        /// a ServerRemoteSessionDataStructureHandler object.
        /// </summary>
        /// <param name="senderInfo">
        /// Details about the user creating this session.
        /// </param>
        /// <param name="configurationProviderId">
        /// The resource URI for which this session is being created
        /// </param>
        /// <param name="initializationParameters">
        /// Initialization Parameters xml passed by WSMan API. This data is read from the config
        /// xml.
        /// </param>
        /// <param name="transportManager">
        /// The transport manager this session should use to send/receive data
        /// </param>
        /// <returns></returns>
        internal ServerRemoteSession(PSSenderInfo senderInfo,
            string configurationProviderId,
            string initializationParameters,
            AbstractServerSessionTransportManager transportManager)
        {
            Dbg.Assert(null != transportManager, "transportManager cannot be null.");

            // let input,output and error from native commands redirect as we have
            // to send (or receive) them back to client for action.
            NativeCommandProcessor.IsServerSide = true;
            _senderInfo = senderInfo;
            _configProviderId = configurationProviderId;
            _initParameters = initializationParameters;
#if !UNIX
            _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper;
            _cryptoHelper.Session = this;
#else
            _cryptoHelper = null;
#endif

            Context = new ServerRemoteSessionContext();
            SessionDataStructureHandler = new ServerRemoteSessionDSHandlerlImpl(this, transportManager);
            BaseSessionDataStructureHandler = SessionDataStructureHandler;
            SessionDataStructureHandler.CreateRunspacePoolReceived += HandleCreateRunspacePool;
            SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived;
            SessionDataStructureHandler.SessionClosing += HandleSessionDSHandlerClosing;
            SessionDataStructureHandler.PublicKeyReceived +=
                new EventHandler<RemoteDataEventArgs<string>>(HandlePublicKeyReceived);
            transportManager.Closing += HandleResourceClosing;

            // update the quotas from sessionState..start with default size..and
            // when Custom Session Configuration is loaded (during runspace creation) update this.
            transportManager.ReceivedDataCollection.MaximumReceivedObjectSize =
                BaseTransportManager.MaximumReceivedObjectSize;

            // session transport manager can receive unlimited data..however each object is limited
            // by maxRecvdObjectSize. this is to allow clients to use a session for an unlimited time..
            // also the messages that can be sent to a session are limited and very controlled.
            // However a command transport manager can be restricted to receive only a fixed amount of data
            // controlled by maxRecvdDataSizeCommand..This is because commands can accept any number of input
            // objects
            transportManager.ReceivedDataCollection.MaximumReceivedDataSize = null;
        }
        /// <summary>
        /// Creates a server remote session for the supplied <paramref name="configurationProviderId"/>
        /// and <paramref name="transportManager"/>.
        /// </summary>
        /// <param name="senderInfo"></param>
        /// <param name="configurationProviderId"></param>
        /// <param name="initializationParameters">
        /// Initialization Parameters xml passed by WSMan API. This data is read from the config
        /// xml.
        /// </param>
        /// <param name="transportManager"></param>
        /// <param name="configurationName">Optional configuration endpoint name for OutOfProc sessions</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">
        /// InitialSessionState provider with <paramref name="configurationProviderId"/> does
        /// not exist on the remote server.
        /// </exception>
        /* 
                  <InitializationParameters>
                    <Param Name="PSVersion" Value="2.0" />
                    <Param Name="ApplicationBase" Value="<folder path>" />
                    ...
                  </InitializationParameters> 
        */
        internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo,
            string configurationProviderId,
            string initializationParameters,
            AbstractServerSessionTransportManager transportManager,
            string configurationName = null)
        {
            Dbg.Assert((senderInfo != null) & (senderInfo.UserInfo != null),
                "senderInfo and userInfo cannot be null.");

            s_trace.WriteLine("Finding InitialSessionState provider for id : {0}", configurationProviderId);

            if (string.IsNullOrEmpty(configurationProviderId))
            {
                throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId);
            }

            ServerRemoteSession result = new ServerRemoteSession(senderInfo,
                configurationProviderId,
                initializationParameters,
                transportManager)
            {
                _configurationName = configurationName
            };

            // start state machine.
            RemoteSessionStateMachineEventArgs startEventArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CreateSession);
            result.SessionDataStructureHandler.StateMachine.RaiseEvent(startEventArg);

            return result;
        }
Exemple #19
0
 /// <summary>
 /// Gets application private data
 /// </summary>
 /// <param name="senderInfo">Sender information</param>
 /// <returns>Always returns null</returns>
 public override PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
 {
     return null;
 }
 public virtual int?GetMaximumReceivedObjectSize(PSSenderInfo senderInfo)
 {
     return(0xa00000);
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sessionConfigurationData"></param>
        /// <param name="senderInfo"></param>
        /// <param name="configProviderId"></param>
        /// <returns></returns>
        public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
        {
            Tracer structuredTracer = new Tracer();

            structuredTracer.Correlate();

            if (sessionConfigurationData == null)
                throw new ArgumentNullException("sessionConfigurationData");

            if (senderInfo == null)
                throw new ArgumentNullException("senderInfo");

            if (string.IsNullOrEmpty(configProviderId))
                throw new ArgumentNullException("configProviderId");

            if (Interlocked.CompareExchange(ref _modulesLoaded, ModulesLoaded, ModulesNotLoaded) == ModulesNotLoaded)
            {
                // it is sufficient if Populate() is called the first time and
                // modules are loaded once

                try
                {
                    IsWorkflowTypeEndpoint = true;

                    PSWorkflowConfigurationProvider workflowConfiguration = WorkflowJobSourceAdapter.GetInstance().GetPSWorkflowRuntime().Configuration;
                    if (workflowConfiguration == null)
                        throw new InvalidOperationException("PSWorkflowConfigurationProvider is null");

                    workflowConfiguration.Populate(sessionConfigurationData.PrivateData, configProviderId, senderInfo);

                    // now get all the modules in the specified path and import the same
                    if (sessionConfigurationData.ModulesToImport != null)
                    {
                        foreach (var module in sessionConfigurationData.ModulesToImport)
                        {
                            ModuleSpecification moduleSpec = null;
                            if (ModuleSpecification.TryParse(module, out moduleSpec))
                            {
                                var modulesToImport = new Collection<ModuleSpecification> { moduleSpec };
                                InitialSessionState.ImportPSModule(modulesToImport);
                            }
                            else
                            {
                                InitialSessionState.ImportPSModule(new[] { Environment.ExpandEnvironmentVariables(module) });
                            }
                        }
                    }

                    // Start the workflow job manager, if not started, to add an event handler for zero active sessions changed events
                    // This is required to auto shutdown the workflow type shared process when no workflow jobs have scheduled/inprogress and when no active sessions
                    WorkflowJobSourceAdapter.GetInstance().GetJobManager();
                }
                catch(Exception)
                {
                    // if there is an exception in either Populate() or Importing modules
                    // we consider that it is not loaded
                    Interlocked.CompareExchange(ref _modulesLoaded, ModulesNotLoaded, ModulesLoaded);
                    throw;
                }
            }
            
            if (configProviderId.ToLower(CultureInfo.InvariantCulture).Equals("http://schemas.microsoft.com/powershell/microsoft.windows.servermanagerworkflows"))
            {
                PSSessionConfigurationData.IsServerManager = true;
            }

            return InitialSessionState;
        }
Exemple #22
0
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            InitialSessionState state = null;
            bool        flag          = false;
            string      str           = TryGetValue(this.configHash, ConfigFileContants.SessionType);
            SessionType type          = SessionType.Default;
            bool        flag2         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleCmdlets);
            bool        flag3         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleFunctions);
            bool        flag4         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleAliases);
            bool        flag5         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleProviders);

            if (!string.IsNullOrEmpty(str))
            {
                type = (SessionType)Enum.Parse(typeof(SessionType), str, true);
                switch (type)
                {
                case SessionType.Empty:
                    state = InitialSessionState.Create();
                    goto Label_00AD;

                case SessionType.RestrictedRemoteServer:
                    state = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
                    if (flag5)
                    {
                        InitialSessionState state2 = InitialSessionState.CreateDefault2();
                        state.Providers.Add(state2.Providers);
                    }
                    goto Label_00AD;
                }
                state = InitialSessionState.CreateDefault2();
            }
            else
            {
                state = InitialSessionState.CreateDefault2();
            }
Label_00AD:
            if (this.configHash.ContainsKey(ConfigFileContants.AssembliesToLoad))
            {
                string[] strArray = TryGetStringArray(this.configHash[ConfigFileContants.AssembliesToLoad]);
                if (strArray != null)
                {
                    foreach (string str2 in strArray)
                    {
                        state.Assemblies.Add(new SessionStateAssemblyEntry(str2));
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.ModulesToImport))
            {
                object[] objArray = TryGetObjectsOfType <object>(this.configHash[ConfigFileContants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) });
                if ((this.configHash[ConfigFileContants.ModulesToImport] != null) && (objArray == null))
                {
                    PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport));
                    exception.SetErrorId("InvalidModulesToImportKeyEntries");
                    throw exception;
                }
                if (objArray != null)
                {
                    Collection <ModuleSpecification> modules = new Collection <ModuleSpecification>();
                    foreach (object obj2 in objArray)
                    {
                        ModuleSpecification item = null;
                        string str4 = obj2 as string;
                        if (!string.IsNullOrEmpty(str4))
                        {
                            item = new ModuleSpecification(str4);
                        }
                        else
                        {
                            Hashtable moduleSpecification = obj2 as Hashtable;
                            if (moduleSpecification != null)
                            {
                                item = new ModuleSpecification(moduleSpecification);
                            }
                        }
                        if (item != null)
                        {
                            if (string.Equals(InitialSessionState.CoreModule, item.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                if (type == SessionType.Empty)
                                {
                                    state.ImportCorePSSnapIn();
                                }
                            }
                            else
                            {
                                modules.Add(item);
                            }
                        }
                    }
                    state.ImportPSModule(modules);
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.AliasDefinitions))
            {
                Hashtable[] hashtableArray = TryGetHashtableArray(this.configHash[ConfigFileContants.AliasDefinitions]);
                if (hashtableArray != null)
                {
                    foreach (Hashtable hashtable2 in hashtableArray)
                    {
                        SessionStateAliasEntry entry = this.CreateSessionStateAliasEntry(hashtable2);
                        if (entry != null)
                        {
                            state.Commands.Add(entry);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
            {
                Hashtable[] hashtableArray2 = TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                if (hashtableArray2 != null)
                {
                    foreach (Hashtable hashtable3 in hashtableArray2)
                    {
                        SessionStateFunctionEntry entry2 = this.CreateSessionStateFunctionEntry(hashtable3);
                        if (entry2 != null)
                        {
                            state.Commands.Add(entry2);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
            {
                Hashtable[] hashtableArray3 = TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                if (hashtableArray3 != null)
                {
                    foreach (Hashtable hashtable4 in hashtableArray3)
                    {
                        if (!hashtable4.ContainsKey(ConfigFileContants.VariableValueToken) || !(hashtable4[ConfigFileContants.VariableValueToken] is ScriptBlock))
                        {
                            SessionStateVariableEntry entry3 = this.CreateSessionStateVariableEntry(hashtable4);
                            if (entry3 != null)
                            {
                                state.Variables.Add(entry3);
                            }
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.TypesToProcess))
            {
                string[] strArray2 = TryGetStringArray(this.configHash[ConfigFileContants.TypesToProcess]);
                if (strArray2 != null)
                {
                    foreach (string str5 in strArray2)
                    {
                        if (!string.IsNullOrEmpty(str5))
                        {
                            state.Types.Add(new SessionStateTypeEntry(str5));
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FormatsToProcess))
            {
                string[] strArray3 = TryGetStringArray(this.configHash[ConfigFileContants.FormatsToProcess]);
                if (strArray3 != null)
                {
                    foreach (string str6 in strArray3)
                    {
                        if (!string.IsNullOrEmpty(str6))
                        {
                            state.Formats.Add(new SessionStateFormatEntry(str6));
                        }
                    }
                }
            }
            if ((flag2 || flag3) || (flag4 || flag5))
            {
                flag = true;
            }
            if (flag)
            {
                state.Variables.Add(new SessionStateVariableEntry("PSModuleAutoLoadingPreference", PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None));
                if (type == SessionType.Default)
                {
                    state.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray <string>());
                }
                if (!flag2)
                {
                    state.Commands.Remove("Import-Module", typeof(SessionStateCmdletEntry));
                }
                if (!flag4)
                {
                    state.Commands.Remove("ipmo", typeof(SessionStateAliasEntry));
                }
            }
            return(state);
        }
Exemple #23
0
 public override InitialSessionState GetInitialSessionState(
     PSSenderInfo senderInfo)
 {
     return(InitialSessionState.CreateDefault());
 }
 public virtual int?GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo) => new int?(52428800);
 public virtual int? GetMaximumReceivedObjectSize(PSSenderInfo senderInfo)
 {
     return 0xa00000;
 }
 public abstract InitialSessionState GetInitialSessionState(
     PSSenderInfo senderInfo);
 public virtual int? GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo)
 {
     return 0x3200000;
 }
 public virtual int?GetMaximumReceivedDataSizePerCommand(PSSenderInfo senderInfo)
 {
     return(0x3200000);
 }
 public virtual int?GetMaximumReceivedObjectSize(PSSenderInfo senderInfo) => new int?(10485760);
 /// <summary>
 /// Used by OutOfProcessServerMediator to create a remote session.
 /// </summary>
 /// <param name="senderInfo"></param>
 /// <param name="initializationScriptForOutOfProcessRunspace"></param>
 /// <param name="transportManager"></param>
 /// <param name="configurationName"></param>
 /// <returns></returns>
 internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo,
     string initializationScriptForOutOfProcessRunspace,
     AbstractServerSessionTransportManager transportManager,
     string configurationName)
 {
     ServerRemoteSession result = CreateServerRemoteSession(senderInfo,
         "Microsoft.PowerShell", "", transportManager, configurationName);
     result._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace;
     return result;
 }
Exemple #31
0
 internal static ServerRemoteSession CreateServerRemoteSession(PSSenderInfo senderInfo, string initializationScriptForOutOfProcessRunspace, AbstractServerSessionTransportManager transportManager)
 {
     ServerRemoteSession session = CreateServerRemoteSession(senderInfo, "Microsoft.PowerShell", "", transportManager);
     session._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace;
     return session;
 }
        public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
        {
            if (sessionConfigurationData == null)
            {
                throw new ArgumentNullException("sessionConfigurationData");
            }
            if (senderInfo == null)
            {
                throw new ArgumentNullException("senderInfo");
            }
            if (configProviderId == null)
            {
                throw new ArgumentNullException("configProviderId");
            }
            InitialSessionState state = InitialSessionState.CreateDefault();

            if ((sessionConfigurationData != null) && (sessionConfigurationData.ModulesToImport != null))
            {
                foreach (string str in sessionConfigurationData.ModulesToImport)
                {
                    state.ImportPSModulesFromPath(str);
                }
            }
            if ((senderInfo.ConnectionString != null) && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8"))
            {
                PSSessionConfigurationData.IsServerManager = true;
            }
            return(state);
        }
 public virtual PSPrimitiveDictionary GetApplicationPrivateData(
     PSSenderInfo senderInfo)
 {
     return((PSPrimitiveDictionary)null);
 }
Exemple #34
0
        /// <summary>
        /// used to create PSPrincipal object from senderDetails struct.
        /// </summary>
        /// <param name="senderDetails"></param>
        /// <returns></returns>
        private PSSenderInfo GetPSSenderInfo(
            WSManNativeApi.WSManSenderDetails senderDetails)
        {
            // senderDetails will not be null.
            Dbg.Assert(null != senderDetails, "senderDetails cannot be null");

            // Construct PSIdentity
            PSCertificateDetails psCertDetails = null;
            // Construct Certificate Details
            if (null != senderDetails.certificateDetails)
            {
                psCertDetails = new PSCertificateDetails(
                    senderDetails.certificateDetails.subject,
                    senderDetails.certificateDetails.issuerName,
                    senderDetails.certificateDetails.issuerThumbprint);
            }

            // Construct PSPrincipal
            PSIdentity psIdentity = new PSIdentity(senderDetails.authenticationMechanism, true, senderDetails.senderName, psCertDetails);

            // For Virtual and RunAs accounts WSMan specifies the client token via an environment variable and
            // senderDetails.clientToken should not be used.
            IntPtr clientToken = GetRunAsClientToken();
            clientToken = (clientToken != IntPtr.Zero) ? clientToken : senderDetails.clientToken;
            WindowsIdentity windowsIdentity = null;
            if (clientToken != IntPtr.Zero)
            {
                try
                {
                    windowsIdentity = new WindowsIdentity(clientToken, senderDetails.authenticationMechanism);
                }
                // Suppress exceptions..So windowsIdentity = null in these cases
                catch (ArgumentException)
                {
                    // userToken is 0.
                    // -or-
                    // userToken is duplicated and invalid for impersonation.
                }
                catch (System.Security.SecurityException)
                {
                    // The caller does not have the correct permissions. 
                    // -or-
                    // A Win32 error occurred.
                }
            }

            PSPrincipal userPrincipal = new PSPrincipal(psIdentity, windowsIdentity);
            PSSenderInfo result = new PSSenderInfo(userPrincipal, senderDetails.httpUrl);
            return result;
        }
 public virtual PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo)
 {
     return null;
 }
		public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
		{
			throw new NotImplementedException();
		}
 public abstract InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo);
 public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
 {
     throw new NotImplementedException();
 }
 public virtual InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId)
 {
     throw new NotImplementedException();
 }