private static void SetExecutionPolicy(ExecutionPolicy policy, ExecutionPolicyScope scope) { using (var ps = PowerShell.Create()) { ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", policy).AddParameter("Scope", scope); ps.Invoke(); } }
internal static string GetExecutionPolicy(ExecutionPolicy policy) { switch (policy) { case ExecutionPolicy.Unrestricted: return "Unrestricted"; case ExecutionPolicy.RemoteSigned: return "RemoteSigned"; case ExecutionPolicy.AllSigned: return "AllSigned"; case ExecutionPolicy.Restricted: return "Restricted"; case ExecutionPolicy.Bypass: return "Bypass"; } return "Restricted"; }
public void SetExecutionPolicy(ExecutionPolicy policy, ExecutionPolicyScope scope) { string command = string.Format(CultureInfo.InvariantCulture, "Set-ExecutionPolicy {0} -Scope {1} -Force", policy.ToString(), scope.ToString()); Invoke(command, inputs: null, outputResults: false); }
internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId) { #if UNIX throw new PlatformNotSupportedException(); #else string executionPolicy = "Restricted"; string preferenceKey = Utils.GetRegistryConfigurationPath(shellId); switch (policy) { case ExecutionPolicy.Restricted: executionPolicy = "Restricted"; break; case ExecutionPolicy.AllSigned: executionPolicy = "AllSigned"; break; case ExecutionPolicy.RemoteSigned: executionPolicy = "RemoteSigned"; break; case ExecutionPolicy.Unrestricted: executionPolicy = "Unrestricted"; break; case ExecutionPolicy.Bypass: executionPolicy = "Bypass"; break; } // Set the execution policy switch (scope) { case ExecutionPolicyScope.Process: { if (policy == ExecutionPolicy.Undefined) executionPolicy = null; Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); break; } case ExecutionPolicyScope.CurrentUser: { // They want to remove it if (policy == ExecutionPolicy.Undefined) { ConfigPropertyAccessor.Instance.RemoveExecutionPolicy(ConfigPropertyAccessor.PropertyScope.CurrentUser, shellId); CleanKeyParents(Registry.CurrentUser, preferenceKey); } else { ConfigPropertyAccessor.Instance.SetExecutionPolicy(ConfigPropertyAccessor.PropertyScope.CurrentUser, shellId, executionPolicy); } break; } case ExecutionPolicyScope.LocalMachine: { // They want to remove it if (policy == ExecutionPolicy.Undefined) { ConfigPropertyAccessor.Instance.RemoveExecutionPolicy(ConfigPropertyAccessor.PropertyScope.SystemWide, shellId); CleanKeyParents(Registry.LocalMachine, preferenceKey); } else { ConfigPropertyAccessor.Instance.SetExecutionPolicy(ConfigPropertyAccessor.PropertyScope.SystemWide, shellId, executionPolicy); } break; } } #endif }
public HmrcService(EmployerLevyConfiguration configuration, IHttpClientWrapper httpClientWrapper, ITokenServiceApiClient tokenServiceApiClient, [RequiredPolicy(HmrcExecutionPolicy.Name)] ExecutionPolicy executionPolicy, ICacheProvider cacheProvider, IAzureAdAuthenticationService azureAdAuthenticationService) { _configuration = configuration; _httpClientWrapper = httpClientWrapper; _tokenServiceApiClient = tokenServiceApiClient; _executionPolicy = executionPolicy; _cacheProvider = cacheProvider; _azureAdAuthenticationService = azureAdAuthenticationService; _httpClientWrapper.BaseUrl = _configuration.Hmrc.BaseUrl; _httpClientWrapper.AuthScheme = "Bearer"; _httpClientWrapper.MediaTypeWithQualityHeaderValueList = new List<MediaTypeWithQualityHeaderValue> { new MediaTypeWithQualityHeaderValue("application/vnd.hmrc.1.0+json") }; }
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); }
internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId) { string str = "Restricted"; string registryConfigurationPath = Utils.GetRegistryConfigurationPath(shellId); switch (policy) { case ExecutionPolicy.Unrestricted: str = "Unrestricted"; break; case ExecutionPolicy.RemoteSigned: str = "RemoteSigned"; break; case ExecutionPolicy.AllSigned: str = "AllSigned"; break; case ExecutionPolicy.Restricted: str = "Restricted"; break; case ExecutionPolicy.Bypass: str = "Bypass"; break; } switch (scope) { case ExecutionPolicyScope.Process: if (policy == ExecutionPolicy.Undefined) { str = null; } Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", str); return; case ExecutionPolicyScope.CurrentUser: if (policy != ExecutionPolicy.Undefined) { using (RegistryKey key2 = Registry.CurrentUser.CreateSubKey(registryConfigurationPath)) { key2.SetValue("ExecutionPolicy", str, RegistryValueKind.String); return; } } using (RegistryKey key = Registry.CurrentUser.OpenSubKey(registryConfigurationPath, true)) { if ((key != null) && (key.GetValue("ExecutionPolicy") != null)) { key.DeleteValue("ExecutionPolicy"); } } CleanKeyParents(Registry.CurrentUser, registryConfigurationPath); return; case ExecutionPolicyScope.LocalMachine: break; default: return; } if (policy == ExecutionPolicy.Undefined) { using (RegistryKey key3 = Registry.LocalMachine.OpenSubKey(registryConfigurationPath, true)) { if ((key3 != null) && (key3.GetValue("ExecutionPolicy") != null)) { key3.DeleteValue("ExecutionPolicy"); } } CleanKeyParents(Registry.LocalMachine, registryConfigurationPath); } else { using (RegistryKey key4 = Registry.LocalMachine.CreateSubKey(registryConfigurationPath)) { key4.SetValue("ExecutionPolicy", str, RegistryValueKind.String); } } }
public static void UpdateExecutionPolicy(string shellId, ExecutionPolicy executionPolicy) { if (isWinSQMEnabled && shellId.Equals(Utils.DefaultPowerShellShellID, StringComparison.OrdinalIgnoreCase)) { lock (syncObject) { dataValueCache[0x2098] = (int) executionPolicy; } } }
public PipelineBuilder WithExecutionPolicy(ExecutionPolicy policy) { _actions.Add(x => x.WithExecutionPolicy(policy)); return(this); }
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; }
public void SetExecutionPolicy(ExecutionPolicy policy, ExecutionPolicyScope scope) { string command = string.Format(CultureInfo.InvariantCulture, "Set-ExecutionPolicy {0} -Scope {1} -Force", policy, scope); Invoke(command, inputs: null, outputResults: false); }
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; }
private void SetExecutionPolicy(ExecutionPolicy policy, ExecutionPolicyScope scope) { using (PowerShell ps = PowerShell.Create()) { ps.Runspace = _runspace; ps.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", policy) .AddParameter("Scope", scope); ps.Invoke(); } }
/// <summary> /// Runs a single expression in the script. /// </summary> /// <param name="expression">The expression to run.</param> public TestStatistics Run(SExpression expression) { if (expression.IsCallTo("module")) { var module = Assembler.AssembleModule(expression, out string moduleId); var instance = Wasm.Interpret.ModuleInstance.Instantiate( module, importer, policy: ExecutionPolicy.Create(maxMemorySize: 0x1000), compiler: Compiler); moduleInstances.Add(instance); if (moduleId != null) { moduleInstancesByName[moduleId] = instance; } if (module.StartFunctionIndex.HasValue) { instance.Functions[(int)module.StartFunctionIndex.Value].Invoke(Array.Empty <object>()); } return(TestStatistics.Empty); } else if (expression.IsCallTo("register")) { var tail = expression.Tail; var name = Assembler.AssembleString(tail[0], Log); tail = tail.Skip(1).ToArray(); var moduleId = Assembler.AssembleLabelOrNull(ref tail); if (moduleId == null) { importer.RegisterImporter(name, new ModuleExportsImporter(moduleInstances[moduleInstances.Count - 1])); } else { importer.RegisterImporter(name, new ModuleExportsImporter(moduleInstancesByName[moduleId])); } return(TestStatistics.Empty); } else if (expression.IsCallTo("invoke") || expression.IsCallTo("get")) { RunAction(expression); return(TestStatistics.SingleSuccess); } else if (expression.IsCallTo("assert_return")) { var results = RunAction(expression.Tail[0]); var expected = expression.Tail .Skip(1) .Zip(results, (expr, val) => EvaluateConstExpr(expr, val.GetType())) .ToArray(); if (expected.Length != results.Count) { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced result ", string.Join(", ", results), "; expected ", string.Join(", ", expected), ".", Assembler.Highlight(expression))); return(TestStatistics.SingleFailure); } bool failures = false; for (int i = 0; i < expected.Length; i++) { if (!object.Equals(results[i], expected[i])) { if (AlmostEquals(results[i], expected[i])) { Log.Log( new LogEntry( Severity.Warning, "rounding error", "action produced result ", results[i].ToString(), "; expected ", expected[i].ToString(), ".", Assembler.Highlight(expression))); } else { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced result ", results[i].ToString(), "; expected ", expected[i].ToString(), ".", Assembler.Highlight(expression))); failures = true; } } } return(failures ? TestStatistics.SingleFailure : TestStatistics.SingleSuccess); } else if (expression.IsCallTo("assert_trap") || expression.IsCallTo("assert_exhaustion")) { var expected = Assembler.AssembleString(expression.Tail[1], Log); bool caught = false; Exception exception = null; try { if (expression.Tail[0].IsCallTo("module")) { Run(expression.Tail[0]); } else { RunAction(expression.Tail[0], false); } } catch (TrapException ex) { caught = ex.SpecMessage == expected; exception = ex; } catch (PixieException) { throw; } catch (Exception ex) { caught = false; exception = ex; } if (caught) { return(TestStatistics.SingleSuccess); } else { if (exception == null) { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action should have trapped, but didn't.", Assembler.Highlight(expression))); } else { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action trapped as expected, but with an unexpected exception. ", exception.ToString(), Assembler.Highlight(expression))); } return(TestStatistics.SingleFailure); } } else if (expression.IsCallTo("assert_return_canonical_nan")) { var results = RunAction(expression.Tail[0]); bool isCanonicalNaN; if (results.Count != 1) { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced ", results.Count.ToString(), " results (", string.Join(", ", results), "); expected a single canonical NaN.", Assembler.Highlight(expression))); return(TestStatistics.SingleFailure); } else if (results[0] is double) { var val = Interpret.ValueHelpers.ReinterpretAsInt64((double)results[0]); isCanonicalNaN = val == Interpret.ValueHelpers.ReinterpretAsInt64((double)FloatLiteral.NaN(false)) || val == Interpret.ValueHelpers.ReinterpretAsInt64((double)FloatLiteral.NaN(true)); } else if (results[0] is float) { var val = Interpret.ValueHelpers.ReinterpretAsInt32((float)results[0]); isCanonicalNaN = val == Interpret.ValueHelpers.ReinterpretAsInt32((float)FloatLiteral.NaN(false)) || val == Interpret.ValueHelpers.ReinterpretAsInt32((float)FloatLiteral.NaN(true)); } else { isCanonicalNaN = false; } if (isCanonicalNaN) { return(TestStatistics.SingleSuccess); } else { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced ", results[0].ToString(), "; expected a single canonical NaN.", Assembler.Highlight(expression))); return(TestStatistics.SingleFailure); } } else if (expression.IsCallTo("assert_return_arithmetic_nan")) { var results = RunAction(expression.Tail[0]); bool isNaN; if (results.Count != 1) { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced ", results.Count.ToString(), " results (", string.Join(", ", results), "); expected a single NaN.", Assembler.Highlight(expression))); return(TestStatistics.SingleFailure); } else if (results[0] is double) { isNaN = double.IsNaN((double)results[0]); } else if (results[0] is float) { isNaN = float.IsNaN((float)results[0]); } else { isNaN = false; } if (isNaN) { return(TestStatistics.SingleSuccess); } else { Log.Log( new LogEntry( Severity.Error, "assertion failed", "action produced ", results[0].ToString(), "; expected a single NaN.", Assembler.Highlight(expression))); return(TestStatistics.SingleFailure); } } else { Log.Log( new LogEntry( Severity.Warning, "unknown script command", Quotation.QuoteEvenInBold( "expression ", expression.Head.Span.Text, " was not recognized as a known script command."), Assembler.Highlight(expression))); return(TestStatistics.SingleUnknown); } }
public static TPipeline WithExecutionPolicy <TPipeline>(this TPipeline pipeline, ExecutionPolicy policy) where TPipeline : IPipeline { pipeline.ExecutionPolicy = policy; return(pipeline); }
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); // 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); } } // WLDP and Applocker takes priority over powershell exeuction policy. // See if they want to bypass the authorization manager if (_executionPolicy == ExecutionPolicy.Bypass) { return(true); } 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[] { 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); }
public static void SetExecutionPolicy(this Runspace runspace, ExecutionPolicy policy, ExecutionPolicyScope scope) { string command = string.Format(CultureInfo.InvariantCulture, "Set-ExecutionPolicy {0} -Scope {1} -Force", policy.ToString(), scope.ToString()); runspace.Invoke(command, null, false); }
public RedisConnection(string connectionString) { this.policy = new ExecutionPolicy(); this.connectionString = connectionString; }