private static CommandProcessorBase CreateCommandProcessorForScript( ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope) { return(CommandDiscovery.GetScriptAsCmdletProcessor((IScriptCommandInfo)scriptInfo, context, useNewScope, true) ?? (CommandProcessorBase) new ScriptCommandProcessor(scriptInfo, context, useNewScope)); }
private HelpCommentsParser(CommandInfo commandInfo, List <string> parameterDescriptions) { this._sections = new CommentHelpInfo(); this._parameters = new Dictionary <string, string>(); this._examples = new List <string>(); this._inputs = new List <string>(); this._outputs = new List <string>(); this._links = new List <string>(); FunctionInfo info = commandInfo as FunctionInfo; if (info != null) { this.scriptBlock = info.ScriptBlock; this.commandName = info.Name; } else { ExternalScriptInfo info2 = commandInfo as ExternalScriptInfo; if (info2 != null) { this.scriptBlock = info2.ScriptBlock; this.commandName = info2.Path; } } this.commandMetadata = commandInfo.CommandMetadata; this.parameterDescriptions = parameterDescriptions; }
private bool CommandInfoMatches(CommandInfo commandInfo) { if (commandInfo != null) { if (this.CommandPattern.IsMatch(commandInfo.Name)) { return(true); } if ((!string.IsNullOrEmpty(commandInfo.ModuleName) && (this.Command.IndexOf('\\') != -1)) && this.CommandPattern.IsMatch(commandInfo.ModuleName + @"\" + commandInfo.Name)) { return(true); } ExternalScriptInfo info = commandInfo as ExternalScriptInfo; if (info != null) { if (info.Path.Equals(this.Command, StringComparison.OrdinalIgnoreCase)) { return(true); } if (this.CommandPattern.IsMatch(Path.GetFileNameWithoutExtension(info.Path))) { return(true); } } } return(false); }
private void EnterScriptFunction(FunctionContext functionContext) { InvocationInfo automaticVariable = (InvocationInfo)functionContext._localsTuple.GetAutomaticVariable(AutomaticVariable.MyInvocation); ScriptBlock block = functionContext._scriptBlock; CallStackInfo item = new CallStackInfo { InvocationInfo = automaticVariable, ScriptBlock = block, FunctionContext = functionContext, IsFrameHidden = block.DebuggerHidden }; this._callStack.Add(item); if (this._context._debuggingMode > 0) //TODO: REVIEW: Why was 0?? { ExternalScriptInfo myCommand = automaticVariable.MyCommand as ExternalScriptInfo; if (myCommand != null) { this.RegisterScriptFile(myCommand); } bool flag = this.CheckCommand(automaticVariable); this.SetupBreakpoints(functionContext); if ((block.DebuggerStepThrough && (this._overOrOutFrame == null)) && (this._steppingMode == SteppingMode.StepIn)) { this.ResumeExecution(DebuggerResumeAction.StepOut); } if (flag) { this.OnSequencePointHit(functionContext); } if (((this._context.PSDebugTraceLevel > 1) && !block.DebuggerStepThrough) && !block.DebuggerHidden) { this.TraceScriptFunctionEntry(functionContext); } } }
internal CommandProcessorBase CreateScriptProcessorForMiniShell( ExternalScriptInfo scriptInfo, bool useLocalScope) { CommandDiscovery.VerifyPSVersion(scriptInfo); if (string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { if (scriptInfo.RequiresPSSnapIns != null && scriptInfo.RequiresPSSnapIns.Count > 0) { Collection <string> psSnapinNames = this.GetPSSnapinNames(scriptInfo.RequiresPSSnapIns); ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, psSnapinNames, "ScriptRequiresMissingPSSnapIns"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } return(CommandDiscovery.CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope)); } if (string.Equals(this._context.ShellID, scriptInfo.RequiresApplicationID, StringComparison.OrdinalIgnoreCase)) { return(CommandDiscovery.CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope)); } string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(scriptInfo.RequiresApplicationID); ScriptRequiresException requiresException1 = new ScriptRequiresException(scriptInfo.Name, scriptInfo.ApplicationIDLineNumber, scriptInfo.RequiresApplicationID, pathFromRegistry, "ScriptRequiresUnmatchedShellId"); CommandDiscovery.tracer.TraceException((Exception)requiresException1); throw requiresException1; }
internal ScriptCommandProcessor( ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope) : base((CommandInfo)scriptInfo) { this.Context = context; this.FromScriptFile = true; this._rethrowExitException = this.Context.ScriptCommandProcessorShouldRethrowExit; this.Context.ScriptCommandProcessorShouldRethrowExit = false; this._scriptBlock = scriptInfo.ScriptBlock; this._dontUseScopeCommandOrigin = true; this.SetupCommand(); if (this._scriptBlock.SessionStateInternal != null) { this.CommandSessionState = this._scriptBlock.SessionStateInternal; } if (!useLocalScope) { return; } this.UseLocalScope = useLocalScope; if (this.CommandSessionState == null) { this.CommandSessionState = context.EngineSessionState; } this.CommandScope = this.CommandSessionState.NewScope(this.FromScriptFile); }
/// <summary> /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter /// sets based on an argument list (so we can get the dynamic parameters.) /// </summary> internal override CommandInfo CreateGetCommandCopy(object[] argumentList) { ExternalScriptInfo copy = new ExternalScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList }; return(copy); }
internal PSModuleInfo CreateModule( string path, ExternalScriptInfo scriptInfo, Token callerToken, SessionState ss, params object[] arguments) { return(this.CreateModuleImplementation(ModuleIntrinsics.GetModuleName(path), path, (object)scriptInfo, callerToken, ss, out ArrayList _, arguments)); }
internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) { Version requiresPsVersion = scriptInfo.RequiresPSVersion; if (requiresPsVersion != (Version)null && !Utils.IsVersionSupported(requiresPsVersion)) { ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, scriptInfo.PSVersionLineNumber, requiresPsVersion, PSVersionInfo.PSVersion.ToString(), "ScriptRequiresUnmatchedPSVersion"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } }
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; }
public CommandMetadata(string path) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection <Attribute>(); ExternalScriptInfo info = new ExternalScriptInfo(Path.GetFileName(path), path); this.Init(info.ScriptBlock, path, false); this._wrappedCommandType = CommandTypes.ExternalScript; }
public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection <Attribute>(); if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException("commandInfo"); } while (commandInfo is AliasInfo) { commandInfo = ((AliasInfo)commandInfo).ResolvedCommand; if (commandInfo == null) { throw PSTraceSource.NewNotSupportedException(); } } CmdletInfo info = commandInfo as CmdletInfo; if (info != null) { this.Init(commandInfo.Name, info.ImplementingType, shouldGenerateCommonParameters); } else { ExternalScriptInfo info2 = commandInfo as ExternalScriptInfo; if (info2 != null) { this.Init(info2.ScriptBlock, info2.Path, shouldGenerateCommonParameters); this._wrappedCommandType = CommandTypes.ExternalScript; } else { FunctionInfo info3 = commandInfo as FunctionInfo; if (info3 == null) { throw PSTraceSource.NewNotSupportedException(); } this.Init(info3.ScriptBlock, info3.Name, shouldGenerateCommonParameters); this._wrappedCommandType = commandInfo.CommandType; } } }
private CommandProcessorBase CreateScriptProcessorForSingleShell( ExternalScriptInfo scriptInfo, RunspaceConfigForSingleShell ssRunConfig, bool useLocalScope) { CommandDiscovery.VerifyPSVersion(scriptInfo); Collection <PSSnapInNameVersionPair> requiresPsSnapIns = scriptInfo.RequiresPSSnapIns; if (requiresPsSnapIns != null) { Collection <string> missingPSSnapIns = (Collection <string>)null; foreach (PSSnapInNameVersionPair PSSnapin in requiresPsSnapIns) { Collection <PSSnapInInfo> psSnapIn = ssRunConfig.ConsoleInfo.GetPSSnapIn(PSSnapin.PSSnapInName, false); if (psSnapIn == null || psSnapIn.Count == 0) { if (missingPSSnapIns == null) { missingPSSnapIns = new Collection <string>(); } missingPSSnapIns.Add(CommandDiscovery.BuildPSSnapInDisplayName(PSSnapin)); } else if (PSSnapin.Version != (Version)null && !CommandDiscovery.AreInstalledRequiresVersionsCompatible(PSSnapin.Version, psSnapIn[0].Version)) { if (missingPSSnapIns == null) { missingPSSnapIns = new Collection <string>(); } missingPSSnapIns.Add(CommandDiscovery.BuildPSSnapInDisplayName(PSSnapin)); } } if (missingPSSnapIns != null) { ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, missingPSSnapIns, "ScriptRequiresMissingPSSnapIns"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } } else if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { CommandDiscovery.GetShellPathFromRegistry(scriptInfo.RequiresApplicationID); ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, scriptInfo.ApplicationIDLineNumber, string.Empty, string.Empty, "RequiresShellIDInvalidForSingleShell"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } return(CommandDiscovery.CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope)); }
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); }
private CommandInfo GetInfoFromPath(string path) { CommandInfo info = null; if (!File.Exists(path)) { CommandDiscovery.discoveryTracer.TraceError("The path does not exist: {0}", new object[] { path }); } else { string a = null; try { a = Path.GetExtension(path); } catch (ArgumentException) { } if (a == null) { info = null; } else if (string.Equals(a, ".ps1", StringComparison.OrdinalIgnoreCase)) { if ((this.commandTypes & CommandTypes.ExternalScript) != 0) { string fileName = Path.GetFileName(path); CommandDiscovery.discoveryTracer.WriteLine("Command Found: path ({0}) is a script with name: {1}", new object[] { path, fileName }); info = new ExternalScriptInfo(fileName, path, this._context); } } else if ((this.commandTypes & CommandTypes.Application) != 0) { string name = Path.GetFileName(path); CommandDiscovery.discoveryTracer.WriteLine("Command Found: path ({0}) is an application with name: {1}", new object[] { path, name }); info = new ApplicationInfo(name, path, this._context); } } if ((info != null) && ((((PSLanguageMode)info.DefiningLanguageMode) == PSLanguageMode.ConstrainedLanguage) && (this._context.LanguageMode == PSLanguageMode.FullLanguage))) { info = null; } return(info); }
internal ExternalScriptInfo(ExternalScriptInfo other) : base(other) { this._path = string.Empty; this._path = other._path; this.CommonInitialization(); }
/// <summary> /// Construct a CommandMetadata object for a script file. /// </summary> /// <param name="path">The path to the script file.</param> public CommandMetadata(string path) { string scriptName = IO.Path.GetFileName(path); ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, path); Init(scriptInfo.ScriptBlock, path, false); _wrappedCommandType = CommandTypes.ExternalScript; }
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; }
internal DlrScriptCommandProcessor(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) : base(scriptInfo, context, useNewScope, sessionState) { Init(); }
internal CommandProcessorBase LookupCommandProcessor( CommandInfo commandInfo, CommandOrigin commandOrigin, bool?useLocalScope) { if (commandInfo.CommandType == CommandTypes.Alias && (commandOrigin == CommandOrigin.Internal || commandInfo.Visibility == SessionStateEntryVisibility.Public)) { AliasInfo aliasInfo = (AliasInfo)commandInfo; commandInfo = aliasInfo.ResolvedCommand; if (commandInfo == null) { CommandNotFoundException notFoundException = new CommandNotFoundException(aliasInfo.Name, (Exception)null, "AliasNotResolvedException", new object[1] { (object)aliasInfo.UnresolvedCommandName }); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } PSSQMAPI.IncrementData(CommandTypes.Alias); } CommandDiscovery.ShouldRun(this._context, (PSHost)this._context.EngineHostInterface, commandInfo, commandOrigin); CommandProcessorBase commandProcessorBase; switch (commandInfo.CommandType) { case CommandTypes.Function: case CommandTypes.Filter: FunctionInfo functionInfo = (FunctionInfo)commandInfo; ExecutionContext context1 = this._context; bool? nullable1 = useLocalScope; int num1 = nullable1.HasValue ? (nullable1.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(functionInfo, context1, num1 != 0); break; case CommandTypes.Cmdlet: commandProcessorBase = (CommandProcessorBase) new CommandProcessor((CmdletInfo)commandInfo, this._context); break; case CommandTypes.ExternalScript: ExternalScriptInfo externalScriptInfo = (ExternalScriptInfo)commandInfo; externalScriptInfo.SignatureChecked = true; try { if (!this._context.IsSingleShell) { ExternalScriptInfo scriptInfo = externalScriptInfo; bool?nullable2 = useLocalScope; int num2 = nullable2.HasValue ? (nullable2.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = this.CreateScriptProcessorForMiniShell(scriptInfo, num2 != 0); break; } ExternalScriptInfo scriptInfo1 = externalScriptInfo; RunspaceConfigForSingleShell runspaceConfiguration = this._context.RunspaceConfiguration as RunspaceConfigForSingleShell; bool?nullable3 = useLocalScope; int num3 = nullable3.HasValue ? (nullable3.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = this.CreateScriptProcessorForSingleShell(scriptInfo1, runspaceConfiguration, num3 != 0); break; } catch (ScriptRequiresSyntaxException ex) { CommandNotFoundException notFoundException = new CommandNotFoundException(ex.Message, (Exception)ex); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } catch (PSArgumentException ex) { CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)ex, "ScriptRequiresInvalidFormat", new object[0]); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } case CommandTypes.Application: commandProcessorBase = (CommandProcessorBase) new NativeCommandProcessor((ApplicationInfo)commandInfo, this._context); break; case CommandTypes.Script: ScriptInfo scriptInfo2 = (ScriptInfo)commandInfo; ExecutionContext context2 = this._context; bool? nullable4 = useLocalScope; int num4 = nullable4.HasValue ? (nullable4.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptInfo2, context2, num4 != 0); break; default: CommandNotFoundException notFoundException1 = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]); CommandDiscovery.tracer.TraceException((Exception)notFoundException1); throw notFoundException1; } PSSQMAPI.IncrementData(commandInfo.CommandType); commandProcessorBase.Command.CommandOriginInternal = commandOrigin; commandProcessorBase.Command.MyInvocation.InvocationName = commandInfo.Name; return(commandProcessorBase); }
internal PSModuleInfo CreateModule(string path, ExternalScriptInfo scriptInfo, IScriptExtent scriptPosition, SessionState ss, object privateData, params object[] arguments) { ArrayList list; return(this.CreateModuleImplementation(GetModuleName(path), path, scriptInfo, scriptPosition, ss, privateData, out list, arguments)); }
internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) { Version requiresPSVersion = scriptInfo.RequiresPSVersion; if ((requiresPSVersion != null) && !Utils.IsPSVersionSupported(requiresPSVersion)) { ScriptRequiresException exception = new ScriptRequiresException(scriptInfo.Name, requiresPSVersion, PSVersionInfo.PSVersion.ToString(), "ScriptRequiresUnmatchedPSVersion"); throw exception; } }
public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out ParseError[] errors) { ScriptBlockAst scriptBlockAst; Parser parser = new Parser(); ExternalScriptInfo externalScriptInfo = new ExternalScriptInfo(fileName, fileName); List<Token> tokens1 = new List<Token>(); try { scriptBlockAst = parser.Parse(fileName, externalScriptInfo.ScriptContents, tokens1, out errors); } catch (Exception exception1) { Exception exception = exception1; throw new ParseException(ParserStrings.UnrecoverableParserError, exception); } tokens = tokens1.ToArray(); return scriptBlockAst; }
/// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal ExternalScriptInfo(ExternalScriptInfo other) : base(other) { _path = other._path; CommonInitialization(); }
internal void RegisterScriptFile(ExternalScriptInfo scriptCommandInfo) { this.RegisterScriptFile(scriptCommandInfo.Path, scriptCommandInfo.ScriptContents); }
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 System.Management.Automation.Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) { string fileContent = Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; System.Management.Automation.Signature signature = SignatureHelper.GetSignature(path, fileContent); if ((signature.Status != SignatureStatus.Valid) && (script.OriginalEncoding != Encoding.Unicode)) { fileContent = Encoding.Unicode.GetString(Encoding.Unicode.GetPreamble()) + script.ScriptContents; System.Management.Automation.Signature signature2 = SignatureHelper.GetSignature(path, fileContent); if (signature2.Status == SignatureStatus.Valid) { signature = signature2; } } 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; } }
private static CommandProcessorBase CreateCommandProcessorForScript(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) { sessionState = sessionState ?? (scriptInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState); CommandProcessorBase base2 = GetScriptAsCmdletProcessor(scriptInfo, context, useNewScope, true, sessionState); if (base2 != null) { return base2; } return new DlrScriptCommandProcessor(scriptInfo, context, useNewScope, sessionState); }
private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState) { VerifyPSVersion(scriptInfo); this.VerifyRequiredModules(scriptInfo); IEnumerable<PSSnapInSpecification> requiresPSSnapIns = scriptInfo.RequiresPSSnapIns; if ((requiresPSSnapIns != null) && requiresPSSnapIns.Any<PSSnapInSpecification>()) { Collection<string> requiresMissingPSSnapIns = null; VerifyRequiredSnapins(requiresPSSnapIns, context, out requiresMissingPSSnapIns); if (requiresMissingPSSnapIns != null) { ScriptRequiresException exception = new ScriptRequiresException(scriptInfo.Name, requiresMissingPSSnapIns, "ScriptRequiresMissingPSSnapIns", true); throw exception; } } else if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { GetShellPathFromRegistry(scriptInfo.RequiresApplicationID); ScriptRequiresException exception2 = new ScriptRequiresException(scriptInfo.Name, string.Empty, string.Empty, "RequiresShellIDInvalidForSingleShell"); throw exception2; } return CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope, sessionState); }
private PSModuleInfo CreateModuleImplementation(string name, string path, object moduleCode, IScriptExtent scriptPosition, SessionState ss, object privateData, out ArrayList result, params object[] arguments) { if (ss == null) { ss = new SessionState(this._context, true, true); } SessionStateInternal engineSessionState = this._context.EngineSessionState; PSModuleInfo info = new PSModuleInfo(name, path, this._context, ss); ss.Internal.Module = info; info.PrivateData = privateData; bool flag = false; int newValue = 0; try { ScriptBlock scriptBlock; this._context.EngineSessionState = ss.Internal; ExternalScriptInfo scriptCommandInfo = moduleCode as ExternalScriptInfo; if (scriptCommandInfo != null) { scriptBlock = scriptCommandInfo.ScriptBlock; this._context.Debugger.RegisterScriptFile(scriptCommandInfo); } else { scriptBlock = moduleCode as ScriptBlock; if (scriptBlock != null) { PSLanguageMode?languageMode = scriptBlock.LanguageMode; scriptBlock = scriptBlock.Clone(true); scriptBlock.LanguageMode = languageMode; scriptBlock.SessionState = ss; } else if (moduleCode is string) { scriptBlock = ScriptBlock.Create(this._context, (string)moduleCode); } } if (scriptBlock == null) { throw PSTraceSource.NewInvalidOperationException(); } scriptBlock.SessionStateInternal = ss.Internal; InvocationInfo invocationInfo = new InvocationInfo(scriptCommandInfo, scriptPosition); info._definitionExtent = scriptBlock.Ast.Extent; ArrayList resultList = new ArrayList(); try { Pipe outputPipe = new Pipe(resultList); scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, invocationInfo, arguments ?? new object[0]); } catch (ExitException exception) { newValue = (int)exception.Argument; flag = true; } result = resultList; } finally { this._context.EngineSessionState = engineSessionState; } if (flag) { this._context.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue); } return(info); }
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; // Product binaries are always trusted if (SecuritySupport.IsProductBinary(path)) 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; #if !CORECLR // 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; } } #endif if (_executionPolicy == ExecutionPolicy.Unrestricted) { // 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[] { Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.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> /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter /// sets based on an argument list (so we can get the dynamic parameters.) /// </summary> internal override CommandInfo CreateGetCommandCopy(object[] argumentList) { ExternalScriptInfo copy = new ExternalScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList }; return copy; }
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; }
internal DlrScriptCommandProcessor(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) : base(scriptInfo, context, useNewScope, sessionState) { this._input = new ArrayList(); this.Init(); }
/// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable <string> allowedCommands, IEnumerable <string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } var retResult = evaluationResult as Hashtable; if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return(retResult); }
private void VerifyRequiredModules(ExternalScriptInfo scriptInfo) { if (scriptInfo.RequiresModules != null) { foreach (ModuleSpecification specification in scriptInfo.RequiresModules) { ErrorRecord error = null; ModuleCmdletBase.LoadRequiredModule(this.Context, null, specification, null, ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, out error); if (error != null) { ScriptRequiresException exception = new ScriptRequiresException(scriptInfo.Name, new Collection<string> { specification.Name }, "ScriptRequiresMissingModules", false, error); throw exception; } } } }
internal CommandProcessorBase CreateScriptProcessorForMiniShell(ExternalScriptInfo scriptInfo, bool useLocalScope, SessionStateInternal sessionState) { VerifyPSVersion(scriptInfo); this.VerifyRequiredModules(scriptInfo); if (string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { if ((scriptInfo.RequiresPSSnapIns != null) && scriptInfo.RequiresPSSnapIns.Any<PSSnapInSpecification>()) { Collection<string> pSSnapinNames = GetPSSnapinNames(scriptInfo.RequiresPSSnapIns); ScriptRequiresException exception = new ScriptRequiresException(scriptInfo.Name, pSSnapinNames, "ScriptRequiresMissingPSSnapIns", true); throw exception; } return CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope, sessionState); } if (string.Equals(this._context.ShellID, scriptInfo.RequiresApplicationID, StringComparison.OrdinalIgnoreCase)) { return CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope, sessionState); } string shellPathFromRegistry = GetShellPathFromRegistry(scriptInfo.RequiresApplicationID); ScriptRequiresException exception2 = new ScriptRequiresException(scriptInfo.Name, scriptInfo.RequiresApplicationID, shellPathFromRegistry, "ScriptRequiresUnmatchedShellId"); throw exception2; }
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; }
/// <summary> /// Reads content of file and converts it to a scriptblock /// </summary> /// <param name="filePath"></param> /// <param name="isLiteralPath"></param> /// <returns></returns> protected ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath) { //Make sure filepath doesn't contain wildcards if ((!isLiteralPath) && WildcardPattern.ContainsWildcardCharacters(filePath)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter), "filePath"); } if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension), "filePath"); } //Resolve file path string resolvedPath = PathResolver.ResolveProviderAndPath(filePath, isLiteralPath, this, false, RemotingErrorIdStrings.FilePathNotFromFileSystemProvider); //read content of file ExternalScriptInfo scriptInfo = new ExternalScriptInfo(filePath, resolvedPath, this.Context); // Skip ShouldRun check for .psd1 files. // Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file. // if (!filePath.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) { this.Context.AuthorizationManager.ShouldRunInternal(scriptInfo, CommandOrigin.Internal, this.Context.EngineHostInterface); } return scriptInfo.ScriptBlock; }
/// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable<string> allowedCommands, IEnumerable<string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } var retResult = evaluationResult as Hashtable; if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return retResult; }
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; } }
public CommandMetadata(string path) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection<Attribute>(); ExternalScriptInfo info = new ExternalScriptInfo(Path.GetFileName(path), path); this.Init(info.ScriptBlock, path, false); this._wrappedCommandType = CommandTypes.ExternalScript; }