/// <summary> /// Creates a local runspace with the autoloading turned on. /// </summary> /// <returns></returns> internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState iss = GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode != null && languageMode.HasValue) { iss.LanguageMode = languageMode.Value; } // Add a variable indicating that we're in Workflow endpoint. This enables the // autoloading feature. SessionStateVariableEntry ssve = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", true, "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); iss.Variables.Add(ssve); Runspace runspace = RunspaceFactory.CreateRunspace(iss); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
} // CoreBeginProcessing /// <summary> /// Create a throttle operation using NewProcessConnectionInfo /// ie., Out-Of-Process runspace. /// </summary> protected override void CreateHelpersForSpecifiedComputerNames() { // If we're in ConstrainedLanguage mode and the system is in lockdown mode, // ensure that they haven't specified a ScriptBlock or InitScript - as // we can't protect that boundary if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) && ((ScriptBlock != null) || (InitializationScript != null))) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode), "CannotStartJobInconsistentLanguageMode", ErrorCategory.PermissionDenied, Context.LanguageMode)); } NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential); connectionInfo.RunAs32 = _shouldRunAs32; connectionInfo.InitializationScript = _initScript; connectionInfo.AuthenticationMechanism = this.Authentication; connectionInfo.PSVersion = this.PSVersion; RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host, Utils.GetTypeTableFromExecutionContextTLS()); remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; Pipeline pipeline = CreatePipeline(remoteRunspace); IThrottleOperation operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline); Operations.Add(operation); }
protected Runspace CreateRunspace() { Runspace runspace = null; if (this.rsConfig != null) { runspace = RunspaceFactory.CreateRunspace(this.host, this.rsConfig); } else { runspace = RunspaceFactory.CreateRunspaceFromSessionStateNoClone(this.host, this._initialSessionState); } runspace.ThreadOptions = (this.ThreadOptions == PSThreadOptions.Default) ? PSThreadOptions.ReuseThread : this.ThreadOptions; runspace.ApartmentState = this.ApartmentState; this.PropagateApplicationPrivateData(runspace); runspace.Open(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } runspace.Events.ForwardEvent += new EventHandler <PSEventArgs>(this.OnRunspaceForwardEvent); lock (this.runspaceList) { this.runspaceList.Add(runspace); this.totalRunspaces = this.runspaceList.Count; } lock (this.syncObject) { this.cleanupTimer.Change(this.CleanupInterval, this.CleanupInterval); } this.RunspaceCreated.SafeInvoke <RunspaceCreatedEventArgs>(this, new RunspaceCreatedEventArgs(runspace)); return(runspace); }
private void ReadScriptContents() { if (this._scriptContents == null) { try { using (FileStream stream = new FileStream(this._path, FileMode.Open, FileAccess.Read)) { using (StreamReader reader = new StreamReader(stream, Encoding.Default)) { this._scriptContents = reader.ReadToEnd(); this._originalEncoding = reader.CurrentEncoding; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if (SystemPolicy.GetLockdownPolicy(this._path, stream.SafeFileHandle) != SystemEnforcementMode.Enforce) { base.DefiningLanguageMode = (PSLanguageMode)0; } else { base.DefiningLanguageMode = (PSLanguageMode)3; } } else if (base.Context != null) { base.DefiningLanguageMode = new PSLanguageMode?(base.Context.LanguageMode); } } } } catch (ArgumentException exception) { ThrowCommandNotFoundException(exception); } catch (IOException exception2) { ThrowCommandNotFoundException(exception2); } catch (NotSupportedException exception3) { ThrowCommandNotFoundException(exception3); } catch (UnauthorizedAccessException exception4) { ThrowCommandNotFoundException(exception4); } } }
private void CommonInitialization() { if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if (SystemPolicy.GetLockdownPolicy(this._path, null) != SystemEnforcementMode.Enforce) { base.DefiningLanguageMode = (PSLanguageMode)0; } else { base.DefiningLanguageMode = (PSLanguageMode)3; } } else { base.DefiningLanguageMode = PSLanguageMode.FullLanguage; } }
/// <summary> /// Common initialization for all constructors. /// </summary> private void CommonInitialization() { // Assume external scripts are untrusted by default (for Get-Command, etc) // until we've actually parsed their script block. if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) { // Get the lock down policy with no handle. This only impacts command discovery, // as the real language mode assignment will be done when we read the script // contents. SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null); if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) { this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } else { this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; } } }
internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode.HasValue && languageMode.HasValue) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value; } SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry); Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
private void ReadScriptContents() { if (_scriptContents == null) { // make sure we can actually load the script and that it's non-empty // before we call it. // Note, although we are passing ASCII as the encoding, the StreamReader // class still obeys the byte order marks at the beginning of the file // if present. If not present, then ASCII is used as the default encoding. try { using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) { Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) { _scriptContents = scriptReader.ReadToEnd(); _originalEncoding = scriptReader.CurrentEncoding; // Check if this came from a trusted path. If so, set its language mode to FullLanguage. if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) { SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle); if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) { this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } else { this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; } } else { if (this.Context != null) { this.DefiningLanguageMode = this.Context.LanguageMode; } } } } } catch (ArgumentException e) { // This catches PSArgumentException as well. ThrowCommandNotFoundException(e); } catch (IOException e) { ThrowCommandNotFoundException(e); } catch (NotSupportedException e) { ThrowCommandNotFoundException(e); } catch (UnauthorizedAccessException e) { // this is unadvertised exception thrown by the StreamReader ctor when // no permission to read the script file ThrowCommandNotFoundException(e); } } }
protected override void CreateHelpersForSpecifiedComputerNames() { if (((base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)) && ((this.ScriptBlock != null) || (this.InitializationScript != null))) { base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode), "CannotStartJobInconsistentLanguageMode", ErrorCategory.PermissionDenied, base.Context.LanguageMode)); } NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential) { RunAs32 = this.shouldRunAs32, InitializationScript = this.initScript, AuthenticationMechanism = this.Authentication, PSVersion = this.PSVersion }; RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, base.Host, Utils.GetTypeTableFromExecutionContextTLS()); remoteRunspace.Events.ReceivedEvents.PSEventReceived += new PSEventReceivedEventHandler(this.OnRunspacePSEventReceived); Pipeline pipeline = base.CreatePipeline(remoteRunspace); IThrottleOperation item = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline, false); base.Operations.Add(item); }
/// <summary> Create the object </summary> protected override void BeginProcessing() { Type type = null; PSArgumentException mshArgE = null; if (string.Compare(ParameterSetName, netSetName, StringComparison.Ordinal) == 0) { object _newObject = null; try { type = LanguagePrimitives.ConvertTo(TypeName, typeof(Type), CultureInfo.InvariantCulture) as Type; } catch (Exception e) { // these complications in Exception handling are aim to make error messages better. if (e is InvalidCastException || e is ArgumentException) { if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException) { ThrowTerminatingError( new ErrorRecord( e, "AmbiguousTypeReference", ErrorCategory.InvalidType, targetObject: null)); } mshArgE = PSTraceSource.NewArgumentException( "TypeName", NewObjectStrings.TypeNotFound, TypeName); ThrowTerminatingError( new ErrorRecord( mshArgE, "TypeNotFound", ErrorCategory.InvalidType, targetObject: null)); } throw e; } Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true"); if (type.IsByRefLike) { ThrowTerminatingError( new ErrorRecord( PSTraceSource.NewInvalidOperationException( NewObjectStrings.CannotInstantiateBoxedByRefLikeType, type), nameof(NewObjectStrings.CannotInstantiateBoxedByRefLikeType), ErrorCategory.InvalidOperation, targetObject: null)); } if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { if (!CoreTypes.Contains(type)) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); } } // WinRT does not support creating instances of attribute & delegate WinRT types. if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type))) { ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType), "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null)); } if (ArgumentList == null || ArgumentList.Length == 0) { ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes); if (ci != null && ci.IsPublic) { _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, new object[] { }); if (_newObject != null && Property != null) { // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } WriteObject(_newObject); return; } else if (type.GetTypeInfo().IsValueType) { // This is for default parameterless struct ctor which is not returned by // Type.GetConstructor(System.Type.EmptyTypes). try { _newObject = Activator.CreateInstance(type); if (_newObject != null && Property != null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } } catch (TargetInvocationException e) { ThrowTerminatingError( new ErrorRecord( e.InnerException ?? e, "ConstructorCalledThrowException", ErrorCategory.InvalidOperation, null)); } WriteObject(_newObject); return; } } else { ConstructorInfo[] ctorInfos = type.GetConstructors(); if (ctorInfos.Length != 0) { _newObject = CallConstructor(type, ctorInfos, ArgumentList); if (_newObject != null && Property != null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } WriteObject(_newObject); return; } } mshArgE = PSTraceSource.NewArgumentException( "TypeName", NewObjectStrings.CannotFindAppropriateCtor, TypeName); ThrowTerminatingError( new ErrorRecord( mshArgE, "CannotFindAppropriateCtor", ErrorCategory.ObjectNotFound, null)); } #if !UNIX else // Parameterset -Com { int result = NewObjectNativeMethods.CLSIDFromProgID(ComObject, out _comObjectClsId); // If we're in ConstrainedLanguage, do additional restrictions if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { bool isAllowed = false; // If it's a system-wide lockdown, we may allow additional COM types if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { if ((result >= 0) && SystemPolicy.IsClassInApprovedList(_comObjectClsId)) { isAllowed = true; } } if (!isAllowed) { ThrowTerminatingError( new ErrorRecord( new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); return; } } object comObject = CreateComObject(); string comObjectTypeName = comObject.GetType().FullName; if (!comObjectTypeName.Equals("System.__ComObject")) { mshArgE = PSTraceSource.NewArgumentException( "TypeName", NewObjectStrings.ComInteropLoaded, comObjectTypeName); WriteVerbose(mshArgE.Message); if (Strict) { WriteError(new ErrorRecord( mshArgE, "ComInteropLoaded", ErrorCategory.InvalidArgument, comObject)); } } if (comObject != null && Property != null) { // Win8:649519 comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); } WriteObject(comObject); } #endif }
private void OnDebuggerStop(InvocationInfo invocationInfo, List <Breakpoint> breakpoints) { LocalRunspace currentRunspace = this._context.CurrentRunspace as LocalRunspace; if ((currentRunspace.PulsePipeline != null) && (currentRunspace.PulsePipeline == currentRunspace.GetCurrentlyRunningPipeline())) { this._context.EngineHostInterface.UI.WriteWarningLine((breakpoints.Count > 0) ? string.Format(CultureInfo.CurrentCulture, DebuggerStrings.WarningBreakpointWillNotBeHit, new object[] { breakpoints[0] }) : new InvalidOperationException().Message); } else { this._steppingMode = SteppingMode.None; EventHandler <DebuggerStopEventArgs> debuggerStop = this.DebuggerStop; if (debuggerStop != null) { this.InBreakpoint = true; this._context.SetVariable(SpecialVariables.PSDebugContextVarPath, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo baseObject = null; bool flag = false; try { Collection <PSObject> collection = this._context.SessionState.InvokeProvider.Item.Get(@"function:\prompt"); if ((collection != null) && (collection.Count > 0)) { baseObject = collection[0].BaseObject as FunctionInfo; if (string.Equals(baseObject.Definition, InitialSessionState.DefaultPromptString, StringComparison.OrdinalIgnoreCase)) { flag = true; } } } catch (ItemNotFoundException) { } if (flag) { string script = "\"[DBG]: PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) \""; baseObject.Update(ScriptBlock.Create(script), true, ScopedItemOptions.Unspecified); } PSLanguageMode languageMode = this._context.LanguageMode; PSLanguageMode?nullable = null; if (this._context.UseFullLanguageModeInDebugger && (this._context.LanguageMode != PSLanguageMode.FullLanguage)) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.FullLanguage; } else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { nullable = new PSLanguageMode?(this._context.LanguageMode); this._context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } RunspaceAvailability runspaceAvailability = this._context.CurrentRunspace.RunspaceAvailability; this._context.CurrentRunspace.UpdateRunspaceAvailability((this._context.CurrentRunspace.GetCurrentlyRunningPipeline() != null) ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); try { this._context._debuggingMode = -1; if (this._callStack.Any <CallStackInfo>()) { this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = true; } DebuggerStopEventArgs e = new DebuggerStopEventArgs(invocationInfo, breakpoints); debuggerStop(this, e); this.ResumeExecution(e.ResumeAction); } finally { this._context._debuggingMode = 1; if (this._callStack.Any <CallStackInfo>()) { this._callStack.Last <CallStackInfo>().TopFrameAtBreakpoint = false; } this._context.CurrentRunspace.UpdateRunspaceAvailability(runspaceAvailability, true); if (nullable.HasValue) { this._context.LanguageMode = nullable.Value; } this._context.EngineSessionState.RemoveVariable("PSDebugContext"); if (flag) { baseObject.Update(ScriptBlock.Create(InitialSessionState.DefaultPromptString), true, ScopedItemOptions.Unspecified); } this.InBreakpoint = false; } } } }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); this.PSJobTypeName = "ThreadJob"; // Create host object for thread jobs. ThreadJobHost host = new ThreadJobHost(); HookupHostDataDelegates(host); // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } _rs = RunspaceFactory.CreateRunspace(host, iss); _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.ResourceManager.GetString("CannotParseScriptFile")); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.ResourceManager.GetString("NoScriptToRun")); } // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as an array or dictionary, depending on PowerShell version. if (psCmdlet.Host.Version.Major >= 5) { _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } else if (psCmdlet.Host.Version.Major == 3 || psCmdlet.Host.Version.Major == 4) { _usingValuesArray = GetUsingValuesAsArray(usingAsts, psCmdlet); } } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
private static PSLanguageMode GetSystemLanguageMode() { return((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage); }
private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args) { bool flag = false; if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; flag = true; } try { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath); } catch (ArgumentException) { } catch (ProviderNotFoundException) { } catch (DriveNotFoundException) { } catch (ProviderInvocationException) { } if (this.configHash != null) { if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables)) { Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable; if (hashtable != null) { foreach (DictionaryEntry entry in hashtable) { string introduced76 = entry.Key.ToString(); this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args); } } } if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions)) { Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]); if (hashtableArray != null) { foreach (Hashtable hashtable2 in hashtableArray) { if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken)) { string str2 = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken); ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock; if (!string.IsNullOrEmpty(str2) && (block != null)) { block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState; PowerShell powershell = PowerShell.Create(); powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope"); powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2); this.InvokePowerShell(powershell, args); } } } } } if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess)) { string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]); if (strArray != null) { foreach (string str3 in strArray) { if (!string.IsNullOrEmpty(str3)) { this.InvokeScript(new Command(str3, true, false), args); } } } } bool flag2 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases)) { string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]); if (strArray2 != null) { flag2 = true; foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable()) { bool flag3 = false; foreach (string str4 in strArray2) { if (!string.IsNullOrEmpty(str4)) { IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4); if (this.MatchKeyPattern(patternList, pair.Key)) { pair.Value.Visibility = SessionStateEntryVisibility.Public; flag3 = true; } } } if (!flag3) { pair.Value.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets)) { string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]); if (strArray3 != null) { flag2 = true; foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable()) { bool flag4 = false; foreach (string str5 in strArray3) { if (!string.IsNullOrEmpty(str5)) { IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5); if (this.MatchKeyPattern(enumerable2, pair2.Key)) { foreach (CmdletInfo info in pair2.Value) { info.Visibility = SessionStateEntryVisibility.Public; flag4 = true; } } } } if (!flag4) { foreach (CmdletInfo info2 in pair2.Value) { info2.Visibility = SessionStateEntryVisibility.Private; } } } } } List <string> list = new List <string>(); bool flag5 = false; if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions)) { string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]); if (strArray4 != null) { flag2 = true; flag5 = true; list.AddRange(strArray4); } } if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions)) { Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]); if (hashtableArray2 != null) { foreach (Hashtable hashtable3 in hashtableArray2) { string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken); if (!string.IsNullOrEmpty(str6)) { list.Add(str6); } } } } string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType); if (!string.IsNullOrEmpty(str7)) { SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true); if (type == SessionType.RestrictedRemoteServer) { list.Add("Get-Command"); list.Add("Get-FormatData"); list.Add("Select-Object"); list.Add("Get-Help"); list.Add("Measure-Object"); list.Add("Out-Default"); list.Add("Exit-PSSession"); } } if (list.Count > 0) { foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable()) { bool flag6 = false; string key = entry2.Key.ToString(); FunctionInfo info3 = entry2.Value as FunctionInfo; if (info3 != null) { foreach (string str9 in list) { if (!string.IsNullOrEmpty(str9)) { IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9); if (this.MatchKeyPattern(enumerable3, key)) { info3.Visibility = SessionStateEntryVisibility.Public; flag6 = true; } } } if (!flag6 && flag5) { info3.Visibility = SessionStateEntryVisibility.Private; } } } } if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders)) { string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]); if (strArray5 != null) { flag2 = true; IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers; Collection <string> collection = new Collection <string>(); foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers) { bool flag7 = false; foreach (string str10 in strArray5) { if (!string.IsNullOrEmpty(str10)) { IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10); if (this.MatchKeyPattern(enumerable4, pair3.Key)) { flag7 = true; } } } if (!flag7) { collection.Add(pair3.Key); } } foreach (string str11 in collection) { args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11); } } } if (flag2) { CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module"); IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable(); PSModuleAutoLoadingPreference preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private); bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private); if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None)) { throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders })); } } if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode)) { PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true); if (flag && (mode != PSLanguageMode.ConstrainedLanguage)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState); } args.Runspace.ExecutionContext.LanguageMode = mode; } if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy)) { ExecutionPolicy policy = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true); string shellID = args.Runspace.ExecutionContext.ShellID; SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID); } } Command cmdToRun = null; if (!string.IsNullOrEmpty(this.configData.StartupScript)) { cmdToRun = new Command(this.configData.StartupScript, false, false); } else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace)) { cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false); } if (cmdToRun != null) { this.InvokeScript(cmdToRun, args); if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); if (valueToConvert != null) { this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null); } } } }
protected override void BeginProcessing() { Type result = null; PSArgumentException exception = null; if (string.Compare(base.ParameterSetName, "Net", StringComparison.Ordinal) == 0) { object o = null; if (!LanguagePrimitives.TryConvertTo <Type>(this.typeName, out result)) { exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "TypeNotFound", new object[] { this.typeName }); base.ThrowTerminatingError(new ErrorRecord(exception, "TypeNotFound", ErrorCategory.InvalidType, null)); } if ((base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && !CoreTypes.Contains(result)) { base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); } if (WinRTHelper.IsWinRTType(result) && (typeof(Attribute).IsAssignableFrom(result) || typeof(Delegate).IsAssignableFrom(result))) { base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType), "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null)); } if ((this.arguments == null) || (this.arguments.Length == 0)) { ConstructorInfo constructor = result.GetConstructor(Type.EmptyTypes); if ((constructor != null) && constructor.IsPublic) { o = this.CallConstructor(result, new ConstructorInfo[] { constructor }, new object[0]); if ((o != null) && (this.property != null)) { o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true); } base.WriteObject(o); return; } if (result.IsValueType) { try { o = Activator.CreateInstance(result, false); if ((o != null) && (this.property != null)) { o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true); } } catch (TargetInvocationException exception2) { base.ThrowTerminatingError(new ErrorRecord((exception2.InnerException == null) ? exception2 : exception2.InnerException, "ConstructorCalledThrowException", ErrorCategory.InvalidOperation, null)); } base.WriteObject(o); return; } } else { ConstructorInfo[] constructors = result.GetConstructors(); if (constructors.Length != 0) { o = this.CallConstructor(result, constructors, this.arguments); if ((o != null) && (this.property != null)) { o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true); } base.WriteObject(o); return; } } exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "CannotFindAppropriateCtor", new object[] { this.typeName }); base.ThrowTerminatingError(new ErrorRecord(exception, "CannotFindAppropriateCtor", ErrorCategory.ObjectNotFound, null)); } else { NewObjectNativeMethods.CLSIDFromProgID(this.comObject, out this.comObjectClsId); if (base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { bool flag2 = false; if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && SystemPolicy.IsClassInApprovedList(this.comObjectClsId)) { flag2 = true; } if (!flag2) { base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); return; } } PSSQMAPI.IncrementDataPoint((int)0x2099); object targetObject = this.CreateComObject(); string fullName = targetObject.GetType().FullName; if (!fullName.Equals("System.__ComObject")) { exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "ComInteropLoaded", new object[] { fullName }); base.WriteVerbose(exception.Message); if (this.Strict != 0) { base.WriteError(new ErrorRecord(exception, "ComInteropLoaded", ErrorCategory.InvalidArgument, targetObject)); } } if ((targetObject != null) && (this.property != null)) { targetObject = LanguagePrimitives.SetObjectProperties(targetObject, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true); } base.WriteObject(targetObject); } }
internal static IAstToWorkflowConverter GetAstToWorkflowConverterAndEnsureWorkflowModuleLoaded(ExecutionContext context) { IAstToWorkflowConverter converter = null; Type type = null; if (IsRunningFromSysWOW64()) { throw new NotSupportedException(AutomationExceptions.WorkflowDoesNotSupportWOW64); } if (((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)) { throw new NotSupportedException(Modules.CannotDefineWorkflowInconsistentLanguageMode); } if ((context != null) && !context.PSWorkflowModuleLoadingInProgress) { context.PSWorkflowModuleLoadingInProgress = true; List <PSModuleInfo> modules = context.Modules.GetModules(new string[] { "PSWorkflow" }, false); if ((modules == null) || (modules.Count == 0)) { CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context); Command command = new Command(commandInfo); try { PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", "PSWorkflow").AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke <PSModuleInfo>(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { converter = (IAstToWorkflowConverter)type.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); } if (converter == null) { throw new NotSupportedException(StringUtil.Format(AutomationExceptions.CantLoadWorkflowType, "Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "PSWorkflow")); } return(converter); }
protected override void BeginProcessing() { if (base.Context.InternalHost.ExternalHost is ServerRemoteHost) { base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(UtilityDebuggerStrings.RemoteDebuggerNotSupported), "SetPSBreakpoint:RemoteDebuggerNotSupported", ErrorCategory.NotImplemented, null)); } if ((base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)) { base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(UtilityDebuggerStrings.RemoteDebuggerNotSupported), "CannotSetBreakpointInconsistentLanguageMode", ErrorCategory.PermissionDenied, base.Context.LanguageMode)); } }
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason) { bool policyCheckPassed = false; reason = null; string path = script.Path; string reasonMessage; // path is assumed to be fully qualified here if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0) { throw PSTraceSource.NewArgumentException("path"); } if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1)) { throw PSTraceSource.NewArgumentException("path"); } FileInfo fi = new FileInfo(path); // Return false if the file does not exist, so that // we don't introduce a race condition if (!fi.Exists) { reason = new FileNotFoundException(path); return(false); } // Quick exit if we don't support the file type if (!IsSupportedExtension(fi.Extension)) { return(true); } // Get the execution policy _executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId); // See if they want to bypass the authorization manager if (_executionPolicy == ExecutionPolicy.Bypass) { return(true); } // Always check the SAFER APIs if code integrity isn't being handled system-wide through // WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage. // Otherwise, block. // SAFER APIs are not on CSS or OneCore if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) { SaferPolicy saferPolicy = SaferPolicy.Disallowed; int saferAttempt = 0; bool gotSaferPolicy = false; // We need to put in a retry workaround, as the SAFER APIs fail when under stress. while ((!gotSaferPolicy) && (saferAttempt < 5)) { try { saferPolicy = SecuritySupport.GetSaferPolicy(path, null); gotSaferPolicy = true; } catch (System.ComponentModel.Win32Exception) { if (saferAttempt > 4) { throw; } saferAttempt++; System.Threading.Thread.Sleep(100); } } // If the script is disallowed via AppLocker, block the file // unless the system-wide lockdown policy is "Enforce" (where all PowerShell // scripts are in blocked). If the system policy is "Enforce", then the // script will be allowed (but ConstrainedLanguage will be applied). if (saferPolicy == SaferPolicy.Disallowed) { reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } } if (_executionPolicy == ExecutionPolicy.Unrestricted) { // Product binaries are always trusted // This avoids signature and security zone checks if (SecuritySupport.IsProductBinary(path)) { return(true); } // We need to give the "Remote File" warning // if the file originated from the internet if (!IsLocalFile(fi.FullName)) { // Get the signature of the file. if (String.IsNullOrEmpty(script.ScriptContents)) { reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed, with a publisher that // we trust if (signature.Status == SignatureStatus.Valid) { // The file is signed by a trusted publisher if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } } // We don't care about the signature. If you distrust them, // or the signature does not exist, we prompt you only // because it's remote. if (!policyCheckPassed) { RunPromptDecision decision = RunPromptDecision.DoNotRun; // Get their remote prompt answer, allowing them to // enter nested prompts, if wanted. do { decision = RemoteFilePrompt(path, host); if (decision == RunPromptDecision.Suspend) { host.EnterNestedPrompt(); } } while (decision == RunPromptDecision.Suspend); switch (decision) { case RunPromptDecision.RunOnce: policyCheckPassed = true; break; case RunPromptDecision.DoNotRun: default: policyCheckPassed = false; reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path); reason = new UnauthorizedAccessException(reasonMessage); break; } } } else { policyCheckPassed = true; } } // Don't need to check the signature if the file is local // and we're in "RemoteSigned" mode else if ((IsLocalFile(fi.FullName)) && (_executionPolicy == ExecutionPolicy.RemoteSigned)) { policyCheckPassed = true; } else if ((_executionPolicy == ExecutionPolicy.AllSigned) || (_executionPolicy == ExecutionPolicy.RemoteSigned)) { // if policy requires signature verification, // make it so. // Get the signature of the file. if (String.IsNullOrEmpty(script.ScriptContents)) { reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(reasonMessage); return(false); } Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed. if (signature.Status == SignatureStatus.Valid) { // The file is signed by a trusted publisher if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } // The file is signed by an unknown publisher, // So prompt. else { policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature); } } // The file is UnknownError, NotSigned, HashMismatch, // NotTrusted, NotSupportedFileFormat else { policyCheckPassed = false; if (signature.Status == SignatureStatus.NotTrusted) { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_NotTrusted, path, signature.SignerCertificate.SubjectName.Name)); } else { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_Unknown, path, signature.StatusMessage)); } } } else // if(executionPolicy == ExecutionPolicy.Restricted) { // Deny everything policyCheckPassed = false; // But accept mshxml files from publishers that we // trust, or files in the system protected directories bool reasonSet = false; if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] trustedDirectories = new string[] { Platform.GetFolderPath(Environment.SpecialFolder.System), Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; foreach (string trustedDirectory in trustedDirectories) { if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase)) { policyCheckPassed = true; } } if (!policyCheckPassed) { // Get the signature of the file. Signature signature = GetSignatureWithEncodingRetry(path, script); // The file is signed by a trusted publisher if (signature.Status == SignatureStatus.Valid) { if (IsTrustedPublisher(signature, path)) { policyCheckPassed = true; } // The file is signed by an unknown publisher, // So prompt. else { policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature); reasonSet = true; } } } } if (!policyCheckPassed && !reasonSet) { reason = new UnauthorizedAccessException( StringUtil.Format(Authenticode.Reason_RestrictedMode, path)); } } return(policyCheckPassed); }
/// <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)); } }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> /// <param name="currentLocationPath"></param> /// <param name="streamingHost"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet, string currentLocationPath, PSHost streamingHost) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); _streamingHost = streamingHost; _currentLocationPath = currentLocationPath; this.PSJobTypeName = "ThreadJob"; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.NoScriptToRun); } // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); // Determine session language mode for Windows platforms WarningRecord lockdownWarning = null; if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce); if (enforceLockdown && !string.IsNullOrEmpty(_filePath)) { // If script source is a file, check to see if it is trusted by the lock down policy enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce); if (!enforceLockdown && (_initSb != null)) { // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce // lock down. Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script. enforceLockdown = true; lockdownWarning = new WarningRecord( string.Format( CultureInfo.InvariantCulture, Properties.Resources.CannotRunTrustedFileInFL, _filePath)); } } iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } if (_streamingHost != null) { _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss); } else { _rs = RunspaceFactory.CreateRunspace(iss); } _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; if (lockdownWarning != null) { this.Warning.Add(lockdownWarning); } this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Information = _ps.Streams.Information; this.Information.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }