// Check the signature via the SIP which should never erroneously validate an invalid signature // or altered script. private static Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) { // Invoke the SIP directly with the most simple method Signature signature = SignatureHelper.GetSignature(path, fileContent: null); if (signature.Status == SignatureStatus.Valid) { return(signature); } // try harder to validate the signature by being explicit about encoding // and providing the script contents string verificationContents = Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; signature = SignatureHelper.GetSignature(path, verificationContents); // A last ditch effort - // If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM if (signature.Status != SignatureStatus.Valid && script.OriginalEncoding != Encoding.Unicode) { verificationContents = Encoding.Unicode.GetString(Encoding.Unicode.GetPreamble()) + script.ScriptContents; Signature fallbackSignature = SignatureHelper.GetSignature(path, verificationContents); if (fallbackSignature.Status == SignatureStatus.Valid) { signature = fallbackSignature; } } return(signature); }
private Collection <PSObject> ExecuteScriptInSessionState(string path, SessionState sessionState) { var scriptBlock = new ExternalScriptInfo(path, ScopeUsages.CurrentScope).ScriptBlock; var originalContext = _executionContext; var scopedContext = _executionContext.Clone(sessionState, ScopeUsages.CurrentScope); try { // actually change the scope by changing the execution context // there should definitely be a nicer way for this #ExecutionContextChange _executionContext = scopedContext; _executionContext.CurrentRunspace.ExecutionContext = scopedContext; return(scriptBlock.Invoke()); // TODO: pass parameters if set } catch (ExitException e) { var exitCode = LanguagePrimitives.ConvertTo <int>(e.Argument); _executionContext.SetLastExitCodeVariable(exitCode); _executionContext.SetSuccessVariable(exitCode == 0); return(new Collection <PSObject>() { PSObject.AsPSObject(e.Argument) }); } finally { // restore original context / scope _executionContext.CurrentRunspace.ExecutionContext = originalContext; _executionContext = originalContext; } }
internal DISCPowerShellConfiguration(string configFile) { this.configFile = configFile; Runspace defaultRunspace = Runspace.DefaultRunspace; try { string str; Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace(); Runspace.DefaultRunspace.Open(); ExternalScriptInfo scriptInfo = DISCUtils.GetScriptInfoForFile(Runspace.DefaultRunspace.ExecutionContext, configFile, out str); this.configHash = DISCUtils.LoadConfigFile(Runspace.DefaultRunspace.ExecutionContext, scriptInfo); Runspace.DefaultRunspace.Close(); } catch (PSSecurityException exception) { PSInvalidOperationException exception2 = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, configFile), exception); exception2.SetErrorId("InvalidPSSessionConfigurationFilePath"); throw exception2; } finally { Runspace.DefaultRunspace = defaultRunspace; } }
protected internal override bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason) { bool flag = false; reason = null; Utils.CheckArgForNull(commandInfo, "commandInfo"); Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name"); CommandTypes commandType = commandInfo.CommandType; if (commandType <= CommandTypes.ExternalScript) { switch (commandType) { case CommandTypes.Alias: return(true); case CommandTypes.Function: case CommandTypes.Filter: goto Label_006C; case (CommandTypes.Function | CommandTypes.Alias): return(flag); case CommandTypes.Cmdlet: return(true); case CommandTypes.ExternalScript: { ExternalScriptInfo script = commandInfo as ExternalScriptInfo; if (script == null) { reason = PSTraceSource.NewArgumentException("scriptInfo"); return(flag); } return(this.CheckPolicy(script, host, out reason)); } } return(flag); } switch (commandType) { case CommandTypes.Application: return(true); case CommandTypes.Script: return(true); case CommandTypes.Workflow: break; default: return(flag); } Label_006C: return(true); }
/// <summary> /// Parse input from the specified file. /// </summary> /// <param name="fileName">The name of the file to parse.</param> /// <param name="tokens">Returns the tokens from parsing the script.</param> /// <param name="errors">Returns errors, if any, discovered while parsing the script.</param> /// <returns>The <see cref="ScriptBlockAst"/> that represents the input script file.</returns> public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out ParseError[] errors) { const string scriptSchemaExtension = ".schema.psm1"; var parseDscResource = false; // If the file has the 'schema.psm1' extension, then it is a 'DSC module file' however we don't actually load the // module at parse time so we can't use the normal mechanisms to bind the module name for configuration commands. // As an alternative, we extract the base name of the module file and use that as the module name for any keywords exported by this file. var parser = new Parser(); if (!string.IsNullOrEmpty(fileName) && fileName.Length > scriptSchemaExtension.Length && fileName.EndsWith(scriptSchemaExtension, StringComparison.OrdinalIgnoreCase)) { parser._keywordModuleName = Path.GetFileName(fileName.Substring(0, fileName.Length - scriptSchemaExtension.Length)); parseDscResource = true; } string scriptContents; try { var esi = new ExternalScriptInfo(fileName, fileName); scriptContents = esi.ScriptContents; } catch (Exception e) { var emptyExtent = new EmptyScriptExtent(); var errorMsg = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileReadError, e.Message); errors = new[] { new ParseError(emptyExtent, "FileReadError", errorMsg) }; tokens = Utils.EmptyArray<Token>(); return new ScriptBlockAst(emptyExtent, null, new StatementBlockAst(emptyExtent, null, null), false); } var tokenList = new List<Token>(); ScriptBlockAst result; try { if (!parseDscResource) { DynamicKeyword.Push(); } result = parser.Parse(fileName, scriptContents, tokenList, out errors, ParseMode.Default); } catch (Exception e) { throw new ParseException(ParserStrings.UnrecoverableParserError, e); } finally { if (!parseDscResource) { DynamicKeyword.Pop(); } } tokens = tokenList.ToArray(); return result; }
internal static ExternalScriptInfo GetScriptInfoForFile(ExecutionContext context, string fileName, out string scriptName) { scriptName = Path.GetFileName(fileName); ExternalScriptInfo commandInfo = new ExternalScriptInfo(scriptName, fileName, context); if (!scriptName.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) { context.AuthorizationManager.ShouldRunInternal(commandInfo, CommandOrigin.Internal, context.EngineHostInterface); CommandDiscovery.VerifyPSVersion(commandInfo); commandInfo.SignatureChecked = true; } return(commandInfo); }
protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted) { // get file contents ExternalScriptInfo ps1xmlInfo = new ExternalScriptInfo(FilePath, FilePath); string fileContents = ps1xmlInfo.ScriptContents; isFullyTrusted = false; if (ps1xmlInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) { isFullyTrusted = true; } if (authorizationManager != null) { try { authorizationManager.ShouldRunInternal(ps1xmlInfo, CommandOrigin.Internal, host); } catch (PSSecurityException reason) { string errorMessage = StringUtil.Format(TypesXmlStrings.ValidationException, string.Empty /* TODO/FIXME snapin */, FilePath, reason.Message); ReportLogEntryHelper(errorMessage, XmlLoaderLoggerEntry.EntryType.Error, failToLoadFile: true); return(null); } } // load file into XML document try { XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument( fileContents, true, /* preserve whitespace, comments, etc. */ null); /* default maxCharacters */ this.ReportTrace("XmlDocument loaded OK"); return(doc); } catch (XmlException e) { this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, FilePath, e.Message)); this.ReportTrace("XmlDocument discarded"); return(null); } catch (Exception e) // will rethrow { CommandProcessor.CheckForSevereException(e); throw; } }
private System.Management.Automation.Signature GetSignatureWithEncodingRetry( string path, ExternalScriptInfo script) { string fileContent1 = Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; System.Management.Automation.Signature signature1 = SignatureHelper.GetSignature(path, fileContent1); if (signature1.Status != SignatureStatus.Valid && script.OriginalEncoding != Encoding.Unicode) { string fileContent2 = Encoding.Unicode.GetString(Encoding.Unicode.GetPreamble()) + script.ScriptContents; System.Management.Automation.Signature signature2 = SignatureHelper.GetSignature(path, fileContent2); if (signature2.Status == SignatureStatus.Valid) { signature1 = signature2; } } return(signature1); }
private bool IsDuplicate(CommandInfo info) { string key = null; ApplicationInfo info2 = info as ApplicationInfo; if (info2 != null) { key = info2.Path; } else { CmdletInfo info3 = info as CmdletInfo; if (info3 != null) { key = info3.FullName; } else { ScriptInfo info4 = info as ScriptInfo; if (info4 != null) { key = info4.Definition; } else { ExternalScriptInfo info5 = info as ExternalScriptInfo; if (info5 != null) { key = info5.Path; } } } } if (key != null) { if (this.commandsWritten.ContainsKey(key)) { return(true); } this.commandsWritten.Add(key, info); } return(false); }
internal static Hashtable LoadConfigFile(ExecutionContext context, ExternalScriptInfo scriptInfo) { object obj2; object variableValue = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); object newValue = context.GetVariableValue(SpecialVariables.PSCommandPathVarPath); try { context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(scriptInfo.Definition)); context.SetVariable(SpecialVariables.PSCommandPathVarPath, scriptInfo.Definition); obj2 = PSObject.Base(scriptInfo.ScriptBlock.InvokeReturnAsIs(new object[0])); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, variableValue); context.SetVariable(SpecialVariables.PSCommandPathVarPath, newValue); } return(obj2 as Hashtable); }
protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager authorizationManager, PSHost host, out bool isFullyTrusted) { XmlDocument document2; ExternalScriptInfo commandInfo = new ExternalScriptInfo(this.FilePath, this.FilePath); string scriptContents = commandInfo.ScriptContents; isFullyTrusted = false; if (((PSLanguageMode)commandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) { isFullyTrusted = true; } if (authorizationManager != null) { try { authorizationManager.ShouldRunInternal(commandInfo, CommandOrigin.Internal, host); } catch (PSSecurityException exception) { string message = StringUtil.Format(TypesXmlStrings.ValidationException, new object[] { string.Empty, this.FilePath, exception.Message }); this.ReportLogEntryHelper(message, XmlLoaderLoggerEntry.EntryType.Error, true); return(null); } } try { XmlDocument document = InternalDeserializer.LoadUnsafeXmlDocument(scriptContents, true, null); this.ReportTrace("XmlDocument loaded OK"); document2 = document; } catch (XmlException exception2) { this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ErrorInFile, this.FilePath, exception2.Message)); this.ReportTrace("XmlDocument discarded"); document2 = null; } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); throw; } return(document2); }
protected System.Management.Automation.ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath) { if (!isLiteralPath && WildcardPattern.ContainsWildcardCharacters(filePath)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter, new object[0]), "filePath"); } if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension, new object[0]), "filePath"); } string path = new PathResolver().ResolveProviderAndPath(filePath, isLiteralPath, this, false, "RemotingErrorIdStrings", PSRemotingErrorId.FilePathNotFromFileSystemProvider.ToString()); ExternalScriptInfo commandInfo = new ExternalScriptInfo(filePath, path, base.Context); if (!filePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) { base.Context.AuthorizationManager.ShouldRunInternal(commandInfo, CommandOrigin.Internal, base.Context.EngineHostInterface); } return(commandInfo.ScriptBlock); }
private Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) { string verificationContents = System.Text.Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; Signature signature = SignatureHelper.GetSignature(path, verificationContents); // If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM if ((signature.Status != SignatureStatus.Valid) && (script.OriginalEncoding != System.Text.Encoding.Unicode)) { verificationContents = System.Text.Encoding.Unicode.GetString(System.Text.Encoding.Unicode.GetPreamble()) + script.ScriptContents; Signature fallbackSignature = SignatureHelper.GetSignature(path, verificationContents); if (fallbackSignature.Status == SignatureStatus.Valid) { signature = fallbackSignature; } } return(signature); }
protected XmlDocument LoadXmlDocumentFromFileLoadingInfo( AuthorizationManager authorizationManager, PSHost host) { ExternalScriptInfo externalScriptInfo = new ExternalScriptInfo(this.FilePath, this.FilePath); string scriptContents = externalScriptInfo.ScriptContents; if (authorizationManager != null) { try { authorizationManager.ShouldRunInternal((CommandInfo)externalScriptInfo, CommandOrigin.Internal, host); } catch (PSSecurityException ex) { this.ReportError(ResourceManagerCache.FormatResourceString("TypesXml", "ValidationException", (object)string.Empty, (object)this.FilePath, (object)ex.Message)); return((XmlDocument)null); } } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; try { using (StringReader stringReader = new StringReader(scriptContents)) xmlDocument.Load((TextReader)stringReader); } catch (XmlException ex) { this.ReportError(XmlLoadingResourceManager.FormatString("ErrorInFile", (object)this.FilePath, (object)ex.Message)); this.ReportTrace("XmlDocument discarded"); return((XmlDocument)null); } catch (Exception ex) { XmlLoaderBase.tracer.TraceException(ex); CommandProcessorBase.CheckForSevereException(ex); throw; } this.ReportTrace("XmlDocument loaded OK"); return(xmlDocument); }
/// <summary> /// </summary> protected override void ProcessRecord() { ProviderInfo provider = null; Collection <string> filePaths; try { if (this.Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem)) { filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider); } else { filePaths = new Collection <string>(); filePaths.Add(_path); } } catch (ItemNotFoundException) { string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } // Make sure that the path is in the file system - that's all we can handle currently... if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { // "The current provider ({0}) cannot open a file" throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName); } // Make sure at least one file was found... if (filePaths == null || filePaths.Count < 1) { string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } if (filePaths.Count > 1) { // "The path resolved to more than one file; can only process one file at a time." throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath); } string filePath = filePaths[0]; ExternalScriptInfo scriptInfo = null; string ext = System.IO.Path.GetExtension(filePath); if (ext.Equals(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase)) { // Create a script info for loading the file... string scriptName; scriptInfo = DISCUtils.GetScriptInfoForFile(this.Context, filePath, out scriptName); Hashtable configTable = null; try { configTable = DISCUtils.LoadConfigFile(this.Context, scriptInfo); } catch (RuntimeException e) { WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCErrorParsingConfigFile, filePath, e.Message)); WriteObject(false); return; } if (configTable == null) { WriteObject(false); return; } DISCUtils.ExecutionPolicyType = typeof(ExecutionPolicy); WriteObject(DISCUtils.VerifyConfigTable(configTable, this, filePath)); } else { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, filePath); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } }
/// <summary> /// Determines if should run the specified command. Please see the /// class summary for an overview of the semantics enforced by this /// authorization manager. /// </summary> /// /// <param name="commandInfo"> /// The command to be run. /// </param> /// <param name="origin"> /// The origin of the command. /// </param> /// <param name="host"> /// The PSHost executing the command. /// </param> /// <param name="reason"> /// If access is denied, this parameter provides a specialized /// Exception as the reason. /// </param> /// /// <returns> /// True if the command should be run. False otherwise. /// </returns> /// /// <exception cref="System.ArgumentException"> /// CommandInfo is invalid. This may occur if /// commandInfo.Name is null or empty. /// </exception> /// /// <exception cref="System.ArgumentNullException"> /// CommandInfo is null. /// </exception> /// /// <exception cref="System.IO.FileNotFoundException"> /// The file specified by commandInfo.Path is not found. /// </exception> protected internal override bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason) { Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter"); bool allowRun = false; reason = null; Utils.CheckArgForNull(commandInfo, "commandInfo"); Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name"); switch (commandInfo.CommandType) { case CommandTypes.Cmdlet: // Always allow cmdlets to run allowRun = true; break; case CommandTypes.Alias: // // we do not care about verifying an alias as we will // get subsequent call(s) for commands/scripts // when the alias is expanded. // allowRun = true; break; case CommandTypes.Function: case CommandTypes.Filter: case CommandTypes.Workflow: case CommandTypes.Configuration: // // we do not check functions/filters. // we only perform script level check. // allowRun = true; break; case CommandTypes.Script: // // Allow scripts that are built into the // runspace configuration to run. // allowRun = true; break; case CommandTypes.ExternalScript: ExternalScriptInfo si = commandInfo as ExternalScriptInfo; if (si == null) { reason = PSTraceSource.NewArgumentException("scriptInfo"); } else { bool etwEnabled = ParserEventSource.Log.IsEnabled(); if (etwEnabled) { ParserEventSource.Log.CheckSecurityStart(si.Path); } allowRun = CheckPolicy(si, host, out reason); if (etwEnabled) { ParserEventSource.Log.CheckSecurityStop(si.Path); } } break; case CommandTypes.Application: // // We do not check executables -- that is done by Windows // allowRun = true; break; } return(allowRun); }
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); }
protected override void ProcessRecord() { ProviderInfo provider = null; Collection <string> resolvedProviderPathFromPSPath; try { if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem)) { resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this.path, out provider); } else { resolvedProviderPathFromPSPath = new Collection <string> { this.path }; } } catch (ItemNotFoundException) { FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, this.path)); ErrorRecord errorRecord = new ErrorRecord(exception, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, this.path); base.WriteError(errorRecord); return; } if (!provider.NameEquals(base.Context.ProviderNames.FileSystem)) { throw InterpreterError.NewInterpreterException(this.path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName }); } if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1)) { if (resolvedProviderPathFromPSPath.Count > 1) { throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]); } string path = resolvedProviderPathFromPSPath[0]; ExternalScriptInfo scriptInfo = null; if (System.IO.Path.GetExtension(path).Equals(".pssc", StringComparison.OrdinalIgnoreCase)) { string str5; scriptInfo = DISCUtils.GetScriptInfoForFile(base.Context, path, out str5); Hashtable table = null; try { table = DISCUtils.LoadConfigFile(base.Context, scriptInfo); } catch (RuntimeException exception3) { base.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCErrorParsingConfigFile, path, exception3.Message)); base.WriteObject(false); return; } if (table == null) { base.WriteObject(false); } else { DISCUtils.ExecutionPolicyType = typeof(ExecutionPolicy); base.WriteObject(DISCUtils.VerifyConfigTable(table, this, path)); } } else { InvalidOperationException exception4 = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, path)); ErrorRecord record3 = new ErrorRecord(exception4, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path); base.ThrowTerminatingError(record3); } } else { FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, this.path)); ErrorRecord record2 = new ErrorRecord(exception2, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, this.path); base.WriteError(record2); } }
/// <summary> /// Implements the record processing for this cmdlet. /// </summary> protected override void ProcessRecord() { ProviderInfo provider = null; Collection <string> filePaths; try { if (Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem)) { filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider); } else { filePaths = new Collection <string>(); filePaths.Add(_path); } } catch (ItemNotFoundException) { string message = StringUtil.Format(Modules.ModuleNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } // Make sure that the path is in the file system - that's all we can handle currently... if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { // "The current provider ({0}) cannot open a file" throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName); } // Make sure at least one file was found... if (filePaths == null || filePaths.Count < 1) { string message = StringUtil.Format(Modules.ModuleNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, _path); WriteError(er); return; } if (filePaths.Count > 1) { // "The path resolved to more than one file; can only process one file at a time." throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath); } string filePath = filePaths[0]; ExternalScriptInfo scriptInfo = null; string ext = System.IO.Path.GetExtension(filePath); if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { // Create a script info for loading the file... string scriptName; scriptInfo = GetScriptInfoForFile(filePath, out scriptName, false); // we should reserve the Context.ModuleBeingProcessed unchanged after loadModuleManifest(), otherwise the module won't be importable next time. PSModuleInfo module; string _origModuleBeingProcessed = Context.ModuleBeingProcessed; try { module = LoadModuleManifest( scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings /* but don't stop on first error and don't load elements */, null, null, null, null); if (module != null) { // Validate file existence if (module.RequiredAssemblies != null) { foreach (string requiredAssembliespath in module.RequiredAssemblies) { if (!IsValidFilePath(requiredAssembliespath, module, true) && !IsValidGacAssembly(requiredAssembliespath)) { string errorMsg = StringUtil.Format(Modules.InvalidRequiredAssembliesInModuleManifest, requiredAssembliespath, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredAssembliesInModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } if (!HasValidRootModule(module)) { string errorMsg = StringUtil.Format(Modules.InvalidModuleManifest, module.RootModule, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidRootModuleInModuleManifest", ErrorCategory.InvalidArgument, _path); WriteError(errorRecord); } Hashtable data = null; Hashtable localizedData = null; bool containerErrors = false; LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors); ModuleSpecification[] nestedModules; GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules); if (nestedModules != null) { foreach (ModuleSpecification nestedModule in nestedModules) { if (!IsValidFilePath(nestedModule.Name, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILAssemblyExtension, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILExecutableExtension, module, true) && !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) && !IsValidGacAssembly(nestedModule.Name)) { Collection <PSModuleInfo> modules = GetModuleIfAvailable(nestedModule); if (0 == modules.Count) { string errorMsg = StringUtil.Format(Modules.InvalidNestedModuleinModuleManifest, nestedModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidNestedModuleinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } } ModuleSpecification[] requiredModules; GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules); if (requiredModules != null) { foreach (ModuleSpecification requiredModule in requiredModules) { var modules = GetModule(new[] { requiredModule.Name }, all: false, refresh: true); if (modules.Count == 0) { string errorMsg = StringUtil.Format(Modules.InvalidRequiredModulesinModuleManifest, requiredModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredModulesinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } string[] fileListPaths; GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths); if (fileListPaths != null) { foreach (string fileListPath in fileListPaths) { if (!IsValidFilePath(fileListPath, module, true)) { string errorMsg = StringUtil.Format(Modules.InvalidFilePathinModuleManifest, fileListPath, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidFilePathinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } ModuleSpecification[] moduleListModules; GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules); if (moduleListModules != null) { foreach (ModuleSpecification moduleListModule in moduleListModules) { var modules = GetModule(new[] { moduleListModule.Name }, all: false, refresh: true); if (modules.Count == 0) { string errorMsg = StringUtil.Format(Modules.InvalidModuleListinModuleManifest, moduleListModule.Name, filePath); var errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidModuleListinModuleManifest", ErrorCategory.ObjectNotFound, _path); WriteError(errorRecord); } } } if (module.CompatiblePSEditions.Any()) { // The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher. // Ensure that PowerShellVersion module manifest key value is '5.1' or higher. // var minimumRequiredPowerShellVersion = new Version(5, 1); if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) { string errorMsg = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path); WriteError(errorRecord); } } } } finally { Context.ModuleBeingProcessed = _origModuleBeingProcessed; } DirectoryInfo parent = null; try { parent = Directory.GetParent(filePath); } catch (IOException) { } catch (UnauthorizedAccessException) { } catch (ArgumentException) { } Version version; if (parent != null && Version.TryParse(parent.Name, out version)) { if (!version.Equals(module.Version)) { string message = StringUtil.Format(Modules.InvalidModuleManifestVersion, filePath, module.Version.ToString(), parent.FullName); var ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion", ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder); } if (module != null) { WriteObject(module); } } else { string message = StringUtil.Format(Modules.InvalidModuleManifestPath, filePath); InvalidOperationException ioe = new InvalidOperationException(message); ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, _path); ThrowTerminatingError(er); } }
protected override void ProcessRecord() { ProviderInfo provider = null; Collection <string> resolvedProviderPathFromPSPath; try { if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem)) { resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider); } else { resolvedProviderPathFromPSPath = new Collection <string> { this._path }; } } catch (ItemNotFoundException) { FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(errorRecord); return; } if (!provider.NameEquals(base.Context.ProviderNames.FileSystem)) { throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName }); } if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1)) { if (resolvedProviderPathFromPSPath.Count > 1) { throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]); } string path = resolvedProviderPathFromPSPath[0]; ExternalScriptInfo scriptInfo = null; if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase)) { string str5; scriptInfo = base.GetScriptInfoForFile(path, out str5, false); PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null); if (sendToPipeline != null) { base.WriteObject(sendToPipeline); } } else { InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path)); ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path); base.ThrowTerminatingError(record3); } } else { FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(record2); } }
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason) { string str2; bool flag = false; reason = null; string path = script.Path; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { if (path.IndexOf('\\') < 0) { throw PSTraceSource.NewArgumentException("path"); } if (path.LastIndexOf('\\') == (path.Length - 1)) { throw PSTraceSource.NewArgumentException("path"); } } FileInfo info = new FileInfo(path); if (!info.Exists) { reason = new FileNotFoundException(path); return(false); } if (!IsSupportedExtension(info.Extension)) { return(true); } if (this.IsProductBinary(path)) { return(true); } this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId); if (this.executionPolicy == ExecutionPolicy.Bypass) { return(true); } SaferPolicy disallowed = SaferPolicy.Disallowed; int num = 0; bool flag2 = false; while (!flag2 && (num < 5)) { try { disallowed = SecuritySupport.GetSaferPolicy(path); flag2 = true; continue; } catch (Win32Exception) { if (num > 4) { throw; } num++; Thread.Sleep(100); continue; } } if (disallowed == SaferPolicy.Disallowed) { str2 = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path); reason = new UnauthorizedAccessException(str2); return(false); } if (this.executionPolicy != ExecutionPolicy.Unrestricted) { if (this.IsLocalFile(info.FullName) && (this.executionPolicy == ExecutionPolicy.RemoteSigned)) { return(true); } if ((this.executionPolicy == ExecutionPolicy.AllSigned) || (this.executionPolicy == ExecutionPolicy.RemoteSigned)) { if (string.IsNullOrEmpty(script.ScriptContents)) { str2 = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(str2); return(false); } System.Management.Automation.Signature signature = this.GetSignatureWithEncodingRetry(path, script); if (signature.Status == SignatureStatus.Valid) { return(this.IsTrustedPublisher(signature, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature)); } flag = false; if (signature.Status == SignatureStatus.NotTrusted) { reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_NotTrusted, path, signature.SignerCertificate.SubjectName.Name)); return(flag); } reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_Unknown, path, signature.StatusMessage)); return(flag); } flag = false; bool flag3 = false; if (string.Equals(info.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] strArray = new string[] { Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; foreach (string str3 in strArray) { if (info.FullName.StartsWith(str3, StringComparison.OrdinalIgnoreCase)) { flag = true; } } if (!flag) { System.Management.Automation.Signature signature3 = this.GetSignatureWithEncodingRetry(path, script); if (signature3.Status == SignatureStatus.Valid) { if (this.IsTrustedPublisher(signature3, path)) { flag = true; } else { flag = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature3); flag3 = true; } } } } if (!flag && !flag3) { reason = new UnauthorizedAccessException(StringUtil.Format(Authenticode.Reason_RestrictedMode, path)); } return(flag); } if (this.IsLocalFile(info.FullName)) { return(true); } if (string.IsNullOrEmpty(script.ScriptContents)) { str2 = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path); reason = new UnauthorizedAccessException(str2); return(false); } System.Management.Automation.Signature signatureWithEncodingRetry = this.GetSignatureWithEncodingRetry(path, script); if ((signatureWithEncodingRetry.Status == SignatureStatus.Valid) && this.IsTrustedPublisher(signatureWithEncodingRetry, path)) { flag = true; } if (flag) { return(flag); } RunPromptDecision doNotRun = RunPromptDecision.DoNotRun; Label_0149: doNotRun = this.RemoteFilePrompt(path, host); if (doNotRun == RunPromptDecision.Suspend) { host.EnterNestedPrompt(); } switch (doNotRun) { case RunPromptDecision.RunOnce: return(true); case RunPromptDecision.Suspend: goto Label_0149; } flag = false; str2 = StringUtil.Format(Authenticode.Reason_DoNotRun, path); reason = new UnauthorizedAccessException(str2); return(flag); }
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason) { bool flag1 = false; reason = (Exception)null; string path = script.Path; if (path.IndexOf('\\') < 0) { throw PSAuthorizationManager.tracer.NewArgumentException("path"); } FileInfo fileInfo = path.LastIndexOf('\\') != path.Length - 1 ? new FileInfo(path) : throw PSAuthorizationManager.tracer.NewArgumentException("path"); if (!fileInfo.Exists) { return(false); } if (!PSAuthorizationManager.IsSupportedExtension(fileInfo.Extension) || this.IsProductBinary(path)) { return(true); } this.executionPolicy = SecuritySupport.GetExecutionPolicy(this.shellId); if (this.executionPolicy == ExecutionPolicy.Bypass) { return(true); } if (SecuritySupport.GetSaferPolicy(path) == SaferPolicy.Disallowed) { string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DisallowedBySafer", (object)path); reason = (Exception) new UnauthorizedAccessException(message); return(false); } if (this.executionPolicy == ExecutionPolicy.Unrestricted) { if (!this.IsLocalFile(fileInfo.FullName)) { if (string.IsNullOrEmpty(script.ScriptContents)) { string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path); reason = (Exception) new UnauthorizedAccessException(message); return(false); } System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script); if (withEncodingRetry.Status == SignatureStatus.Valid && this.IsTrustedPublisher(withEncodingRetry, path)) { flag1 = true; } if (!flag1) { PSAuthorizationManager.RunPromptDecision runPromptDecision; do { runPromptDecision = this.RemoteFilePrompt(path, host); if (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend) { host.EnterNestedPrompt(); } }while (runPromptDecision == PSAuthorizationManager.RunPromptDecision.Suspend); switch (runPromptDecision - 1) { case PSAuthorizationManager.RunPromptDecision.DoNotRun: flag1 = true; break; default: flag1 = false; string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_DoNotRun", (object)path); reason = (Exception) new UnauthorizedAccessException(message); break; } } } else { flag1 = true; } } else if (this.IsLocalFile(fileInfo.FullName) && this.executionPolicy == ExecutionPolicy.RemoteSigned) { flag1 = true; } else if (this.executionPolicy == ExecutionPolicy.AllSigned || this.executionPolicy == ExecutionPolicy.RemoteSigned) { if (string.IsNullOrEmpty(script.ScriptContents)) { string message = ResourceManagerCache.FormatResourceString("Authenticode", "Reason_FileContentUnavailable", (object)path); reason = (Exception) new UnauthorizedAccessException(message); return(false); } System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script); if (withEncodingRetry.Status == SignatureStatus.Valid) { flag1 = this.IsTrustedPublisher(withEncodingRetry, path) || this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry); } else { flag1 = false; if (withEncodingRetry.Status == SignatureStatus.NotTrusted) { reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_NotTrusted", (object)path, (object)withEncodingRetry.SignerCertificate.SubjectName.Name)); } else { reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_Unknown", (object)path, (object)withEncodingRetry.StatusMessage)); } } } else { flag1 = false; bool flag2 = false; if (string.Equals(fileInfo.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] strArray = new string[2] { Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) }; foreach (string str in strArray) { if (fileInfo.FullName.StartsWith(str, StringComparison.OrdinalIgnoreCase)) { flag1 = true; } } if (!flag1) { System.Management.Automation.Signature withEncodingRetry = this.GetSignatureWithEncodingRetry(path, script); if (withEncodingRetry.Status == SignatureStatus.Valid) { if (this.IsTrustedPublisher(withEncodingRetry, path)) { flag1 = true; } else { flag1 = this.SetPolicyFromAuthenticodePrompt(path, host, ref reason, withEncodingRetry); flag2 = true; } } } } if (!flag1 && !flag2) { reason = (Exception) new UnauthorizedAccessException(ResourceManagerCache.FormatResourceString("Authenticode", "Reason_RestrictedMode", (object)path)); } } return(flag1); }